Condition in Jenkins pipeline on the triggers directive

一笑奈何 提交于 2020-12-12 11:36:33

问题


Jenkins has a nice relatively comprehensive documentation about Jenkinsfile syntax. But I still not find there an answer is it possible to do a flow control on the top level of pipeline? Literally include something if just in pipeline {} section (Declarative) like:

pipeline {
    if (bla == foo) {
        triggers {
            ...configuration
        }
} 

or

pipeline {
    triggers {
        if (bla == foo) {
            something...
        }
    }
} 

triggers section is a section which can be included only once and only in the pipeline section. But if statement has to be applied only in stage level seems.

Do anyone know how to conditionally include something in direcitves, such as, triggers, or conditionally include directives itself?


回答1:


You can't use flow control in a pipeline outside of when and script, but you can call functions for things like trigger parameters:

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

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

Another way is to generate your pipeline script dynamically using 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') }"
    } 
}


来源:https://stackoverflow.com/questions/61106044/condition-in-jenkins-pipeline-on-the-triggers-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!