book
  • README
  • cheatsheet
    • bash
      • builtin
      • syntactic sugar
      • cmd
      • havefun
    • text-processing
      • awk
      • sed
      • html
      • json
      • regex
      • unicode
    • osx
    • curl
    • tricky
    • widget
    • proxy
    • colors
    • math
    • media
    • ssl
      • keystore
      • verification
      • server
      • client
      • tricky
    • windows
      • powershell
      • choco
      • wsl
      • wt
      • shortcut
      • clsid
      • env
      • shell:folder
  • vim
    • nvim
    • install
    • color
    • plugins
      • usage
      • other plugins
      • deprecated
    • tricky
    • viml
    • windows
    • troubleshooting
  • devops
    • admin tools
    • ssh
    • git
      • config
      • alias
      • submodule
      • eol
      • example
      • gerrit
        • gerrit API
      • github
      • troubleshooting
      • tricky
      • statistics
    • pre-commit
    • release-tools
    • tmux
      • cheatsheet
    • ansible
    • vault
    • artifactory
      • api
      • cli
      • aql
      • nginx cert
    • klocwork
      • kwadmin
      • kwserver
      • api
      • q&a
    • elk
    • mongodb
    • android
    • mobile
  • jenkins
    • config
      • windows
    • appearance
    • troubleshooting
    • jenkinsfile
      • utility
      • parallel
      • build
      • envvar
      • properties
      • trigger
      • node
    • script
      • job
      • build
      • stage
      • agent
      • security & authorization
      • exception
      • monitor
      • tricky
    • api
      • blueocean
    • cli
    • plugins
      • kubernetes
      • docker
      • shared-libs
      • lockable-resource
      • ansicolor
      • badge
      • groovy-postbuild
      • simple-theme
      • customizable-header
      • artifactory
      • jira-steps
      • job-dsl
      • build-timeline
      • crumbIssuer
      • coverage
      • uno-choice
      • tricky
  • virtualization
    • kubernetes
      • init
        • kubespray
        • kubeadm
          • environment
          • crio v1.30.4
          • docker v1.15.3
          • HA
        • addons
        • etcd
      • kubectl
        • pod
        • deploy
        • replicasets
        • namespace
        • secrets
      • node
      • certificates
      • events
      • kubeconfig
      • kubelet
      • troubleshooting
      • cheatsheet
      • auth
      • api
      • tools
        • monitor
        • helm
        • network
        • minikube
    • docker
      • run & exec
      • voume
      • remove
      • show info
      • dockerfile
      • dockerd
      • tricky
      • troubleshooting
      • windows
    • crio
    • podman
  • ai
    • prompt
  • osx
    • apps
      • init
      • brew
    • defaults
    • system
    • network
    • script
    • tricky
  • linux
    • devenv
    • util
      • time & date
      • output formatting
      • params
      • tricky
    • nutshell
    • disk
    • network
    • troubleshooting
    • system
      • apt/yum/snap
      • authorization
      • apps
      • x11
    • ubuntu
      • systemctl
      • x
    • rpi
  • programming
    • groovy
    • python
      • config
      • basic
      • list
      • pip
      • q&a
    • others
    • archive
      • angular
      • maven
      • mysql
        • installation
        • logs
      • ruby
        • rubyInstallationQ&A
  • tools
    • fonts
    • html & css
    • Jira & Confluence
    • node & npm
      • gitbook
      • hexo
      • github.page
      • code themes
    • app
      • microsoft office
      • vscode
      • virtualbox
      • iterm2
      • browser
      • skype
      • teamviewer
      • others
  • quotes
  • english
Powered by GitBook
On this page
  • environment variables
  • global environment
  • setup environment

Was this helpful?

  1. jenkins
  2. jenkinsfile

envvar

PreviousbuildNextproperties

Last updated 1 year ago

Was this helpful?

references:

environment variables

get current customized environment

println currentBuild.getBuildVariables()?.MY_ENV

get downstream build environment

def res = build job: 'downstream-job', propagate: false
println res.getBuildVariables()?.MY_ENV

get previous build environment

println currentBuild.getPreviousBuild().getBuildVariables()?.MY_ENV

global environment

System.getenv()

To get the Jenkins Global environment variables

System.getenv().collect { k, v -> "$k=$v" }.join('\n>>> ')
  • result

    PATH=/opt/java/openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    >>> PWD=/
    >>> LANGUAGE=en_US:en
    >>> LC_ALL=en_US.UTF-8
    >>> SHLVL=0
    >>> JAVA_HOME=/opt/java/openjdk
    >>> JENKINS_VERSION=2.284
    >>> JAVA_VERSION=jdk8u282-b08
    >>> JENKINS_UC=https://updates.jenkins.io
    >>> JAVA_OPTS=-Xms48G -Xmx144G -Duser.timezone='America/Los_Angeles' -XX:+UseG1GC -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox allow-same-origin allow-scripts; default-src 'self'; script-src * 'unsafe-eval'; img-src *; style-src * 'unsafe-inline'; font-src *;" -Djenkins.slaves.NioChannelSelector.disabled=true -Djenkins.slaves.JnlpSlaveAgentProtocol3.enabled=false -Djava.awt.headless=true -Djenkins.security.ClassFilterImpl.SUPPRESS_WHITELIST=true -Dhudson.model.ParametersAction.keepUndefinedParameters=true -Dcom.cloudbees.workflow.rest.external.ChangeSetExt.resolveCommitAuthors=true -Djenkins.install.runSetupWizard=true -Dpermissive-script-security.enabled=true -DsessionTimeout=1440 -DsessionEviction=43200 -Dgroovy.grape.report.downloads=true -Divy.message.logger.level=4 -Dhudson.plugins.active_directory.ActiveDirectorySecurityRealm.forceLdaps=false
    ...

