jenkins教程:jenkinsfile语法之Scripted pipeline脚本式语法

jenkins教程:jenkinsfile语法之Scripted pipeline脚本式语法_Test

Scripted pipeline

Scripted pipeline是基于groovy语法定制的一种DSL语言,它的灵活性更高,具有更好的可扩展性。

使用它需要了解一定的groovy语法知识,可参考如下文档:

请看下面的Scripted pipeline脚本,使用了if/else和try/catch/finally流程控制方法,无论构建状态是什么都发送邮件:

node('win_agent') {
    try {
        // 自动化测试 
        stage('Test') {
            TEST_STATU = bat (
                script: '''echo autotest''',
                returnStatus: true
            ) == 0
            
            if ("${TEST_STATU}" == "false") {
                catchError(stageResult: 'FAILURE') {
                    echo "测试未通过"
                    env.LOG = "测试未通过"
                }
            } else {
                echo "测试通过"
                env.LOG = "测试通过"
            }
        }
    } catch (exc) {
    	currentBuild.result = 'FAILURE'
        echo "Something failed, I'm in the catch block."
  	} finally {
    	stage("email") {
            emailext (
                subject: '\'构建通知:${PROJECT_NAME} - Build # ${BUILD_NUMBER} - ${BUILD_STATUS}\'',
                to: "XXXXXXXX@163.com", 
                body: '${FILE,path="email.html"}',
                )
        }
  }
}

DSL方法步骤

前面介绍Declarative pipeline和Scripted pipeline语法的实例中,使用到了一些方法步骤,比如shechoemailext等,它们是jenkins插件提供的一些方法步骤,下面举2个例子:

1、bat/sh方法:

STATU = bat (
                script: '''echo 666''',
                returnStatus: true
            ) == 0
echo ${STATU}

2、catchError方法:捕获到异常后,设置当前构建或者阶段状态设置为FAILURE,并继续执行Pipeline后面的步骤:

stage('Test') {
    STATU = bat (
                script: '''echo 666''',
                returnStatus: true
            ) == 0
    
    if ("${TEST}" == "false") {
        catchError(stageResult: 'FAILURE') {
            echo "测试未通过"
        }
    } else {
        echo "测试通过"
    }
}

也可以用try-catch来实现。


links:

https://devtest-notes.readthedocs.io/zh/latest/CI/continuous-integration-for-jenkins-pipeline.html