如何处理Jenkins声明式管道中的每晚构建 [英] How to handle nightly build in Jenkins declarative pipeline

查看:92
本文介绍了如何处理Jenkins声明式管道中的每晚构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在仓库中有一个带有Jenkinsfile的多分支管道,并且我能够拥有我的CI工作流程(构建和单元测试-> deploy-dev->批准-> deploy-QA->批准-> deploy-prod ). 我想做的是在第一阶段构建&的夜间构建中添加SonarQube Analysis.单元测试. 由于我的构建是由Gitlab触发的,因此我将管道触发器定义如下:

I have a multibranch pipeline with a Jenkinsfile in my repo and I am able to have my CI workflow (build & unit tests -> deploy-dev -> approval -> deploy-QA -> approval -> deploy-prod) on every commit. What I would like to do is add SonarQube Analysis on nightly builds in the first phase build & unit tests. Since my build is triggerd by Gitlab I have defined my pipeline triggers as follow :

pipeline {
    ...
    triggers {
        gitlab(triggerOnPush: true, triggerOnMergeRequest: true, branchFilterType: 'All')
    }
    ...
}

要设置我的每晚版本,我已添加

To setup my nightly build I have added

triggers {
    ...
    cron('H H * * *')
}

但是,现在,如果我们仅构建夜间由cron表达式触发的作业,该如何执行分析步骤?

But now, how to execute analysis step if we are only building the job triggered by the cron expression at night ?

我的简化构建阶段如下:

My simplified build stage looks as follow :

stage('Build & Tests & Analysis') {
    // HERE THE BEGIN SONAR ANALYSIS  (to be executed on nightly builds)
    bat 'msbuild.exe ...'
    bat 'mstest.exe ...'
    // HERE THE END SONAR ANALYSIS (to be executed on nightly builds)
}

推荐答案

有一种获取构建触发器信息的方法.它在这里描述: https://jenkins.io/doc/pipeline/examples/#get-build -原因

There is the way how to get build trigger information. It is described here: https://jenkins.io/doc/pipeline/examples/#get-build-cause

也请您检查以下内容: 如何在工作流中获得$ CAUSE

It is good for you to check this as well: how to get $CAUSE in workflow

对于您的案例,很好的参考是 https://hopstorawpointers.blogspot.com/2016/10/performing-nightly-build-steps-with.html .这是该来源中的函数,它完全符合您的需求:

Very good reference for your case is https://hopstorawpointers.blogspot.com/2016/10/performing-nightly-build-steps-with.html. Here is the function from that source that exactly matches your need:

// check if the job was started by a timer
@NonCPS
def isJobStartedByTimer() {
    def startedByTimer = false
    try {
        def buildCauses = currentBuild.rawBuild.getCauses()
        for ( buildCause in buildCauses ) {
            if (buildCause != null) {
                def causeDescription = buildCause.getShortDescription()
                echo "shortDescription: ${causeDescription}"
                if (causeDescription.contains("Started by timer")) {
                    startedByTimer = true
                }
            }
        }
    } catch(theError) {
        echo "Error getting build cause"
    }

    return startedByTimer
}

这篇关于如何处理Jenkins声明式管道中的每晚构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