I want to add a Build step with the Groovy plugin to read a file and trigger a build fail depending on the content of the file.
How can I inject the workspace file path in the groovy plugin ?
myFileDirectory = // Get workspace filepath here ??? myFileName = "output.log" myFile = new File(myFileDirectory + myFileName) lastLine = myFile.readLines().get(myFile.readLines().size().toInteger() - 1) if (lastLine ==~ /.Fatal Error.*/ ){ println "Fatal error found" System.exit(1) } else{ println "nothing to see here" }
In the first stage we create a variable called data that holds some text and the we use the writeFile function to write it out to a file. Then we execute ls as an external program using sh. In the second stage we use the readFile function to read in the content of the file.
To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd() def version = readFile "${env.WORKSPACE}/version.txt"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With