Continuous integration/continuous delivery - JenkinsFile detailed tutorial

insert image description here

JenkinsFile detailed tutorial

1. BlueOcean

1. Concept of BlueOcean

Provides a set of visual operation interface to help create and edit Pipeline tasks
It provides developers with a more fun way to use Jenkins
Implements a new, modern user interface
Helps teams of any size achieve continuous delivery

2. Features of BlueOcean

Pipeline editor: an intuitive and visual pipeline editor.
Pipeline visualization: Visual representation of the pipeline.
Pipeline diagnosis: Immediately locate task problems.
Personalized dashboard: Users can customize the dashboard to display only the pipelines related to themselves

3. BlueOcean installation

BlueOcean needs to be installed in the Jenkins plugin
insert image description here

2. Introduction to Pipeline

1. Jenkins Pipeline concept

a. Borrow the idea of ​​Pipeline in Unix, a tool with high cohesion and low coupling
b. Jenkins 2.0 or above will have
c. A series of Jenkins plug-ins describe the entire continuous integration with explanatory code Jenkinsfile
d. Jenkinsfile usage method:

Jenkins task page input
Edit in source code project

2. Jenkinsfile syntax type:

Declarative pipeline
Scripts pipeline

3. Use Jenkins task page input

a. Create a pipeline task in Jenkins

insert image description here

b. Select Pipeline Script in Definition

c. Add Pipeline code in the Pipeline module

pipeline {
    
    
    agent any

    stages {
    
    
        stage('Hello') {
    
    
            steps {
    
    
                echo 'Hello World'
            }
        }
    }
}

insert image description here

d. run

insert image description here

4. Use the Git source code library to import Jenkins Pipeline

a. Select Pipeline script from SCM in the Jenkins Pipeline task,

b. Then add the git source address,

c. Fill in the address of the Jenkinsfile that needs to be run in Script Path

insert image description here

d. run

insert image description here
insert image description here


3. Introduction to Jenkinsfile syntax

1. Jenkinsfile supports two syntax forms:

Declarative pipeline - introduced after v2.5, structured way
Scripts pipeline - based on groovy syntax

insert image description here

2. Jenkinsfile syntax one: Declarative Pipeline

a. Must be included in a pipeline block, specifically: b. The basic part is "steps", steps tell Jenkins what to do c. Statement classification specifically includes Sections, Steps, assignment and other categories
pipeline {
}


insert image description here

3、Declarative Pipeline - agent

agent: defines the command parameters
that must appear in the pipeline execution node

any: the pipeline can be executed on any agent
none: the pipeline will not allocate a global agent, and each stage will allocate its own agent
label: specify the Label of the running node
node: customize the configuration of the running node,

specified label
specified customWorkspace

docker: control the content related to docker running on the target node

Declarative Pipeline - agent code example

pipeline {
    
    
    agent {
    
    
        label 'master'
        customWorkspace 'myWorkspace'
    }
}

4、Declarative Pipeline - stages

Instructions that must appear
No parameters
Contains a sequence of one or more stages, where most of the Pipeline's work is performed;
there must be only one stage in each Pipeline code interval

5、Declarative Pipeline - stage

Instructions that must appear
No parameters
Included in stages
All the actual work done by the Pipeline needs to be included in the stage
The name of the stage needs to be defined

6、Declarative Pipeline - steps

Instructions that must appear
No parameters
Specific execution steps, included in the stage code interval

7. Declarative Pipeline - stages, stage, steps code example

 stages {
    
    
    stage('pull source code'){
    
    
        steps {
    
    
            echo 'pull source code'
            sleep 5
        }
    }
 }

8. Code demo

pipeline {
    
    
    agent any
    
    stages {
    
    
        stage("pull source code"){
    
    
            steps {
    
    
                echo "pull source code"
                sleep 5
            }
        }
        
        stage("build"){
    
    
            steps{
    
    
                echo "build source code"
                sleep 5
            }
        }
        
        stage("test"){
    
    
            steps{
    
    
                echo "run unit test"
            
            }
        }
        
        stage("deploy"){
    
    
            steps{
    
    
                echo "deploy to the website"
            
            }
    }
}
}

