Jenkins pipeline define variable

Jenkins pipeline define variable | Complete tutorial with Example [2023]

This is the fourth part of the Jenkins pipeline example. In this blog, we will understand the Jenkins pipeline define variable.

Introduction

This blog will teach how to write a Jenkins pipeline, define variables in Pipeline, and understand how to use these variables in the Jenkins pipeline.

In Jenkins’s declarative pipeline model, we have an environment declaration block to declare your variables.

environment {
     FOO = "Hello"
   }

You can define all of your variables in the environment session and use these variables in the entire Pipeline.

Jenkins pipeline assigns a value to a variable

In the Jenkins pipeline, we can assign the value to a variable by passing the variable name and its corresponding value in theenvironment declaration block.

environment {
     <varaible_name> = <varaible_value>
   }

In the next session, we will understand how to use the variable in the Jenkins pipeline with an example.

Jenkins pipeline define global variable

To build a new pipeline in Jenkins, Connect to Jenkins UI and click on New item.

Provide the pipeline name as Jenkins pipeline define variable and select Pipeline, and then click on the ok button

Jenkins pipeline define variable

Now go to the pipeline session and paste the below code

pipeline {
    environment {
        FNAME = "Naive"
        LNAME= "Skill"
    }
    agent any
    stages {
        stage('Hello') {
            steps {
                sh "echo Hello ${FNAME} ${LNAME}"
            }
        }
    }
}
Jenkins pipeline define variable

Pipeline explanation

  1. Pipeline
    • The Declarative pipeline should start with the mandatory pipeline block.
  2. environment
    • Environment session is used to define the global variables
    • In this example, we have two environment variables FNAME, and LNAME, and assign values to these variables.
  3. Agent
    • Agent signifies where the Jenkins build job should run. In this case, we have selected an agent as any
  4. Stages/stage
    • stages block consists of different executable stage blocks. 
    • At least one stage block is mandatory inside the stages block.
    • In this example, we have defined a single stage as “Hello”
  5. Steps
    • Steps blocks consist of the actual operation which needs to be performed inside Jenkins.
    • In the Hello stage, we are printing “Hello ${FNAME} ${LNAME} “

Click on the save button to save the Pipeline.

Now click on Build now button(1) to build the Pipeline

Jenkins pipeline define variable

Click on #1(step 2) to see the logs

Jenkins pipeline define variable logs

From the above output, it is clear that the Pipeline ran successfully and printed out “Hello Naive Skill.

Jenkins pipeline define variable in stage

In the above example, the variable which we have defined is the global variable, which can be used anywhere in the Pipeline. Jenkins also provides the facility to define the local variable in the stage block.

The scope of the Jenkins local variable will be limited to stages block. Use the below code snippet to define a local variable in the Jenkins pipeline.

pipeline {
    environment {
        FNAME = "Naive_global"
        LNAME= "Skill_global"
    }
    agent any
    stages {
        stage('Step1') {
            environment {
               FNAME = "Naive_local" 
            }
            steps {
                sh "echo Hello ${FNAME} ${LNAME}"
            }
        }
        stage('Step2') {
            environment {
               LNAME = "skill_local" 
            }
            steps {
                sh "echo Hello ${FNAME} ${LNAME}"
            }
        }
    }
}

Code explanation

  • At the pipeline label, we have defined FNAME=”Naive_global” and LNAME= “Skill_global”
  • In step1, we have again defined a local variable calledFNAME=”Naive_local”
  • In step2, we have again defined a local variable called LNAME=”Skill_local”

On a successful run, you will get the below output.

Jenkins pipeline define variable in stage

From the above output, it is clear that the global variable gets overwritten with the local values.

Jenkins Pipeline define a variable array

In Jenkins declarative Pipeline, you can define an array variable using the def keyword Below is the sample code snipped for the same:

def sample_array = ["TOM", "JACk", "HARRY"]
pipeline {
	agent any
    	stages {
        	stage("print") {
            	steps {
                	echo sample_array
            	}
            }
        }
}

Code Explanation:

  • The code you provided defines a variable sample_array as an array containing the strings “TOM”, “JACK”, and “HARRY”.
  • Later we defined a pipeline with a single stage called “print” which contains a single step that uses the echo command to print the value of the sample_array variable to the console.

When you run this pipeline, it will execute the “print” stage on any available agent. The output will be:

[Pipeline] echo
[TOM, JACk, HARRY]

you can also iterate over the array and perform specific actions on each element of the array.

pipeline {
    stages {
        stage("print") {
            steps {
                script {
                    for (int i = 0; i < sample_array.size(); i++) {
                        echo sample_array[i]
                    }
                }
            }
        }
    }
}

The output of the above code will be:

[Pipeline] echo
TOM
[Pipeline] echo
JACk
[Pipeline] echo
HARRY

Jenkins Pipeline define variable between stages

In Jenkins declarative Pipeline, variables can be usually defined at the top level of the pipeline script and they are available to all stages in the pipeline. However, if you wish to pass a variable from one stage to another, you can use the below code block.

pipeline {
    stages {
        stage("Test1") {
            steps {
                script {
                    def test_var = "Hello, World!"
                    env.test_var = test_var
                }
            }
        }
        stage("Test2") {
            steps {
                echo "${env.test_var}"
            }
        }
    }
}

Code explanation:

  • The above code defines a pipeline with two stages: “Test1” and “Test2”. In the first stage “Test1” it defines a variable test_var with the value “Hello, World!” inside a script block, and sets it as an environment variable env.test_var.
  • The second stage “Test2” has a single step that uses the echo command to print the value of the environment variable env.test_var to the console
  • Since the variable is set as an environment variable in the previous stage, it’s available to all stages of the pipeline.

When you run this pipeline, the output will be:

[Pipeline] echo
Hello, World!

Alternatively, you can also use the return statement to return the variable from the script block, and then use it in the next stage.

pipeline {
    stages {
        stage("Test1") {
            steps {
                script {
                    def test_var = "Hello, World!"
                    return test_var
                }
            }
        }
        stage("Test2") {
            steps {
                echo "${Test1}"
            }
        }
    }
}

Please note that in this case, the variable will be available to the next stage with the same name as the previous stage and it will be accessible using the format “${Test1}”

Jenkins pipeline set an environment variable from sh

So far, we have used the environment block to define theenvironment variable in Jenkins. But this is not the only way to define the environment variable in Jenkins. Users can also define and set the environment in Jenkins using the sh command.

Refer to the below pipeline to define the Jenvironment variable from sh

pipeline{
    agent any
    stages{
        stage("set env variable"){
            steps{
                script{
                    env.NAME = "NAIVE-SKILL"
                    echo "Print NAME Env varaible"
                    echo "${env.NAME}"
                }
            }
        }
    }
}

The pipeline will produce the below output on a successful run.

Jenkins pipeline set an environment variable from sh

Jenkins pipeline list all environment variable

Through the Jenkins pipeline, we can also list all the environment variables present by default. Use the below pipelines to list all variables present in Jenkins.

pipeline {
    agent any
    stages {
        stage('Step1') {
            steps {
              sh 'printenv'
            }
        }
    }
}

The above pipelines will produce the below output.

Jenkins pipeline list all environment variable

You can also go to this URL http://<jenkins-url>/env-vars.html/ to list all the available environment variables for your Jenkins instance.

Conclusion

In this blog, we have learned how to use the variables in the Jenkins pipeline. We have also learned how to define local and global variables in the Jenkins pipeline. Please do let me know if you are facing any issues while following along.

More to Explore

Jenkins workflow

Jenkins pipeline example hello-world

Jenkins pipeline example multiple stages

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top