How to read jenkins old build injected environment variables

Viewed 1711

I am trying to read old jenkins build environment variables (to extract the downstream jobs) using groovy script. I am currently using

build.getEnvVars()

But getting deprecated warning. Could someone tell me what's the best method to read these old build environment variables?

2 Answers

Using pipeline, here's a way to propagate all the environment variables from a downstream so you can use the getBuildVariables() method, including any edits made before the call to makeEnvAvailable in the downstream job.

Note: Requires script approval for method org.jenkinsci.plugins.workflow.support.actions.EnvironmentAction getEnvironment

// Downstream job 'down' Jenkinsfile
@NonCPS
def makeEnvAvailable() {
    // Goes through every environment variable and sets it again
    // This will populate 'downstreamBuild.getBuildVariables()'
    env.getEnvironment().each { k,v -> env.setProperty(k, v)  }
}

pipeline {
    agent any
    parameters {
        booleanParam(name: 'QUICK_BUILD', defaultValue: false,
            description: 'Skip running git clean and perform a quick build' )
    }
    environment {
        TEST_VER="${TEST_VER}"
        VIVARIUM="/tools/pancake"
    }
    stages {
        stage("Env set") {
            steps { 
                script {
                    // Will be visible upstream regardless
                    env.THIS_IS_A_TEST = "test_env_set"

                    // Not set on env. Not available
                    ANOTHER_TEST = "not_env_set"

                    // Does not modify the param or env. Not available
                    QUICK_BUILD = "not_actually_modifying_params"

                    // Set to the same value, but now available upstream
                    env.GIT_COMMIT = env.GIT_COMMIT

                    // Makes every other environment variable available
                    makeEnvAvailable()
                }
            }
        }
    }
}

// Upstream job 'Up' Jenkinsfile
pipeline {
    agent any
    stages {
        stage ("Downstream") {
            steps {
                script {
                    def down = build job: "down"
                    echo down.getBuildVariables().toString()
                    echo down.buildVariables
                }
            }
        }
    }
}

Your upstream job now should have access to every environment variable from your downstream job.

Related