【问题标题】:Accessing jenkins env params from inside a GroovyScript in properties从属性中的 GroovyScript 内部访问 jenkins env 参数
【发布时间】:2020-03-08 09:18:16
【问题描述】:

我有一份詹金斯的工作:

properties([
    parameters([
        [$class: 'ChoiceParameter', choiceType: 'PT_CHECKBOX', description: '''The name of the image to be used.''', filterLength: 1, filterable: true, name: 'OS', randomName: 'choice-parameter-15413073438404172', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: true, script: ''], script: [classpath: [], sandbox: true, script: '''templates = [
        "BB-Win7-x32-SP1",
        "BB-Win7-x64-SP1",
        "BB-Win10-x64-RS1",
        "BB-Win10-x64-RS2",
        "BB-Win10-x32-RS5"]

        return templates''']]]])
])
....
....

这是按预期工作并为 GUI 生成复选框属性。

现在,我想根据工作空间中的文件动态生成这些选项。为此,我需要 groovy 脚本中的 workspace 环境变量。我该怎么做?

【问题讨论】:

  • 要运行你的 groovy 脚本(从 Git 检出工作区后需要读取工作区中文件的脚本...)Jenkins 需要创建参数。为了创建参数,它需要运行一个 groovy 脚本。你在这里遇到了一些先有鸡还是先有蛋的问题。你看过 ActiveChoice 插件吗?
  • 我所说的 groovy 脚本并不是实际的管道。这是ChoiceParameter 类中的脚本。
  • 这就是 ActiveChoice 可以实现的。

标签: jenkins jenkins-pipeline jenkins-groovy


【解决方案1】:

Jenkins 需要在运行管道之前弄清楚所有参数。因此,您的问题基本上归结为“如何在运行管道之前运行(任意)groovy 脚本?”

有两种选择:

  1. 正如我所提到的,ActiveChoice 插件允许您定义返回脚本的参数。然后 Jenkins 将运行脚本(不要忘记批准它),以向您显示“使用参数构建”页面。调试这个是出了名的困难,但这可能会很费劲。

  2. 或者,您可能希望在运行声明式(主要)管道之前运行脚本化管道,如概述,例如在this answer。这可能看起来有点像这样:

def my_choices_list = []

node('master') {
   stage('prepare choices') {
       // read the file contents
       def my_choices = sh script: "cat ${WORKSPACE}/file.txt", returnStdout:true
       // make a list out of it - I haven't tested this!
       my_choices_list = my_choices.trim().split("\n")
   }
}

pipeline {
   parameters { 
        choiceParam('OPTION', my_choices_list)

【讨论】:

  • returnOutput 应该是 returnStdout。但为什么不直接使用readFile 'file.txt'
  • 已修复,关于后者,我通常以cat 开头,因为您可以根据用例将其通过管道传输到grepawksed,我更喜欢在bash 而不是 groovy。但是对于简单的情况,readFile 也可以。
猜你喜欢
  • 2016-08-15
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多