1. Global Environment Variables in the Pipeline
Defining environment variables at the top level of your pipeline makes them accessible in every stage. In the example below, three key–value pairs are defined: the database host, username, and password. You can reference these variables in any stage using the syntax${VARIABLE_NAME}.
git add, git commit, and git push origin main), review the Jenkins console output to verify that the environment variables have been correctly injected. For example, the output might include:
In the “Test” stage, the pipeline echoes the username and password after running the tests with
pytest. Make sure your sensitive information is managed carefully when echoing details in production environments.2. Defining Environment Variables Within a Stage
You might also define environment variables within a specific stage. However, note that these variables are local to the stage and are not accessible in other stages. The example below shows environment variables defined in the “Setup” stage. Attempting to access them in a different stage (such as “Test”) will result in an error.3. Utilizing Built-In Jenkins Environment Variables
Jenkins comes with several built-in environment variables that can be extremely useful. One common variable isenv.GIT_COMMIT, which provides the Git commit hash that triggered the build. This information is particularly useful for tracking builds and deployments.
By leveraging both custom-defined and built-in environment variables, you can manage configuration settings and capture important build metadata seamlessly in your Jenkins pipelines.
Summary
In this lesson, we covered the following key points:- How to define global environment variables to make them accessible in all pipeline stages.
- The limitations of defining environment variables within a specific stage and ensuring proper scope.
- Utilizing built-in Jenkins variables, such as
env.GIT_COMMIT, to obtain valuable build-related information.