preface

Jenkins, one of the core technologies in DevOps stack, CI/CD can’t be done without writing Pipeline scripts. If you just start with Jenkins, you should not be confused by keywords like Agent, stages, and step. Can also quickly build a pipeline skeleton

But when it comes to filling in the skeleton, especially how to use environment variables (built-in | custom), most people will get confused and waste a lot of time. This article will help you to get through environment variables quickly

To prepare

If you want to read this article and try it out, but the Jenkins service is not available and you want to try it out quickly, you can quickly build the Jenkins service with a command from Docker

docker container run --rm -p 8080:8080 -p 50000:50000 --name=jenkins -v $(pwd):/var/jenkins_home jenkins/jenkins
Copy the code

In 2021, there is no local Docker can not be said, come to see whether Docker series into your eyes?

Open your browser and type: localhost:8080

  1. Find the terminal’s temporary password to log in
  2. Install recommended dependencies
  3. Creates a new Pipeline type Item
  4. Click Config on the left, and then enter the script we will write next in the Pipeline section at the bottom of the page to test it

It’s that simple…..

Recognize Jenkins environment variables

Jenkins environment variables are global variables exposed via the env keyword and can be used anywhere in the Jenkins file

There is no real difference between global variables in your programming language

View Jenkins system built-in environment variables

Jenkins has built a lot of environment variables into the system for us to use quickly. There are two ways to check:

A:

Directly in the browser to access the ${YOUR_JENKINS_HOST} / env – vars. The HTML page, http://localhost:8080/env-vars.html, for example, the purpose of each variable is clear

Way 2

Get this by executing the printenv shell command:

pipeline {
    agent any

    stages {
        stage("Env Variables") {
            steps {
                sh "printenv"}}}}Copy the code

Directly save-build, you will see the corresponding environment variables in the terminal log and can quickly see their current values

Often these two methods can be used together

Reading environment variables

Env = ${XXX} env = ${XXX} Take the BUILD_NUMBER built-in environment variable as an example:

If you use shell commands in Jenkins files, you can use these built-in environment variables without even {}. Take a look:

pipeline {
    agent any

    stages {
        stage("Read Env Variables") {
            steps {
                echo ${env.build_number}"
                echo ${BUILD_NUMBER} ${BUILD_NUMBER}
                sh $BUILD_NUMBER = $BUILD_NUMBER}}}}Copy the code

You can see that the results are the same, and whatever the number is, remember the first is the safest

Although the built-in environment variables are good, they can not fully meet the execution logic of our custom pipeline, so we also need to know how to define and use the custom environment variables

Customize Jenkins environment variables

Jenkins Pipeline is divided into Declarative and scripted, and the corresponding environment variables are defined in slightly different ways, which can be summarized in three ways:

Let’s look at a practical example:

pipeline {
    agent any

    environment {
        FOO = "bar"
    }

    stages {
        stage("Custom Env Variables") {
            environment {
                NAME = "RGYB"
            }

            steps {
                echo "FOO = ${env.FOO}"
                echo "NAME = ${env.NAME}"

                script {
                    env.SCRIPT_VARIABLE = "Thumb Up"
                }

                echo "SCRIPT_VARIABLE = ${env.SCRIPT_VARIABLE}"

                withEnv(["WITH_ENV_VAR=Come On"]) {
                    echo "WITH_ENV_VAR = ${env.WITH_ENV_VAR}"
                }
            }
        }
    }
}
Copy the code

To see the results:

