Search code examples
jenkinsjenkins-declarative-pipeline

Are declarative pipeline environment variables are shared across different stages?


Is it expected that environmental variables can be accessed from different stages of a declarative pipeline?

Here is my code:

pipeline {
    agent any
    stages {
        stage('start') {
            environment {
               tool="alpha"
            }
            steps {
                script {
                   tool="beta"
                   echo tool
                }
            }
        }
        stage('end') {
            steps {
                echo tool
            }
        }
    }
}

Output:

both echo are printing "beta"

So is it expected that tool variable declared in stage('start') are accessible in stage('end') too?


Solution

  • echo tool doesn't print tool environment variable, it print a Groovy variable. And you set it to "beta" without defining it first, which Jenkins magically transformed into a global Groovy (not environment) variable for you.

    Try with

    sh script: 'echo $tool'
    

    or

    echo env.tool
    

    to test what the environment variables do.