Jenkinsfile 模板 简记

基本功能模板

用于:速查 + 抽离

模板1

#!groovy
// https://www.jenkins.io/zh/doc/book/pipeline/
// https://zeyangli.github.io/chapter5/2/
// https://zeyangli.github.io/chapter5/1/
// https://github.com/zeyangli


String workspace = "/opt/jenkins/workspace"         // 定义工作目录

// pipeline
pipeline{
    agent {
        node {
            label "any"                             // 指定节点的标签与名称
            customWorkspace "${workspace}"          // 指定运行工作目录(可选)
        }
    }
    
    triggers {                                      // 触发器定期执行 
        cron("H */4 * * 1-5")                       // 计划任务
        pollSCM("H */4 * * 1-5")                    // 定期检测源码变化
        // 当字符串中任何job以最小阈值结束时,流水线被重新触发
        upstream(upstreamProjects: "job1,job2", threshold: hudson.model.Result.SUCCESS)
    }

    parameters {                                    // 参数化构建 == 字符 + 布尔 + 选择
        string(name: "ENV", value: "${ENV}", defaultValue: "staging", description: "")
        booleanParam(name: "try_test", defaultValue: true, description: "")
    }

    environment {                                   // 声明环境变量
        CC = "clang"
        email_to = "test@163.com"
    }

    tools {                                         // 全局工具配置
        maven "apache-maven-3.0.1"
    }

    options {
        timestamps()                                //日志时间 == 需要插件Timestamper
        skipDefaultCheckout()                       // 删除隐式checkout scm语句 == 我觉得应该保留
        disableConcurrentBuilds()                   // 禁止并行
        timeout(time: 1, unit: "HOURS")             //流水线超时设置
        
    }

    stages {                                        // 阶段
        // download code
        stage("getcode"){                           //阶段名称(指令)
            when {
                environment name: "test", value: "production"
            }
            // 听课
            steps{                                  // 步骤
                timeout(time: 5, unit: "MINUTES")   //流水线步骤超时设置
                    script{                         //运行脚本
                        println("获取代码")
                    }
                    echo "hello world"
                    sh "mvn --version"
            }
            // 可用
            steps {
                // 环境变量交互
                // build_number: 跑第几次任务流
                // job_name: 任务名称

                echo "BUILD_NUMBER: ${BUILD_NUMBER}"
                echo "JOB_NAME: ${JOB_NAME}"
            }
        }

        // 构建代码
        stage("buildcode"){ 
            steps{
                timeout(time: 20, unit: "MINUTES")  //流水线步骤超时设置
                    script{                         //运行脚本
                        println("应用打包")

                        mvnHome = tool "m2"
                        println(mvnHome)
                    }
            }
        }
        // 失败后多次尝试执行 retry + pipeline调度pipeline的方法
        stage("try test") {
            when {expression {params.try_test == true}}
            steps {
                withCredentials([file(credentialsId: "test", variable: "test")])
                retry(6) {
                    sh '''
                    set +x     # 执行指令后,会关闭先显示该指令及所下的参数。
                    sleep 10
                    python3 test.py 

                    ### 调度另外一个任务,pipeline call pipeline
                    CallJenkinsJob=${JOB_NAME%/*}/CallJenkinsJob  # 相同工作目录下
                    echo -n ${CallJenkinsJob} > CallJenkinsJob.txt

                    REPO_NAME=${basename ${GIT_URL%.*}}
                    '''
                }
                script {
                    CallJenkinsJobName = readFile("CallJenkinsJob.txt").trim()
                    def CallJenkinsJobResult = build job: "${CallJenkinsJobName}", parameters [
                        string(name: "ENV", value: "${ENV}", defaultValue: "staging", description: "")
                        booleanParam(name: "debug", defaultValue: true, description: "")
                    ]
                }
                // 获取当前的任务描述的方法
                script {
                    // 方式1
                    currentBuild.description = readFile("${WORKSPACE}/DES.txt")
                    // 方式2
                    output_currentBuild = "<table>${foo}|${foo-1}</table>"
                    currentBuild.description = output_currentBuild
                }

            }
        }


        // 代码扫描
        stage("codescan"){                          //阶段名称
            environment {
                AN_ACCESS_KEY = credentials("prefined-secret-text")
            }

            steps{
                timeout(time: 30, unit: "MINUTES")  //流水线步骤超时设置
                    script{                         //运行脚本
                        print("代码扫描")
                        sh "printenv"
                    }
            }
        }

        // 用户交互模式
        stage("example"){
            // 通过流水线语法pipeline-syntax查询input方法的使用与创建
            input {
                id: "test",
                message: "should we continue? ",      // 提示信息
                ok: "yes do it",
                parameters: [
                    string(name: "PERSON", defaultValue: "Mr jenkins", description: "")
                ],
                submitter: "alice,bob"               // 限制谁能提交
            }
        }
    }

    // 构建后操作
    post {  // 与stages 同一层级
        always {                                    //总是执行脚本
            script{
                println("always")
                echo "clean up the job workspace"
                cleanWs()                           // 清楚工作空间
            }
        }

        success {                                   //成功后执行
            script{
                // currentBuild全局变量 + description构建描述
                currentBuild.description = "\n build success"
            }
            sh("build success")
            mail bcc: "", cc: "", body: "<b>Dear Team,<b><br>The below Jenkins job was failed<br>${BUILD_URL}",
                charset: "UTF-8", mimeType: 'text/html', to: "${email_to}", subject: "test ${BUILD_NUMBER} ${GIT_BRANCH}"
        }

        failure {                                   //失败后执行
            script{
                currentBuild.description = "\n build failure"
            }
        }

        aborted {                                   //手动取消后执行
            script{
                currentBuild.description = "\n build aborted"
            }
        }

        unstable {                                  //阶段状态为unstable or 测试失败
            script{
                currentBuild.description = "\n build unstable"
            }
        }
    }

}

