JamesThomasMoon
JamesThomasMoon

Reputation: 7124

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

Given a jenkins build pipeline, jenkins injects a variable env into the node{}. Variable env holds environment variables and values.

I want to print all env properties within the jenkins pipeline. However, I do no not know all env properties ahead of time.

For example, environment variable BRANCH_NAME can be printed with code

node {
    echo "BRANCH_NAME is " + ${env.BRANCH_NAME}
    ...

But again, I don't know all variables ahead of time. I want code that handles that, something like

node {
    for(e in env){
        echo e + " is " + ${e}
    }
    ...

which would echo something like

 BRANCH_NAME is myBranch2
 CHANGE_ID is 44
 ...

I used Jenkins 2.1 for this example.

Upvotes: 166

Views: 292642

Answers (21)

Terry
Terry

Reputation: 14219

Cross-platform way of listing all environment variables:

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

Upvotes: 17

kh0ma
kh0ma

Reputation: 13

If we don't want to have node assigned but print env vars this can help:

print env.getEnvironment()

Tested on Jenkins version: Jenkins 2.426.1

Upvotes: 1

Anushka Fernando
Anushka Fernando

Reputation: 79

You can use sh 'printenv'

 stage('1') {
    sh "printenv" 
 }

Upvotes: 3

LawrenceMouarkach
LawrenceMouarkach

Reputation: 110

Includes both system and build environment vars:

sh script: "printenv", label: 'print environment variables'

Upvotes: 4

Jon X
Jon X

Reputation: 9133

ref: https://www.jenkins.io/doc/pipeline/tour/environment/

node {
    sh 'printenv'
}

Upvotes: 3

Muhammad Maroof
Muhammad Maroof

Reputation: 303

The easiest and quickest way is to use following url to print all environment variables

http://localhost:8080/env-vars.html/

Upvotes: 7

Assault72
Assault72

Reputation: 79

Show all variable in Windows system and Unix system is different, you can define a function to call it every time.

def showSystemVariables(){    
   if(isUnix()){
     sh 'env'
   } else {
     bat 'set'
   }
}

I will call this function first to show all variables in all pipline script

stage('1. Show all variables'){
     steps {
         script{            
              showSystemVariables()
         }
     }
} 

Upvotes: 6

Dmitriy Tarasevich
Dmitriy Tarasevich

Reputation: 1242

You can get all variables from your jenkins instance. Just visit:

  • ${jenkins_host}/env-vars.html
  • ${jenkins_host}/pipeline-syntax/globals

Upvotes: 2

Prosenjit Sen
Prosenjit Sen

Reputation: 366

I found this is the most easiest way:

pipeline {
    agent {
        node {
            label 'master'
        }
    }   
    stages {
        stage('hello world') {
            steps {
                sh 'env'
            }
        }
    }
}

Upvotes: 2

zett42
zett42

Reputation: 27756

The pure Groovy solutions that read the global env variable don't print all environment variables (e. g. they are missing variables from the environment block, from withEnv context and most of the machine-specific variables from the OS). Using shell steps it is possible to get a more complete set, but that requires a node context, which is not always wanted.

Here is a solution that uses the getContext step to retrieve and print the complete set of environment variables, including pipeline parameters, for the current context.

Caveat: Doesn't work in Groovy sandbox. You can use it from a trusted shared library though.

def envAll = getContext( hudson.EnvVars )
echo envAll.collect{ k, v -> "$k = $v" }.join('\n')

Upvotes: 11

dsaydon
dsaydon

Reputation: 4769

if you really want to loop over the env list just do:

def envs = sh(returnStdout: true, script: 'env').split('\n')
envs.each { name  ->
    println "Name: $name"
}

Upvotes: 2

Andrey Regentov
Andrey Regentov

Reputation: 3737

Why all this complicatedness?

sh 'env'

does what you need (under *nix)

Upvotes: 15

claudod
claudod

Reputation: 865

I suppose that you needed that in form of a script, but if someone else just want to have a look through the Jenkins GUI, that list can be found by selecting the "Environment Variables" section in contextual left menu of every build Select project => Select build => Environment Variables

enter image description here

Upvotes: 1

Daniel
Daniel

Reputation: 9464

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.

Upvotes: 11

Roman
Roman

Reputation: 857

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}

Upvotes: 0

Wimateeka
Wimateeka

Reputation: 2686

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.

Upvotes: 165

Jon Lauridsen
Jon Lauridsen

Reputation: 2678

I use Blue Ocean plugin and did not like each environment entry getting its own block. I want one block with all the lines.

Prints poorly:

sh 'echo `env`'

Prints poorly:

sh 'env > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
    println i
}

Prints well:

sh 'env > env.txt'
sh 'cat env.txt'

Prints well: (as mentioned by @mjfroehlich)

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

Upvotes: 8

Eddie
Eddie

Reputation: 1161

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)
        }
    }

Upvotes: 3

mjfroehlich
mjfroehlich

Reputation: 1188

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

Upvotes: 97

Omri Spector
Omri Spector

Reputation: 2561

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

Upvotes: 46

luka5z
luka5z

Reputation: 7805

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.

Upvotes: 15

Related Questions