How do I define variables in Jenkins declarative pipeline?
July 28, 2023 2023-07-28 15:15How do I define variables in Jenkins declarative pipeline?
Jenkins is an open source and written in the Java programming language. The Jenkins can provides hundreds of plugins to support building, deploying and automating any project. we can use for continuous integration / continuous delivery and deployment It is used to implement CI/CD workflows, called pipelines.
In Jenkins declarative pipeline, you can define variables using the environment block or using the def keyword. The environment block is used to define environment variables that will be available to all steps in the pipeline.
Here’s how you can define variables using both methods:
1. Using the environment block:
pipeline {
agent any
environment {
// Define environment variables here
ENVIRONMENT = "PROD!"
APPLICATION = "API_APPS"
}
stages {
stage('Example Stage') {
steps {
echo "Value of ENVIRONMENT : ${env.ENVIRONMENT }"
echo "Value of APPLICATION : ${env.APPLICATION }"
}
}
}
}
In the above example, we define two environment variables, ENVIRONMENT and APPLICATION, within the environment block. These variables can be accessed using the env object inside the pipeline’s steps.
Using the def keyword:
pipeline {
agent any
stages {
stage('pull image') {
steps {
// Define variables using the def keyword
def ENVIRONMENT = "PROD!"
def APPLICATION = "API_APPS"
echo "Value of Var1: ${ENVIRONMENT}"
echo "Value of Var2: ${APPLICATION}"
}
}
}
}
Both methods allow you to define variables, but the choice between them depends on whether you need the variables to be available globally (using the environment block) or limited to a specific scope (using the def keyword).