如何确保在运行Jenkins管道之前更新参数列表?

时间:2017-10-11 05:35:17

标签: jenkins jenkins-pipeline

Jenkins管道项目配置为从Git仓库获取其Jenkinsfile

Pipeline Def

如果我更改参数列表,例如,从:

properties([
        parameters([
                string(name: 'FOO', description: 'Choose foo')
        ])
])

为:

properties([
        parameters([
                string(name: 'FOO', description: 'Choose foo'),
                string(name: 'BAR', description: 'Choose bar')
        ])
])

运行构建,第一次运行不会显示新添加的BAR参数:

Parameter list not updated

由于更新的Jenkins文件需要BAR参数,这会导致更改后的第一个构建失败,因为没有向用户显示输入此值的输入。

有没有办法防止这种情况发生?在显示参数输入页面之前确保Jenkinsfile是最新的?

4 个答案:

答案 0 :(得分:4)

简短回答:不会。如果有一些工具可以解析和处理与构建分开的Jenkins文件,那就太好了。但是没有。

Jenkins在检索,解析和运行Jenkins文件之前不知道新参数,唯一的方法就是...运行构建。

实际上,构建历史记录将永远是"一个在后面运行"詹金斯文件;当您在Jenkinsfile中更改某些内容时,下一个版本将使用" old" Jenkinsfile,但在此之后接受并处理构建的新Jenkins文件。

答案 1 :(得分:2)

解决此问题的唯一方法是手动添加“ skip_run”布尔参数,而不是在作业的每个阶段添加when {}子句。

    properties([
        parameters([
                BooleanParameter(name: 'skip_run', description: 'Skips all stages. Used to update parameters in case of changes.', default: False)
        ])
    ])

...

stage('Doing Stuff') {
        when {
            expression { return params.skip_run ==~ /(?i)(N|NO|F|FALSE|OFF|STOP)/ }
        }
        steps {
            ...
        }
    }

当然,这很容易出错。

或者,您可以在流水线的开始处添加一个阶段,从而使有意构建失败。

stage('Update Build Info only') {
        when {
            expression { return params.skip_run ==~ /(?i)(Y|YES|T|TRUE|ON|RUN)/ }
        }
        steps {
            error("This was done deliberately to update the build info.")
        }
    }

更新: 感谢Abort current build from pipeline in Jenkins,我想出了以下解决方案:

要防止构建实际显示为红色,您可以尝试将其包装-优雅地捕获并退出构建。

final updateOnly = 'updateOnly'     
try {
      stage('Update Build Info only') {
            when {
                expression { return params.skip_run ==~ /(?i)(Y|YES|T|TRUE|ON|RUN)/ }
            }
            steps {
                error(updateOnly)
            }
        }
...
//other stages here
...
    } catch (e) {
      if (e.message == updateOnly) {
        currentBuild.result = 'ABORTED'
        echo('Skipping the Job to update the build info')
        // return here instead of throwing error to keep the build "green"
        return
      }
      // normal error handling
      throw e
    }

答案 2 :(得分:1)

我有一个跳过构建的函数,除非作业具有所有必需的参数,例如:

if (job.hasParameters(['FOO', 'BAR'])) {
    // pipeline code
}

答案 3 :(得分:0)

几年前,詹金斯报道了一个与此问题有关的问题 https://issues.jenkins-ci.org/browse/JENKINS-41929

仍然开放,所以还没有优雅的解决方案。