Jenkins 管道中触发器指令的条件

Mik*_* P. 5 jenkins jenkins-groovy jenkins-pipeline jenkins-declarative-pipeline

Jenkins 有一个很好的相对全面的关于 Jenkinsfile 语法的文档。但是我仍然没有找到答案是否可以在管道的顶层进行流量控制?从字面上看,if仅在pipeline {}部分(声明性)中包含一些内容,例如:

pipeline {
    if (bla == foo) {
        triggers {
            ...configuration
        }
} 
Run Code Online (Sandbox Code Playgroud)

或者

pipeline {
    triggers {
        if (bla == foo) {
            something...
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

triggerssection 是一个只能包含一次并且只能包含在该pipeline部分中的部分。但是if语句似乎只适用于阶段级别。

有谁知道如何triggers有条件地包含指令中的某些内容,例如, 或有条件地包含指令本身?

zet*_*t42 10

您不能在when和之外的管道中使用流控制script,但您可以为触发器参数之类的东西调用函数:

pipeline {
    agent any
    triggers{ cron( getCronParams() ) }
    ...
}

def getCronParams() {
    if( someCondition ) {
        return 'H */4 * * 1-5'
    }
    else {
        return 'H/30 */2 * * *'
    } 
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用evaluate()以下方法动态生成管道脚本:

evaluate """
pipeline {
    agent any        
    ${getTriggers()}    
    ...
}
"""

String getTriggers() {
    if( someCondition ) {
        return "triggers{ cron('H */4 * * 1-5') }"
    }
    else {
        return "triggers{ pollSCM('H */4 * * 1-5') }"
    } 
}
Run Code Online (Sandbox Code Playgroud)