How to list all `env` properties within jenkins pipeline job?

前端 未结 15 1690
情深已故
情深已故 2020-11-30 22:20

Given a jenkins 2.1 build pipeline, jenkins injects a env variable into the node{}. For example, BRANCH_NAME can be accessed with

相关标签:
15条回答
  • 2020-11-30 22:33

    Here's a quick script you can add as a pipeline job to list all environment variables:

    node {
        echo(env.getEnvironment().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
        echo(System.getenv().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
    }
    

    This will list both system and Jenkins variables.

    0 讨论(0)
  • 2020-11-30 22:33

    The answers above, are now antiquated due to new pipeline syntax. Below prints out the environment variables.

    script {
            sh 'env > env.txt'
            String[] envs = readFile('env.txt').split("\r?\n")
    
            for(String vars: envs){
                println(vars)
            }
        }
    
    0 讨论(0)
  • 2020-11-30 22:37

    According to Jenkins documentation for declarative pipeline:

    sh 'printenv'
    

    For Jenkins scripted pipeline:

    echo sh(script: 'env|sort', returnStdout: true)
    

    The above also sorts your env vars for convenience.

    0 讨论(0)
  • 2020-11-30 22:37

    another way to get exactly the output mentioned in the question:

    envtext= "printenv".execute().text
    envtext.split('\n').each
    {   envvar=it.split("=")
        println envvar[0]+" is "+envvar[1]
    }
    

    This can easily be extended to build a map with a subset of env vars matching a criteria:

    envdict=[:]
    envtext= "printenv".execute().text
    envtext.split('\n').each
    {   envvar=it.split("=")
        if (envvar[0].startsWith("GERRIT_"))
            envdict.put(envvar[0],envvar[1])
    }    
    envdict.each{println it.key+" is "+it.value}
    
    0 讨论(0)
  • 2020-11-30 22:39

    Another, more concise way:

    node {
        echo sh(returnStdout: true, script: 'env')
        // ...
    }
    

    cf. https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#code-sh-code-shell-script

    0 讨论(0)
  • 2020-11-30 22:41

    The following works:

    @NonCPS
    def printParams() {
      env.getEnvironment().each { name, value -> println "Name: $name -> Value $value" }
    }
    printParams()
    

    Note that it will most probably fail on first execution and require you approve various groovy methods to run in jenkins sandbox. This is done in "manage jenkins/in-process script approval"

    The list I got included:

    • BUILD_DISPLAY_NAME
    • BUILD_ID
    • BUILD_NUMBER
    • BUILD_TAG
    • BUILD_URL
    • CLASSPATH
    • HUDSON_HOME
    • HUDSON_SERVER_COOKIE
    • HUDSON_URL
    • JENKINS_HOME
    • JENKINS_SERVER_COOKIE
    • JENKINS_URL
    • JOB_BASE_NAME
    • JOB_NAME
    • JOB_URL
    0 讨论(0)
提交回复
热议问题