Understand Environment Variables in a Pipeline
In this final step, you will learn about environment variables. The environment directive allows you to define variables that can be used throughout your pipeline, which is ideal for managing configuration settings without hard-coding them in your steps.
The Jenkinsfile from the remote repository already demonstrates this concept with an environment variable that specifies a deployment target.
Let's examine how environment variables are defined and used:
pipeline {
agent any
environment {
DEPLOY_TARGET = 'staging'
}
stages {
// ... other stages ...
stage('Deploy') {
steps {
echo "Deploying the application to ${env.DEPLOY_TARGET}..."
sh 'echo "Application deployed successfully!"'
}
}
}
}
Key points about environment variables in Jenkins Pipelines:
- The
environment { ... } block defines variables that are available throughout the pipeline.
- Variables are accessed using
${env.VARIABLE_NAME} syntax.
- It is crucial to use double quotes (
") for strings with variable interpolation, as Groovy's variable interpolation only works inside double-quoted strings.
- Environment variables make your pipelines more flexible and easier to maintain.
-
If you haven't already, trigger a new build in Jenkins by clicking Build Now.
-
After the build completes, check the Console Output for the build. In the log for the "Deploy" stage, you will see that the variable was correctly substituted:
...
[Pipeline] { (Deploy)
[Pipeline] echo
Deploying the application to staging...
[Pipeline] sh
+ echo Application deployed successfully!
Application deployed successfully!
[Pipeline] } // stage
...
Finished: SUCCESS
- Notice how the
DEPLOY_TARGET environment variable value staging was automatically substituted into the echo statement.
Environment variables are essential for creating flexible pipelines that can be easily configured for different environments (development, staging, production) without modifying the pipeline code itself.