Where does Jenkins store the environment variables ? How to save them for next builds?

Viewed 163

I have the following Jenkinsfile, I can save the environment variables to use them later in an other build when I restart the job from stage 2

pipeline {
    agent any
    options {
        preserveStashes()
    }
    stages {
        stage('Stage 1') {
            steps {
                script {
                    env.TEST = 'test'
                    // do something ...
                }
            }
        }
        stage('Stage 2') {
            steps {
                script {
                   try {
                       unstash 'envFile'
                    } catch(e) {
                       // do something
                    }
                       println env.TEST
                }
            }
        }
    }
    post {
        always {
            script {
                sh 'printenv >envFile'
                stash name: 'envFile', includes: 'envFile'
            }
        }
    }
}

It works correctly ('test' is dispalyed in the console output) both when I build the job and when I restart it from 'stage 2'. It means that env.TEST variable was saved thanks to stash, unstash and preserveStashes.

BUT, it is working too when I stash an empty file (replacing sh 'printenv >envFile' by sh 'touch envFile'). It means that Jenkins saves the environment variables when stashing and unstashing files, is that correct ?

An other question: where does Jenkins save the environment variables, is there a specific file containning the env variables ?

1 Answers

Update

Environment variables are systematically saved when a build is restarted from a stage . No need to stash and unstash files! More details about restart from stage here.

Related