F.P
F.P

Reputation: 17831

How to write out environment variable with Jenkins pipeline

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...?

Upvotes: 3

Views: 6399

Answers (1)

lvthillo
lvthillo

Reputation: 30723

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'

Upvotes: 7

Related Questions