Search code examples
jenkinsjenkins-pipeline

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


Solution

  • 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'