Jenkins-Pipeline语法篇- Pipeline指令

Jenkins Pipeline 语法分类

  • Jenkins Pipeline 支持两种语法,一种 Declarative Pipeline(声明式),一种 ScriptedPipeline(脚本式)。

  • 声明式的 Pipeline 限制用户使用严格的预选定义的结构,是一种声明式的编程模型,对比脚本式的 Pipeline 学习起来更加简单;

  • 脚本式的 Pipeline 限制比较少,结构和语法的限制由 Groovy 本身决定,是一种命令式的编程模型。

  • 所以使用声明式的方式编写 jenkinsfile。一般来说 jenkinsfile 会被放在代码库的根目录下。

Pipeline 的几个基本概念

1、Stage 阶段: stages : 阶段组
  • 一个 Pipeline 有多个 Stage 组成,每个 Stage 包含一组 Step。
  • 注意一个 Stage 可以跨多个 Node 执行,即 Stage 实际上是 Step 的逻辑分组。
  • 一个Jenkinsfile 可以分为大的阶段,如打包、构建、 部署。测试
  • 构建的流程,可以分为这几步,获取源代码,然后打包,构建,进行编译,替换配置文件,编译完打包,进行部署 这个阶段就是stage
2、Node节点:
  • 一个 Node 就是一个 Jenkins 节点,可以是 Master,也可以是 Slave,是 Pipeline中具体 Step 的运行环境。
3、Step步骤:
  • Step是基本的运行单元,可以是创建一个目录、从代码库中 checkout 代码、执行一个 shell 命令、构建 Docker 镜像、将服务发布到 Kubernetes 集群中。

    • Step 由 Jenkins 和 Jenkins 各种插件提供。 dockerfile
  • step步骤 就是具体的操作,具体的一步一步的东西就是步骤step,是最小的操作单元。每个阶段都有很多步骤

options Jenkins Pipeline配置参数

options Jenkins Pipeline配置参数