模板2

pipeline {
    parameters {
        booleanParam(name: "NEW_FUNCTION_NAME",defaultValue: true, description: "")
        choice(name: "env", choices: ['dev', 'uat', 'prod'], description: "")
        string(name: "jobtest", defaultValue: "test", description: "")
    }

    stages {
        stage("ENV") {
            steps {
                
                wrap([$class: "BuildUser"]) {
                    script {
                        env["BUILD_USER_EMAIL"] = "${env.BUILD_USER_EMAIL}"
                        env["BUILD_USER"] = "${BUILD_USER}"
                        env["BUILD_USER_ID"] = "${BUILD_USER_ID}"

                        echo "${BUILD_USER_ID} ${BUILD_USER} ${BUILD_USER_EMIAL}"
                    }
                }

                sh '''
                ### create new functions 
                NEW_FUNCTION_NAME = ${<URL>}
                echo -n ${NEW_FUNCTION_NAME} > NEW_FUNCTION_NAME.txt
                '''
                script {
                    env["NEW_FUNCTION_NAMEJobName"] = readFile('NEW_FUNCTION_NAME.txt').trim()
                }
                sh '''
                echo "NEW_FUNCTION_NAMEJobName: ${NEW_FUNCTION_NAME}" 
                '''
            }
        }
        
        stage("try") {
            steps {
                script {
                    try {
                        withCredentials([usernamePassword(credentialsId: 'OSS', passwordVariable: "OSS", usernameVariable: 'OSS')]) {
                        sh '''
                        set +x
                        source ${OSS}
                        export OSS_INFO=${OSS_INFO}
                        '''
                        }
                    }catch(Exception err){
                        env.NEW_FUNCTION_NAME_Success = "False"
                        echo "error"
                    }
                }
            }
        }

        stage("NEW_FUNCTION_NAME") {
            when { expression {params.NEW_FUNCTION_NAME == true}}
            steps {
                script {
                    def NEW_FUNCTION_NAMEResult = build job: "${NEW_FUNCTION_NAMEJobName}", parameters: [
                        string(key: "foo", value: "${foo}")
                    ]
                    env["NEW_FUNCTION_NAME_Success"] = NEW_FUNCTION_NAMEResult.buildVariables["NEW_FUNCTION_NAME"]
                    if (NEW_FUNCTION_NAME_Success == "False") {
                        error "NEW_FUNCTION_NAME build false ${NEW_FUNCTION_NAME_Success}"
                    }
                }
            }
        }

        stage("credential") {
            steps {
                withCredentials([file(credentialsId: "ACK_SA", variable: "ACK"), usernamePassword(credentialsId: "ACK-1", passwordVariable: "ACK-1", usernameVariable: "ACK-1")]) {
                    sh '''
                    set +x
                    source ${ACK_SA}
                    '''
                }
            }
        }

        stage("allof") {
            when {
                allOf {
                    expression { env.NEW_FUNCTION_NAME_Success != "False"}
                }
            }
            steps {
                sh """
                echo "success"
                sh -ex test.sh 123.sh
                """
            }
        }

    }
    post {}
}

 具体功能

请留意层级关系,对应修改

