Create a file with some content using Groovy in Jenkins pipeline Create a file with some content using Groovy in Jenkins pipeline jenkins jenkins

Create a file with some content using Groovy in Jenkins pipeline


Jenkins Pipeline provides writeFile step that can be used to write a file inside job's workspace.

Take a look at following example:

node {    writeFile file: 'groovy1.txt', text: 'Working with files the Groovy way is easy.'    sh 'ls -l groovy1.txt'    sh 'cat groovy1.txt'}

Running this pipeline scripts generates following output:

[Pipeline] nodeRunning on Jenkins in /var/jenkins_home/workspace/test-pipeline[Pipeline] {[Pipeline] writeFile[Pipeline] sh[test-pipeline] Running shell script+ ls -l groovy1.txt-rw-r--r-- 1 jenkins jenkins 42 Jul  8 16:38 groovy1.txt[Pipeline] sh[test-pipeline] Running shell script+ cat groovy1.txtWorking with files the Groovy way is easy.[Pipeline] }[Pipeline] // node[Pipeline] End of PipelineFinished: SUCCESS

Using Java File

As Jon S mentioned in the comment, Java new File("${env.WORKSPACE}/groovy1.txt") will work only if your node step is executed on master node - if it gets executed on slave node then your pipeline code will fail. You can check following Stack Overflow thread for more information:

In jenkins job, create file using system groovy in current workspace