参数名 说明 例子
buildDiscarder 保留最近历史构建记录的数量 buildDiscarder(logRotator(numToKeepStr: ‘10’)
checkoutToSubdirectory 将代码从版本控制库中拉取后,保存在工作目录的子目录 checkoutToSubdirectory(‘subdir’)
disableConcurrentBuilds 禁用Jenkins同时执行多次该pipeline disableConcurrentBuilds()
newContainerPerStage agent为Docker或Dockerfile时,每个stage都分别运行在一个新容器中 newContainerPerStage()
retry pipeline发生失败后重试次数 retry(4)
timeout pipeline运行超时时间 timeout(time:10, unit: ‘HOURS’)
pipeline{
    agent any
    options{
        buildDiscarder(logRotator(numToKeepStr: '10')
        disableConcurrentBuilds()
        retry(4)
        timeout(time:10, unit: 'HOURS')
    }
    stages{
        stage('demo'){
            steps{
                sh 'echo hello'
            }
        }
    }
}

Jenkins Pipeline支持的指令

指令名 说明 作用域
agent 定义执行任务的代理 stage 或pipeline
input 暂停pipeline,提示输入内容 stage
environment 设置环境变量 stage或pipeline
tools 自动下载并安装指定的工具,并将其加入到PATH变量中 stage或pipeline
options 配置Jenkins pipeline本身,如options{retry(3}},指pipeline失败时再重试2次 stage 或 pipeline
build 触发其他的job steps
when 定义阶段执行的条件 stage
triggers 定义执行pipeline的触发器 pipeline
parameters 执行pipeline前传入一些参数 pipeline
parallel 并行执行多个step stage

**

stage间通过stash进行文件共享,即使stage不在同一个执行主机上

**

pipeline{
    agent none
    stages{
        stage('stash'){
            agent { label "master" }
            steps{
                writeFile file: "a.txt", text: "$BUILD_NUMBER"
                stash name: "abc", includes: "a.txt"
            }
        }
        stage('unstash'){
            agent { label "node" }
            steps{
                script{
                    unstash("abc")
                    def content = readFile("a.txt")
                    echo "${content}"
                }
            }
        }
    }
}

steps中的一些操作

命令名 说明
error 抛出异常,中断整个pipeline
timeout timeout闭包内运行的步骤超时时间
waitUntil 一直循环运行闭包内容,直到return true,经常与timeout同时使用
retry 闭包内脚本重复执行次数
sleep 暂停pipeline一段时间,单位为秒
pipeline{
    agent any
    stages{
        stage('stash'){
            steps{
                timeout(50){  
                    waitUntil{  
                        script{
                            def r = sh script: 'curl http://xxx', returnStatus: true 
                            return (r == 0)  
                        }
                    }
                }
                retry(10){ 
                    script{
                        sh script: 'curl http://xxx', returnStatus: true
                    }
                }
                sleep(20) 
            }
        }
    }
    post{ 
        always{
            echo "结束job"
        }
    }
}

脚本式流水线

  • Jenkinsfile (Scripted Pipeline)
node { 					// 需要有一个或多个node节点表示一系列操作
    stage('Build') { 	//每个stage表示一个步骤
        // Build步骤内容
    }
    stage('Test') { 
        //  Test步骤内容
    }
    stage('Deploy') { 
        //  Deploy步骤内容
    }
}

声明式流水线的基本语法类似于脚本式流水线,但是其功能更加强大

Jenkinsfile (Declarative Pipeline)
pipeline { 			// pipeline是声明式流水线的一种特定语法,在块内定义了整个流水线的所有内容
    agent any 		// agent是声明式流水线的一种特定语法,它指示 Jenkins 为整个流水线分配一个执行器 (在节点上)和工作区,等效于脚本式流水线node块
    stages { 		// 所有流程(状态)的外层块,仅有一个
        stages('Build') { //每个stage为一流程,与脚本式基本一致,每个stage可以定义名称
            steps {  //步骤块,内部包含具体操作
                sh 'mkdir /data/jenkins'
                sh 'make'  // sh操作,其引号间的文字会当成shell直接执行
            }
        }
        stage('Test'){
            steps {
                sh 'curl -I http://192.168.152.147'
                sh 'make check'
                junit 'reports/**/*.xml'  //junit使用匹配的定义测试xml进行单元测试
            }
        }
        stage('Deploy') {
            steps {
                sh 'cp test.war  /usr/local/tomcat/webapps/'
                sh 'make publish'
            }
        }
    }
    stages {
        stage('Build') { //每个stage为一流程,与脚本式基本一致,每个stage可以定义名称
            steps {  //步骤块,内部包含具体操作
                sh 'make'  // sh操作,其引号间的文字会当成shell直接执行
            }
        }
        stage('Test'){
            steps {
                sh 'make check'
                junit 'reports/**/*.xml'  //junit使用匹配的定义测试xml进行单元测试
            }
        }
        stage('Deploy') {
            steps {
                sh 'make publish'
            }
        }  
    }
}
常见的 options(选项)
  • disableConcurrentBuilds():一时间最多只允许一个pipeline运行,如果前面的仍在运行, 后面的将会等待状态。
  • retry(1): 失败了,重试一次。
  • skipStagesAfterUnstable():如果某个stage为unstable状态,则忽略后面的任务,直接退出。
  • timeout(time: 10, unit: ‘MINUTES’):10分钟的超时设置。
  • newContainerPerStage(): agent为Docker或Dockerfile时,每个stage都分别运行在一个新容器中
  • skipDefaultCheckout(): 忽略默认的checkout。
  • buildDiscarder(logRotator(numToKeepStr: ‘10’, artifactNumToKeepStr: ‘1’)): 保留最新的10个build log和1个artifact。
  • error 抛出异常,中断整个pipeline
  • waitUntil 一直循环运行闭包内容,直到return true,经常与timeout同时使用
  • sleep 暂停pipeline一段时间,单位为秒
示例
pipeline{
    agent any
    options{
        buildDiscarder(logRotator(numToKeepStr: '10')
        disableConcurrentBuilds()
        retry(4)
        timeout(time:10, unit: 'HOURS')
    }
    stages{
        stage('demo'){
            steps{
                sh 'echo hello'
            }
        }
    }
}

来一个相对复杂一点的交互式Pipeline

pipeline{
    agent any
    triggers{
        upstream(upstreamProjects: 'job1,job2', threshold: hudson.model.Result.SUCCESS)
    }
    stages{
        stage('pre deploy'){
            steps{
                script{
                    BRANCHES = sh  returnStdout: true, script: 'git branch -r | grep -v HEAD > out.txt; git tag >> out.txt; cat out.txt;'
                    dataMap = input message: '准备发布到哪个环境', ok: '确定', parameters: [choice(choices: ['dev', 'sit', 'prod'], description: '部署环境', name: 'ENV'), choice(choices: "${BRANCHES}", description: '分支', name: 'TAG')], submitterParameter: 'APPROVER'
                }
            }
        }
        stage("演示一下"){
            steps{
                echo "${dataMap['APPROVER']}"
                echo "${dataMap['ENV']}"
                echo "${dataMap['TAG']}"
            }
        }
    }
}

你可能感兴趣的:(Jenkins-Pipeline语法篇- Pipeline指令)