sh 'env' or sh 'printenv'

running script in agent, so the result is the agent system environment variables + job itself variables (i.e: params and ${env.JENKINS_xxx})

sh 'env'

// or
sh 'printenv | sort'
  • result

    AGENT_WORKDIR=/home/devops/agent
    BUILD_DISPLAY_NAME=#1332
    BUILD_ID=1332
    BUILD_NUMBER=1332
    BUILD_TAG=jenkins-marslo-sandbox-1332
    BUILD_TIMESTAMP=2021-05-07 00:02:22 PDT
    JENKINS_HOME=/var/jenkins_home
    JOB_BASE_NAME=sandbox
    MY_TEST=works                   // particular environment setup in agent itself (linux)
    PATH=/it/my/test:/test/again:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    SHLVL=1
    TERM=xterm
    ...

env.getEnvironment() or currentBuild.getRawBuild().getEnvironment()

pure Jenkins job's environment variables (and parameters) references:

println currentBuild.getRawBuild().getEnvironment()

// or
println prettyPrint( toJson(env.getEnvironment()) )
  • result

    {BUILD_DISPLAY_NAME=#1332, BUILD_ID=1332, BUILD_NUMBER=1332, BUILD_TAG=jenkins-marslo-sandbox-1332, BUILD_TIMESTAMP=2021-05-07 00:02:22 PDT, CLASSPATH=, HUDSON_HOME=/var/jenkins_home, JENKINS_HOME=/var/jenkins_home, ...}
    
    // or
    
    {
      "BUILD_DISPLAY_NAME": "#1335",
      "BUILD_ID": "1335",
      "BUILD_NUMBER": "1335",
      "BUILD_TAG": "jenkins-marslo-sandbox-1335",
      "BUILD_TIMESTAMP": "2021-05-07 00:26:40 PDT",
      "CLASSPATH": "",
      "HUDSON_HOME": "/var/jenkins_home",
      "JOB_NAME": "marslo/sandbox",
      ...
    }

references:

import hudson.model.*

def build = Thread.currentThread().executable
def myVar = build.getBuildVariables().get('myVar')
import hudson.slaves.EnvironmentVariablesNodeProperty
import hudson.EnvVars
import hudson.model.BuildableItem
import hudson.model.Job
import jenkins.model.*;

jenkins = Jenkins.instance;
EnvironmentVariablesNodeProperty prop = jenkins.getGlobalNodeProperties()
                                               .get(EnvironmentVariablesNodeProperty.class)
EnvVars env = prop.getEnvVars()

println env['MY_VAR']

setup environment

import hudson.EnvVars;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.util.DescribableList;
import jenkins.model.Jenkins;

public createGlobalEnvironmentVariables(String key, String value){

  Jenkins instance = Jenkins.getInstance();

  DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
  List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);

  EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
  EnvVars envVars = null;

  if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
    newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
    globalNodeProperties.add(newEnvVarsNodeProperty);
    envVars = newEnvVarsNodeProperty.getEnvVars();
  } else {
    envVars = envVarsNodePropertyList.get(0).getEnvVars();
  }
  envVars.put(key, value)
  instance.save()

}
createGlobalEnvironmentVariables('Var1','Dummy')
  • declarative pipeline

    pipeline {
      agent any
      environment {
        DISABLE_AUTH = 'true'                               //can be used in whole pipeline
      }
      stages {
        stage(“Build”) {
          steps {
            echo env.DISABLE_AUTH
          }
        }
      }
    }
  • scripted pipeline

    node{
      stage('Build') {
        withEnv(["DISABLE_AUTH=true"]) {
          echo env.DISABLE_AUTH
        }
      }
    }

### [update Jenkins envvars in Jenkisnfile](https://stackoverflow.com/a/54945018)
```groovy
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
import hudson.slaves.*

def updateEnvVar() {
  script {
    instance = Jenkins.getInstance()
    globalNodeProperties = instance.getGlobalNodeProperties()
    envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)

    newEnvVarsNodeProperty = null
    envVars = null

    if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
      newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
      globalNodeProperties.add(newEnvVarsNodeProperty);
      envVars = newEnvVarsNodeProperty.getEnvVars();
      envVars.put(NEW_VAR, "toto");
    } else {
      for (property in envVarsNodePropertyList) {
        envVars = property.getEnvVars();
        envVars.put("EXISTING_VAR","tata");
      }
    }

    instance.save()
  }
}

Retrieve all properties of env in Jenkinsfile
get builds environment
Access to build environment variables from a groovy script in a Jenkins build step (Windows)
or
using groovy script
creating local environment variables
Jenkins Pipeline Environment Variables - The Definitive Guide
Using environment variables in Jenkins pipelines - with examples
Jenkins Pipeline - set and use environment variables
Pipeline - Build failed due to MissingPropertyException: No such property: env
environment variables
get current customized environment
get downstream build environment
get previous build environment
global environment
System.getenv()
sh 'env' or sh 'printenv'
env.getEnvironment() or currentBuild.getRawBuild().getEnvironment()
get builds environment
setup environment
using groovy script
creating local environment variables