邮件发送

    post {  // 与stages 同一层级
        success {                                   //成功后执行
            mail bcc: "", cc: "", body: "<b>Dear Team,<b><br>The below Jenkins job was failed<br>${BUILD_URL}",
                charset: "UTF-8", mimeType: 'text/html', to: "${email_to}", subject: "test ${BUILD_NUMBER} ${GIT_BRANCH}"
        }
    }

清楚工作空间

优化缓存

    post {  // 与stages 同一层级
        always {                                    //总是执行脚本
            script{
                println("always")
                echo "clean up the job workspace"
                cleanWs()                           // 清楚工作空间
            }
        }
    }

 parameters

常用的3种,还有密码账户等特殊定义需要进一步了解

    parameters {
        booleanParam(name: "NEW_FUNCTION_NAME",defaultValue: true, description: "")
        choice(name: "env", choices: ['dev', 'uat', 'prod'], description: "")
        string(name: "jobtest", defaultValue: "test", description: "")
    }

 构建者信息交互

    stages {
        stage("ENV") {
            steps {
                wrap([$class: "BuildUser"]) {
                    script {
                        env["BUILD_USER_EMAIL"] = "${env.BUILD_USER_EMAIL}"
                        env["BUILD_USER"] = "${BUILD_USER}"
                        env["BUILD_USER_ID"] = "${BUILD_USER_ID}"

                        echo "${BUILD_USER_ID} ${BUILD_USER} ${BUILD_USER_EMIAL}"
                    }
                }
            }
        }
    }

try + catch 实现 debug

stage("try") {
    steps {
        script {
            try {
                sh '''
                set +x
                echo hello
                '''                        
            }catch(Exception err){
                echo "error"
            }
        }
    }
}

allOf 的条件判断

        stage("allof") {
            when {
                allOf {
                    expression { env.NEW_FUNCTION_NAME_Success != "False"}
                }
            }
            steps {
                sh """
                echo "success"
                sh -ex test.sh 123.sh
                """
            }
        }

 获取当前的任务描述的方法

script {
    // 方式1
    currentBuild.description = readFile("${WORKSPACE}/DES.txt")
    // 方式2
    output_currentBuild = "<table>${foo}|${foo-1}</table>"
    currentBuild.description = output_currentBuild
}

 pipeline 调度 pipeline (build job)

pipeline {
    parameters {
        booleanParam(name: "NEW_FUNCTION_NAME",defaultValue: true, description: "")
        choice(name: "env", choices: ['dev', 'uat', 'prod'], description: "")
        string(name: "jobtest", defaultValue: "test", description: "")
    }

    stages {
        stage("ENV") {
            steps {
                sh '''
                ### create new functions 
                NEW_FUNCTION_NAME = ${<URL>}
                echo -n ${NEW_FUNCTION_NAME} > NEW_FUNCTION_NAME.txt
                '''
                script {
                    env["NEW_FUNCTION_NAMEJobName"] = readFile('NEW_FUNCTION_NAME.txt').trim()
                }
                sh '''
                echo "NEW_FUNCTION_NAMEJobName: ${NEW_FUNCTION_NAME}" 
                '''
            }
        }

        stage("NEW_FUNCTION_NAME") {
            when { expression {params.NEW_FUNCTION_NAME == true}}
            steps {
                script {
                    def NEW_FUNCTION_NAMEResult = build job: "${NEW_FUNCTION_NAMEJobName}", parameters: [
                        string(key: "foo", value: "${foo}")
                    ]
                }
            }
        }

    }
    post {}
}

查看目前的Jenkins环境变量

pipeline {
    agent any

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

 10分钟搞定让你困惑的 Jenkins 环境变量 - 知乎 (zhihu.com)

retry

全局配置,假如pipeline失败,重新跑这条pipeline多少次

pipeline {
    agent any
    options {
    	timeout (time: 1, unit: 'HOURS')
    	buildDiscarder(logRotator(numToKeepStr: '2')
    	retry(5)
	}
    stages {
        stage('init') {
            options {
                timeout(time: 30, unit: 'SECONDS') 
            }
            steps {
                echo 'Hello World'
            }
        }
    }
}

局部重试,假如这个stage失败,重跑多少次

stage("retry test") {
    steps {
        retry(6) {
            sh '''
            set +x     # 执行指令后,会关闭先显示该指令及所下的参数。
            sleep 10
            '''
        }
    }
}

 他人参考总结

持续集成:Jenkins Pipeline语法介绍 - 测试开发小记 - 博客园 (cnblogs.com)

  1. 流水线
  2. Pipeline Syntax
  3. 流水线语法
  4. Matrix building in scripted pipeline

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值