3

How can I write out environment variable(s) with writeFile in Jenkins pipelines? It seems such an easy task but I can't find any documentation on how to get it to work.

I tried $VAR, ${VAR} and ${env.VAR}, nothing works...?

F.P
  • 17,421
  • 34
  • 123
  • 189

1 Answers1

7

In a declarative pipeline (using a scripted block for writeFile) it will look like this:

pipeline {
    agent any

    environment {
        SENTENCE = 'Hello World\n'
    }

    stages {
        stage('Write') {
            steps {
                script {
                    writeFile file: 'script.txt', text: env.SENTENCE
                }
            }
        }
        
        stage('Verify') {
            steps {
                sh 'cat script.txt'
            }
        }
    }
}

Output:

...
[Pipeline] { (Verify)
[Pipeline] sh
[test] Running shell script
+ cat script.txt
Hello World
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

If you want to avoid groovy, this will work too:

writeFile file: 'script.txt', text: "${SENTENCE}"

To combine your env var with text you can do:

...
environment {
    SENTENCE = 'Hello World'
}
...

writeFile file: 'script.txt', text: env.SENTENCE + ' is my newest sentence!\n'
Neuron
  • 5,141
  • 5
  • 38
  • 59
lvthillo
  • 28,263
  • 13
  • 94
  • 127
  • How would I combine variables with literal text? – F.P Mar 02 '18 at 06:41
  • @FlorianPeschka Updated the answer – lvthillo Mar 02 '18 at 06:44
  • I'm not sure we should discuss here, but I get a Nullpointer exception now at this line: https://github.com/jenkinsci/jenkins/blob/stable-2.89/core/src/main/java/hudson/FilePath.java#L1923 – F.P Mar 02 '18 at 07:14
  • @FlorianPeschka Can you share your pipeline (or the part where it fails) + you are using the latest version of the plugin? – lvthillo Mar 02 '18 at 07:19
  • It appears `env.GIT_COMMIT` (what I want to write) is `null`. I suspect thats a different issue with my pipeline though. – F.P Mar 02 '18 at 07:25
  • 1
    The env var of GIT_COMMIT is only set when you use the git plugin. BUT for pipelines this behaviour is a bit different. You really have to define the use as explained here: https://stackoverflow.com/questions/46317774/jenkins-git-environment-variables-not-set-in-pipeline – lvthillo Mar 02 '18 at 07:48