insert code snippet here
insert image description here

insert image description here

Four, JenkinsFile syntax parameter post

post : Define the operation at the end of the Pipeline or stage operation.
It is not a mandatory instruction
. Parameters:

always: run regardless of the completion status of the Pipeline run
changed: only run if the current Pipeline run's state is different from the state of the previously completed Pipeline
failure: run only if the current Pipeline is in the "failed" state
success: only run if the current Only run when the Pipeline has a "success" status
Unstable: only run when the current Pipeline has an "unstable" status
aborted: run only when the current Pipeline is in the "aborted" state

Case 1 - Execution failed

pipeline{
    
    
    agent any
    
    stages {
    
    
        stage('Test'){
    
    
            steps{
    
    
                echo "This is test code"
                sleep 2
                sh 'exit -1'
            }
        }
    }
    
    post{
    
    
        always{
    
    
            echo 'say goodby'
        }
        success{
    
    
            echo 'This is success exit'
        }
        failure{
    
    
            echo 'This is failure exit'
        }
    }
}

insert image description here

Case 2 - successful execution

pipeline{
    
    
    agent any
    
    stages {
    
    
        stage('Test'){
    
    
            steps{
    
    
                echo "This is test code"
                sleep 2
                sh 'exit 0'
            }
        }
    }
    
    post{
    
    
        always{
    
    
            echo 'say goodby'
        }
        success{
    
    
            echo 'This is success exit'
        }
        failure{
    
    
            echo 'This is failure exit'
        }
    }
}

insert image description here

Five, JenkinsFile syntax parameter options

options : Defining the exclusive attributes of the pipeline,
which is not a mandatory instruction
Parameters:

buildDiscarder:保持构建的最大个数(历史构建个数)
disableConcurrentBuilds:不允许并行执行pipeline任务
timeout:pipeline 超时时间
retry:失败后,重试整个Pipeline的次数
timestamps:预定义由Pipeline生成的所有控制台输出时间
skipStagesAfterUnstable:一旦构建状态进入了“Unstable”状态,就跳过此stage

1、正常情况

