Jenkins 脚本式 Pipeline 示例

Jenkinsfile (Scripted Pipeline)

node {  
    stage('Build') { 
        // 
    }
    stage('Test') { 
        // 
    }
    stage('Deploy') { 
        // 
    }
}
  • node:在任何可用代理上执行此管道或其任何阶段。
  • stage(‘Build’):定义 “Build” 阶段。stage 块在脚本化流水线语法中是可选的。然而, 在脚本化流水线中实现 stage 块,可以清楚的显示 Jenkins UI 中的每个 stage 的任务子集。
  • // :执行一些与 “Build” 阶段相关的步骤。
  • stage(‘Test’):定义 “Test” 阶段。
  • // :执行一些与 “Test” 阶段相关的步骤。
  • stage(‘Deploy’):定义 “Deploy” 阶段。
  • // :执行一些与 “Deploy” 阶段相关的步骤。

创建 Jeninsfile

node {
    stage('Build') {
        echo 'Building....'
    }
    stage('Test') {
        echo 'Testing....'
    }
    stage('Deploy') {
        echo 'Deploying....'
    }
}

构建 stage,并生成归档文件

node {
    stage('Build') {
        sh 'make' 
        archiveArtifacts artifacts: '**/target/*.jar', fingerprint: true 
    }
}

测试 stage,(sh ‘make check || true’)确保 sh stage 始终可以看到退出代码

node {
    /* .. snip .. */
    stage('Test') {
        /* `make check` returns non-zero on test failures,
         * using `true` to allow the Pipeline to continue nonetheless
         */
        sh 'make check || true' 
        junit '**/target/*.xml' 
    }
    /* .. snip .. */
}

部署 stage,currentBuild.result 变量允许 Pipeline 确定是否有任何测试失败。在这种情况下,该值为 UNSTABLE。

node {
    /* .. snip .. */
    stage('Deploy') {
        if (currentBuild.result == null || currentBuild.result == 'SUCCESS') { 
            sh 'make publish'
        }
    }
    /* .. snip .. */
}

引用全局环境变量

node {
    echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"
}

设置环境变量

node {
    /* .. snip .. */
    withEnv(["PATH+MAVEN=${tool 'M3'}/bin", 'DB_ENGINE=sqlite']) {
        sh 'mvn -B verify'
    }
}

处理参数

properties([parameters([
    string(defaultValue: 'Hello', description: 'How should I greet the world?', name: 'Greeting')
])])

node {
    echo "${params.Greeting} World!"
}

处理失败

node {
    /* .. snip .. */
    stage('Test') {
        try {
            sh 'make check'
        }
        finally {
            junit '**/target/*.xml'
        }
    }
    /* .. snip .. */
}

使用多个代理

stage('Build') {
    node {
        checkout scm
        sh 'make'
        stash includes: '**/target/*.jar', name: 'app' 
    }
}

stage('Test') {
    node('linux') { 
        checkout scm
        try {
            unstash 'app' 
            sh 'make check'
        }
        finally {
            junit '**/target/*.xml'
        }
    }
    node('windows') {
        checkout scm
        try {
            unstash 'app'
            bat 'make check' 
        }
        finally {
            junit '**/target/*.xml'
        }
    }
}

使用并发构建

node {
    stage('Build') {
        /* .. snip .. */
    }
    
    stage('Test') {
        failFast: true
        parallel linux: {
            node('linux') {
                checkout scm
                try {
                    unstash 'app'
                    sh 'make check'
                }
                finally {
                    junit '**/target/*.xml'
                }
            }
        }, windows: {
            node('windows') {
                /* .. snip .. */
            }
        }
    }
}

超时、重试

node {
    stage('Deploy') {
        retry(3) {
            sh './flakey-deploy.sh'
        }

        timeout(time: 3, unit: 'MINUTES') {
            sh './health-check.sh'
        }
    }
}

超时、重试组合使用

node {
    stage('Deploy') {
        timeout(time: 3, unit: 'MINUTES') {
            retry(5) {
                sh './flakey-deploy.sh'
            }
        }
    }
}

post 使用

node {
    try {
        stage('Test') {
            sh 'echo "Fail!"; exit 1'
        }
        echo 'This will run only if successful'
    } catch (e) {
        echo 'This will run only if failed'

        // Since we're catching the exception in order to report on it,
        // we need to re-throw it, to ensure that the build is marked as failed
        throw e
    } finally {
        def currentResult = currentBuild.result ?: 'SUCCESS'
        if (currentResult == 'UNSTABLE') {
            echo 'This will run only if the run was marked as unstable'
        }

        def previousResult = currentBuild.previousBuild?.result
        if (previousResult != null && previousResult != currentResult) {
            echo 'This will run only if the state of the Pipeline has changed'
            echo 'For example, if the Pipeline was previously failing but is now successful'
        }

        echo 'This will always run'
    }
}

在管道中发布 HTML 报告

properties([[$class: 'BuildDiscarderProperty',
                strategy: [$class: 'LogRotator', numToKeepStr: '10']]])

node {
  stage ('Build') {

    // Checkout
    checkout scm

    // install required gems
    sh 'bundle install'

    // build and run tests with coverage
    sh 'bundle exec rake build spec'

    // Archive the built artifacts
    archive includes: 'pkg/*.gem'

    // publish html
    publishHTML (target: [
        allowMissing: false,
        alwaysLinkToLastBuild: false,
        keepAll: true,
        reportDir: 'coverage',
        reportFiles: 'index.html',
        reportName: 'RCov Report'
    ])
  }
}

在管道中发送通知

node {

  notifyStarted()

  /* ... existing build steps ... */
}

def notifyStarted() {
  // send to Slack
  slackSend (color: '#FFFF00', message: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")

  // send to HipChat
  hipchatSend (color: 'YELLOW', notify: true,
      message: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})"
    )

  // send to email
  emailext (
      subject: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
      body: """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
        <p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>&QUOT;</p>""",
      recipientProviders: [[$class: 'DevelopersRecipientProvider']]
    )
}

将 shell 的值赋值给变量

node {
    def tag = sh(script: "git describe --tags --always", returnStdout: true).trim()
}

切换工作目录

node {
    dir('aaa') {
        //
    }
}

自定义工作空间

node {
    ws('aaa') {
        //
    }
}

清理工作空间

node {
    cleanWs()
}

清理工作空间中的目录

node {
    dir('aaa') {
        deleteDir()
    }
}

清理文件

node {
    cleanWs patterns: [[pattern: '*.bak', type: 'INCLUDE'], [pattern: '*.tmp', type: 'INCLUDE']]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值