How can I use pipeline environment variables to configure my Jenkins agent?

4/2/2019

I am trying to use environment variables to configure my Jenkins agent as follows:

pipeline {
  environment { 
    TEST = "test"
  }

  agent {
    kubernetes {
      label 'kubernetes'
      defaultContainer 'jnlp'
      yaml """
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: "${env.TEST}"
...

but ${env.TEST} is coming out as null. Using ${env.BUILD_NUMBER} works as expected so it seems the agent doesn't have access to environment variables defined in the pipeline.

Is there any way to get this to work?

-- dippynark
jenkins
kubernetes

1 Answer

4/2/2019

You have it basically right. env.VALUE are used for specific user environment variables (e.g. If I run jenkins in an agent environment with KUBECONFIG set, as per an AMI or otherwise, that would be considered env.KUBECONFIG). It is confusing, but typically in a library you define global environment variables as follows:

env.MY_VALUE = "some value"

When referencing the env.VALUE, it is the actual user environment variables you are checking. For the values you set in the environment closure, you can just call them by MY_VALUE:

pipeline {
  environment { 
    TEST = "test"
  }

  agent {
    kubernetes {
      label 'kubernetes'
      defaultContainer 'jnlp'
      yaml """
apiVersion: v1
kind: Pod
metadata:
  labels:
    name: "${TEST}"
...
-- pypalms
Source: StackOverflow