WithEnv ([“WITH_ENV_VAR=Come On”]) {} withEnv([“WITH_ENV_VAR=Come On”]) {

A complete pipeline usually has many stages. It is common for environment variables to have different values in different stages. After knowing how to set and read environment variables, we also need to know how to rewrite environment variables

Rewrite the Jenkins environment variable

One of Jenkins’ relatively confusing areas is rewriting environment variables, but just remember these three rules and you should be done

  1. withEnv(["WITH_ENV_VAR=Come On"]) {}This way of writing built-in functions can override any environment variable
  2. Defined in theenvironment {}Environment variables that cannot be scripted (env.key="value") rewrite
  3. Only scripted environment variables can be overridden

These three points are hard rules, and anything not covered by these three points is allowed

The three rules are a bit overwhelming. Farmers choose beans, for example

pipeline {
    agent any

    environment {
        FOO = "Fly like a bird to your mountain."
        NAME = "Tan"
    }

    stages {
        stage("Env Variables") {
            environment {
              	// Will override the variable at line 6
                NAME = "RGYB" 
              	// Overrides the system's built-in environment variable BUILD_NUMBER
                BUILD_NUMBER = "10" 
            }

            steps {
              	// should print "FOO = you fly to your mountain like a bird"
                echo "FOO = ${env.FOO}" 
              	// Should print "NAME = RGYB"
                echo "NAME = ${env.NAME}" 
              	// should print "BUILD_NUMBER = 10"
                echo "BUILD_NUMBER = ${env.BUILD_NUMBER}" 

                script {
                  	// Script creates an environment variable
                    env.SCRIPT_VARIABLE = "1" 
                }
            }
        }

        stage("Override Variables") {
            steps {
                script {
                  	// FOO will not be overridden, violating Rule No.2
                    env.FOO = "Tara"
                  	// SCRIPT_VARIABLE will be overridden to Rule No.3
                    env.SCRIPT_VARIABLE = "2" 
                }

              	// FOO fails to be overridden at line 37, and prints "FOO = you should fly to your mountain like a bird"
                echo "FOO = ${env.FOO}" 
              	// print "SCRIPT_VARIABLE = 2"
                echo "SCRIPT_VARIABLE = ${env.SCRIPT_VARIABLE}" 

              	// FOO will be overridden to Rule No.1
                withEnv(["FOO=Educated"]) { 
                  	// Should print "FOO = gas"
                    echo "FOO = ${env.FOO}" 
                }

              	// For the same reason
                withEnv(["BUILD_NUMBER=15"]) {
                  	// should print "BUILD_NUMBER = 15"
                    echo "BUILD_NUMBER = ${env.BUILD_NUMBER}"
                }
            }
        }
    }
}
Copy the code

Let’s verify the results

So if you look at this, you should be able to set the basic Settings, and as you can see, Jenkins sets the environment variables slightly differently from the way you set the environment variables in a programming language, where you can assign variables to objects, but Jenkins doesn’t, because in the Jenkins file, All values are treated as strings. Can’t you apply Boolean values?

Use Boolean values in Jenkins

If you set a variable to false, Jenkins will convert it to “false”. To use Boolean as a conditional, you must call the toBoolean() method to do the conversion

pipeline {
    agent any

    environment {
        IS_BOOLEAN = false
    }

    stages {
        stage("Env Variables") {
            steps {
                script {
                  	// Hello will be printed because non-empty strings are considered boolea.true
                    if (env.IS_BOOLEAN) {
                        echo "Hello"
                    }

                  	// True Boolean comparison
                    if (env.IS_BOOLEAN.toBoolean() == false) {
                        echo "A soldier of the Sun arch"
                    }
                  
                  	// Real Boolean
                    if(! env.IS_BOOLEAN.toBoolean()) { echo"RGYB"
                    }
                }
            }
        }
    }
}
Copy the code

To see the results:

If you have ever written a Pipeline, you must know that writing a shell is necessary to write a Pipeline. Sometimes, you need to assign the results of shell execution to environment variables. Jenkins also has methods to support this

The Shell result is assigned to the environment variable

It’s easy to do this, just remember one format: sh(script: ‘CMD ‘, returnStdout:true)

pipeline {
    agent any

    environment {
      	// Use trim() to remove whitespace from the result
        LS_RESULT = "${sh(script:'ls -lah', returnStdout: true).trim()}"
    }

    stages {
        stage("Env Variables") {
            steps {
                echo "LS_RESULT = ${env.LS_RESULT}"}}}}Copy the code

conclusion

With regard to Jenkins environment variables, these are basically enough for most application scenarios. When encountering environment variables again, you can go back and look at them. Are there any puzzles to solve?

Personal blog: https://dayarch.top

Day arch a soldier | original