Continuous delivery-Jenkinsfile syntax

The scripting language that implements the Pipeline function is called Jenkinsfile, which is implemented by the Groovy language. The Jenkinsfile is generally placed in the project root directory and is controlled by the source code management software along with the project. There is no need to copy many settings to a new project each time like creating a “free style” project, which provides some direct benefits:

  • Code review/iteration on Pipeline
  • Pipeline audit trail
  • The single source of truth for a Pipeline that can be viewed and edited by multiple members of the project
    Pipeline supports: Declarative (introduced in Pipeline 2.5) and Scripted Pipeline formats. Both support building Pipelines, and both can be used to define a Pipeline Jenkinsfile in the Web UI. Creating and checking a Jenkinsfile into a source control repository is generally considered a best practice.

Declared Pipeline

Declared Pipeline tree

Declared Pipeline must be contained within a fixed-format Pipeline {} block, and each declaration statement must be on its own line without a semicolon at the end of the line. Blocks ( blocks{} ) can only contain Sections, Directives, Steps or assignment statements.

block blocks{}

Statements enclosed by curly brackets, such as Pipeline{}, Section{}, parameters{}, script{}

Sections

Chapters usually contain one or more instructions or steps. Such as agent, post, stages, steps

Directives

environment, options, parameters, triggers (trigger), stage, tools, when

Node (agent)

Must exist, agent must be defined at the top level within the Pipeline block, but whether to use it within the stage is optional
Parameters: any/none/label/node/docker/dockerfile
Common options label/cuetomWorkspace/reuseNode
Example:

agent { label 'my-label' }

agent {
    node {
        label 'my-label'
        customWorkspace '/some/other/path'
    }
}

agent {
    docker {
        image 'nginx:1.12.2'
        label 'my-label'
        args '-v /tmp:/tmp'
    }
}

After building (post)

It is not necessary. It is used in the outermost layer of Pipeline or in stage{}. It is mainly used to express what Jenkins needs to do after completing the build action.

Example:

pipeline {
    agent any
    { stages
        stage('Example'){
            {steps
                echo 'Hello world'
            }
        }
    }
    post {
        always {
            echo 'say goodbay'
        }
    }
}

Stages (stages)

Must exist, including one or more stage commands executed sequentially, which can only be used once within the Pipeline, usually located after agent/options.

Steps

Must exist, steps is located inside the stage instruction block, and includes one or more steps. When there is only one step, the keyword step and its {} can be ignored.

Environment

It is not necessary. environment defines a set of global environment variable key-value pairs, which exist within pipeline {} or stage instructions. Execute the special method credentials() to obtain the predefined credential content in Jenkins.

Example:

environment {CC='clang'}
environment {AN_ACCESS_KEY = credentials('my-prefined-secret-text')}
steps {sh 'printenv'}

Options

Not required, pre-defined Pipeline-specific configuration information, which can only be defined once

Example:

pipeline {
    agent any
    options{
        timeout(time:1,unit: 'HOURS')
    }
}

Parameters

It is not necessary. Define the parameters of parameterized construction. Optional parameters. Parameter type: booleanParam, choice, file, text, password, run, string
Example:

parameters {
        string(name: 'PERSON', defaultValue: 'Jenkins', description: 'Input text parameters')
        choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
}

Triggers (rtiggers)

Not necessary, define the way the Pipeline is automatically triggered with options cron, pollSCM, upstream

Example:

triggers {
       cron('0 8 * * 1-5')
}

Script Pipeline

Script Pipeline statement tree

A Script Pipeline can be divided into several Stages, each Stage represents a set of operations, such as Build, Test; Node represents Jenkins nodes, such as Master, Slave nodes; Step is the most basic operation unit, executed on the corresponding Node node The action statements are written directly in node {}.

Process control statement

Like traditional scripting languages, Script Pipeline is executed sequentially from top to bottom. Groovy expressions can be used for process control. For example, if/else statements control the process through logical conditional judgment:

node {
    stage('Example') {
        if (env.BRANCH_NAME == 'master') {
            echo 'I only execute on the master branch'
        } else {
            echo 'I execute elsewhere'
        }
    }
}

Exception handling statement

Script Pipeline Another way to control script flow is the exception handling mechanism. When an exception occurs in any step due to various reasons, the try/catch/finally statement block must be used in the code to catch the exception, and handle it through pre-set code to ensure that the script can be executed smoothly:

stage('Error Handling') {
    node{
        echo "This is test demo for the error handling"

        try {

            echo "This is in the try block."

            sh 'exit 1'

        }catch (exc) {

            echo "Something failed, I'm in the catch block."

        }finally {

            echo "Finally, I'm in the finally block."

        }
    }
}

Calling the plugin function in Jenkinsfile

In addition to using conventional logic and process control in Jenkinsfile, you can also call Jenkins plug-in functions. The following examples are used to illustrate.

Email Extension plug-in

Email Extension is an external plug-in in Jenkins that is used to send emails. It can be installed from the Jenkins Plugin Manager. The plug-in can be triggered to run through code calls in Pipeline to implement the function of sending emails.

Basic configuration

After installing the Email Extension plug-in, you first need to select an email address to be used to send Jenkins notification emails. The specific parameters of the sending email address must be known in advance (usually the parameters can be found on the configuration parameter information page of the email address); then you need to In Manage Jenkins -> Configure System, fill in the corresponding parameters in the corresponding configuration items of the plug-in. The parameters that must be configured are as follows:

  • SMTP server: smtp service address
  • SMTP port: smtp port number
  • Use SMTP Authentication: Enable SMTP security verification
  • User Name: Sender user name
  • Password: sender password
  • Default Recipients: Default recipients
    Other parameters can be configured according to your own needs. The Email Extension configuration reference screenshot is as follows:

Pipeline code

pipeline{
    agent {
        label 'master'
    }
    stages{ stages
        stage('Send email test') {
            steps{
                echo 'Test Email'
            }
        }
    }
    post {
        always {
            emailext body: '$DEFAULT_CONTENT', recipientProviders: [[$class: 'RequesterRecipientProvider']], subject: '$DEFAULT_SUBJECT'
        }
    }
}

Declared Pipeline is relatively easy to get started with. It is similar to the keyword-driven model we are exposed to when doing automated testing. You only need to understand the defined keywords and fill in the data as required.
Although this method is easy to get started, it lacks flexibility. In contrast, the advantages of script Pipeline are that it is flexible, easy to encapsulate, and easy to use on a large scale, but it requires certain programming skills.

Finally, I would like to thank everyone who read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can just take it away:

This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!