Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What are all environment variables use in Jenkins?

Commonly used variable types in Jenkins include env (environment variables), currentBuild , params (parameters), and docker (access to Docker functions). Jenkins saves all current environment variables in list form.

How do I get environment variables in Groovy Jenkins?

In "Manage Jenkins" -> "Configure System" -> "Global Properties" -> "Environment Variables" I added "ALL_NODES_ENVVAR".


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.


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


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

You can accomplish the result using sh/bat step and readFile:

node {
    sh 'env > env.txt'
    readFile('env.txt').split("\r?\n").each {
        println it
    }
}

Unfortunately env.getEnvironment() returns very limited map of environment variables.


Why all this complicatedness?

sh 'env'

does what you need (under *nix)


Cross-platform way of listing all environment variables:

if (isUnix()) {
    sh env
}
else {
    bat set
}

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.