本文介绍了是否可以从流水线步骤动态设置Jenkins作业参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简化的)詹金斯管道代码.

I have the following (simplified) Jenkins pipeline code.

jobParams.groovy

jobParams.groovy

List get(Object paramVars = {}) {

    def params = []


    params += [
        choice(
            choices: ['branch', 'tag'],
            name: 'RELEASE_TYPE'
        ),
        string(
            defaultValue: '',
            name: 'VERSION'
        ),
    ]

    return params
}

pipeline.groovy

pipeline.groovy

def call() {

    properties([
        parameters(
            jobParams.get()
        )
    ])

    pipeline {
        agent { label 'deploy-slave' }

        stages {
            stage('Prepare') {
                steps {
                    script {
                        // Do some logic here and set a job parameter?
                    }
                }
            }
        }
    }
}

这很好.当管道启动时,作业参数将被设置,并在下次运行时可用.

This works fine. When the pipeline starts the job parameters are set and available for the next time the job runs.

但是,在流水线步骤中执行某些逻辑之后,是否还可以动态设置作业参数?

However, is it also possible to set job parameters dynamically after some logic in a pipeline step?

推荐答案

事实证明非常简单!

我在共享管道库中创建了一个jobProperties.groovy文件,该文件组成参数列表并调用properties()函数.

I created a jobProperties.groovy file in my shared pipeline library, which composes the parameter list and calls the properties() function.

def call() {
    params = [
        string(
            defaultValue: '',
            description: 'Version to deploy',
            name: 'VERSION'
        ),
    ]

    if (env.HANDLER == 'ansible') {
        params += [
            string(
                defaultValue: '',
                description: 'DEPLOY_ARGS | Ad hoc "ansible-playbook" args. Example to limit hosts to' +
                    ' deploy to "-l somehost"',
                name: 'DEPLOY_ARGS'
            ),
        ]
    } else if (env.HANDLER == 'capistrano') {
        params += [
            string(
                defaultValue: '',
                description: 'DEPLOY_ARGS | Ad hoc "cap" args. Example to limit hosts to' +
                    ' deploy to "-z somehost"',
                name: 'DEPLOY_ARGS'
            ),
        ]
    }

    properties([
        parameters(
            params
        )
    ])
}

pipeline.groovy

pipeline.groovy

def call() {
    pipeline {
        agent { label 'deploy-slave' }

        stages {
            stage('Prepare') {
                steps {
                    script {
                        jobProperties()
                    }
                }
            }
        }
    }
}

我认为,如果您没有共享的管道库,那么jobParams.groovy的代码也可以直接放在管道的脚本{}包装器中.

I think that if you don't have a shared pipeline library, the code of jobParams.groovy can be also put directly in the script {} wrapper of the pipeline.

这篇关于是否可以从流水线步骤动态设置Jenkins作业参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:02