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

2 min read 07-10-2024
How to list all `env` properties within jenkins pipeline job?


Unveiling Your Jenkins Pipeline Environment: A Guide to Listing env Properties

Navigating the complex world of Jenkins pipelines can sometimes feel like deciphering a foreign language. One common question that arises is: how do I list all the environment variables (env properties) available within my pipeline job? This article provides a straightforward solution and explores the underlying concepts.

Understanding the env Property

The env property in Jenkins pipelines is a powerful tool that allows you to access and utilize environment variables within your pipeline. These variables can be defined globally at the Jenkins level, in specific jobs or even within the pipeline itself.

Let's say you have a pipeline script that uses the env property to access a variable named BUILD_NUMBER:

pipeline {
  agent any
  stages {
    stage('Echo Build Number') {
      steps {
        echo "Current build number: ${env.BUILD_NUMBER}"
      }
    }
  }
}

But how do you discover all the available env properties within your pipeline?

The Power of the sh Step

The sh step allows you to execute shell commands within your pipeline. This becomes our key to unlocking the env property secrets:

pipeline {
  agent any
  stages {
    stage('List Environment Variables') {
      steps {
        sh 'env'
      }
    }
  }
}

This script utilizes the sh step with the simple command env. When executed, this command outputs a detailed list of all the environment variables available within your pipeline, including:

  • Global Jenkins environment variables
  • Job-specific environment variables
  • Environment variables defined within the pipeline

Beyond the Basics

The sh step provides a comprehensive list of available environment variables, but you can further refine your approach:

  • Filtering specific variables: Use grep to filter for specific variables within the sh 'env' command. For example, sh 'env | grep BUILD_NUMBER' would only show the BUILD_NUMBER variable.
  • Storing results in a variable: You can capture the output of the sh command using a script block and store it in a variable for further processing.

Important Considerations

  • Security: Exercise caution when dealing with sensitive information in your environment variables. Avoid displaying highly sensitive data directly within the pipeline output.
  • Dynamic environments: Environment variables can be dynamic, meaning they can change between builds or even during a single build. Keep this in mind when interpreting your results.

By understanding the env property and utilizing the sh step effectively, you gain valuable insights into your Jenkins pipeline environment, enabling you to manage your jobs with confidence and efficiency.