pipeline{
    
    
    agent {
    
    
        node{
    
    
            label 'docker_node'
            customWorkspace "pipelineWorkspace"
        }
    }
    
    options {
    
    
        timeout(time: 10,unit:"SECONDS")    //构建超过10s,就会超时
        buildDiscarder(logRotator(numToKeepStr:"2"))    //最多保留2个最新的构建
        retry(5)    //失败后尝试运行5}
    stages {
    
    
        stage('begin'){
    
    
            steps{
    
    
                echo 'hello pipeline begin'
                sleep 2
            }
            
        }
        stage('running'){
    
    
            steps{
    
    
              echo 'hello pipeline running'
                sleep 2  
            }
            
        }
        stage('finsh'){
    
    
            steps{
    
    
                echo 'hello pipeline finsh'
                sleep 2
                sh "exit 0"
            }
            
        }
    }
        
    post{
    
    
        always{
    
    
            echo 'say goodby'
        }
        success{
    
    
            echo 'This is success exit'
        }
        failure{
    
    
            echo 'This is failure exit'
        }
    }
        
    
}

控制台输出

Started by user admin
[Pipeline] Start of Pipeline
[Pipeline] node
Running on docker_node in /root/jenkins_mulu/workspace/pipeline_demo_options
[Pipeline] {
    
    
[Pipeline] ws
Running in /root/jenkins_mulu/pipelineWorkspace
[Pipeline] {
    
    
[Pipeline] timeout
Timeout set to expire in 10 sec
[Pipeline] {
    
    
[Pipeline] retry
[Pipeline] {
    
    
[Pipeline] stage
[Pipeline] {
    
     (begin)
[Pipeline] echo
hello pipeline begin
[Pipeline] sleep
Sleeping for 2 sec
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] {
    
     (running)
[Pipeline] echo
hello pipeline running
[Pipeline] sleep
Sleeping for 2 sec
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] {
    
     (finsh)
[Pipeline] echo
hello pipeline finsh
[Pipeline] sleep
Sleeping for 2 sec
[Pipeline] sh
+ exit 0
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] {
    
     (Declarative: Post Actions)
[Pipeline] echo
say goodby
[Pipeline] echo
This is success exit
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // retry
[Pipeline] }
[Pipeline] // timeout
[Pipeline] }
[Pipeline] // ws
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

2、异常情况

pipeline{
    
    
    agent {
    
    
        node{
    
    
            label 'docker_node'
            customWorkspace "pipelineWorkspace"
        }
    }
    
    options {
    
    
        timeout(time: 10,unit:"SECONDS")    //构建超过10s,就会超时
        buildDiscarder(logRotator(numToKeepStr:"2"))    //最多保留2个最新的构建
        retry(5)    //失败后尝试运行5}
    stages {
    
    
        stage('begin'){
    
    
            steps{
    
    
                echo 'hello pipeline begin'
                sleep 2
            }
            
        }
        stage('running'){
    
    
            steps{
    
    
              echo 'hello pipeline running'
                sleep 2  
            }
            
        }
        stage('finsh'){
    
    
            steps{
    
    
                echo 'hello pipeline finsh'
                sleep 2
                sh "exit -1"
            }
            
        }
    }
        
    post{
    
    
        always{
    
    
            echo 'say goodby'
        }
        success{
    
    
            echo 'This is success exit'
        }
        failure{
    
    
            echo 'This is failure exit'
        }
    }
        
    
}

insert image description here

六、JenkinsFile 语法参数 parameters

parameters :定义pipeline 的专有参数列表
不是必须出现的指令
参数:

支持数据类型:booleanParam, choice, credentials, file, text, password, run, string
类似参数化构建的选项

1、Declarative Pipeline - parameters 代码举例

parameters {
    
    
    string(name: 'PERSON', defaultValue: 'Jenkins', description: '输入的文本参数')
    choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')
}

2、案例:以默认值构建

pipeline {
    
    
    agent{
    
    
        node{
    
    
            label 'docker_node'
            customWorkspace "myWorkspace"
        }
    }

    parameters{
    
    
        string(name:'PERSON',defaultValue:'Jenkins',description:'输入文本参数')
    }
    
    stages{
    
    
        stage('Test Parameters'){
    
    
            steps{
    
    
                echo "Hello ${PERSON}"
            }
        }
    }
}

insert image description here

insert image description here

3、案例:非默认值构建

insert image description here

insert image description here

3、解决第一次运行失败的问题

pipeline {
    
    
    agent{
    
    
        node{
    
    
            label 'docker_node'
            customWorkspace "myWorkspace"
        }
    }

    parameters{
    
    
        string(name:'PERSON',defaultValue:'Jenkins',description:'输入文本参数')
    }
    
    environment{
    
    
        PERSON ="$params.PERSON"
    }
    
    stages{
    
    
        stage('Test Parameters'){
    
    
            steps{
    
    
                echo "Hello ${PERSON}"
            }
        }
    }
}

七、JenkinsFile 语法参数 env_tools(有问题)

1、Scripts pipeline: 环境变量定义与引用

环境工具变量的定义
设置位置: “Manage Jenkins”——> “Global Tool Configuration”

1.1、环境变量定义1: JDK Home的定义

insert image description here

1.2、环境变量定义2: Maven Home的定义

insert image description here

2、Script 代码中引用环境变量,调用java、maven工具

stage('env tools') {
    
    
    node('docker_node'){
    
            
        //定义maven java环境
        def mvnHome = tool 'maven'
        def jdkHome = tool 'jdk11'
        
        //引用环境变量,配置PATH变量
        env.PATH = "${mvnHome}/bin:${env.PATH}"
        env.PATH = "${jdkHome}/bin:${env.PATH}"
        
        //调用java mvn 工具
        sh "java -version"
        sh "mvn --version"
    }
}

运行结果

insert image description here

八、JenkinsFile 语法参数 if-else

1、Jenkinsfile 语法二:Scripts pipeline

基于 groovy 语法定制的一种DSL语言
灵活性更高
可扩展性更好
Script pipeline 与 Declarative pipeline 程序构成方式有雷同之处,基本语句也有相似之处

insert image description here

2、Scripts pipeline: 流程控制之 – if/else

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

stage('Build'){
    
    
    node {
    
    
        echo 'this is build stage.'
    }
}

3、采用master构建

insert image description here
insert image description here

4、采用非master构建

insert image description here

insert image description here

九、JenkinsFile 语法参数 try-catch

1、Scripts pipeline: 流程控制之 – try/catch

场景:异常处理,在运行程序的时候,不希望代码的错误,导致程序的退出
使用try进行捕获,使用catch对异常的代码进行处理

2、演示出现异常

stage('Test') {
    
    
    node{
    
    
        echo "This is test stage which run on the slave agent."

        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."

        }
    }
}

insert image description here

3、演示正常

stage('Test') {
    
    
    node{
    
    
        echo "This is test stage which run on the slave agent."

        try {
    
    

            echo "This is in the try block."
            
            sh 'exit 0'

        }catch (exc) {
    
    

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

        }finally {
    
    

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

        }
    }
}

insert image description here

十、JenkinsFile 语法参数 environment

1、Declarative Pipeline - environment

environment: 定义Pipeline或stage运行时的环境变量
不是必须出现的指令
无参数

2、Declarative Pipeline - environment代码举例

environment {
    
    
    hlw = 'hello world'
}

3、environment 运行演示

pipeline {
    
    
    agent  {
    
    
        node{
    
    
            label 'docker_node'
            customWorkspace "myWorkspace"
        }

    }

    environment {
    
    
        hlw = 'hello world'
    }

    stages {
    
    
        stage('Print environment_1'){
    
    
            steps {
    
    
                echo hlw
                sleep 1
            }
        }

        stage('Print environment_2'){
    
    
            steps {
    
    
                sh 'echo ${hlw}'
                sleep 1
            }
        }
    }

    post {
    
    
        success {
    
    
            echo 'goodbye pipeline success!'
            sleep 5
        }

        failure {
    
    
            echo 'ops!!! pipeline failed....'
            sleep 5
        }

        always {
    
    
            echo 'always say goodbye'
        }
    }
}

运行结果
insert image description here

十一、JenkinsFile 语法参数 triggers

1、Declarative Pipeline - triggers

triggers:定义了Pipeline自动化触发的方式
不是必须出现的指令
参数:

cron: Accepts a cron-style string to define the regular interval for Pipeline triggering
pollSCM: Accepts a cron-style string to define the regular interval for Jenkins to check for SCM source changes; the Pipeline will be retriggered if there are new changes.

2. Declarative Pipeline - triggers code example

triggers {
    
    
    cron('H/2 * * * *')
}

3. Triggers run demo

pipeline {
    
    
    agent{
    
    
        node{
    
    
            label 'docker_node'
            customWorkspace "myWorkspace"
        }
    }

    triggers {
    
    
        cron('H/2 * * * *')
    }

    stages{
    
    
        stage('Test Parameters'){
    
    
            steps{
    
    
                echo "Hello"
            }
        }
    }
}

12. Summary of Pipeline

Pipeline is a high-level tool launched after Jenkins 2.0.
With Pipeline, Jenkins tasks can realize the transformation from simple continuous integration to comprehensive CI/CD pipeline upgrade. You can
choose to fill in the Pipeline script in the Jenkins task
or use the source code library to update the Pipeline script. Manage
two Jenkinsfile syntaxes: Declarative Pipeline and Script Pipeline
have similarities in statements, but differ in scalability and flexibility

Guess you like

Origin blog.csdn.net/YZL40514131/article/details/130233239