Jenkins pipelineJob DSL 不解释管道脚本中的变量

标签 jenkins groovy jenkins-pipeline pipeline dsl

我正在尝试使用 jobDSL 插件中的 pipelineJob 函数生成 Jenkins 管道,但无法将参数从 DSL 传递到管道脚本。我有几个项目使用基本上相同的 Jenkinsfile,仅在几个步骤中有所不同。我正在尝试使用 JobDSL 插件动态生成这些管道,其中我想要更改的值被解释为与 DSL 的参数匹配。

我已经尝试了在管道脚本和 DSL 中可以进行的几乎所有字符串解释组合,但无法让 Jenkins/groovy 解释管道脚本中的变量。

我在管道步骤中调用作业 DSL:

def projectName = "myProject"
def envs = ['DEV','QA','UAT']
def repositoryURL = 'myrepo.com'

jobDsl targets: ['jobs/*.groovy'].join('\n'), 
    additionalParameters: [
        project: projectName, 
        environments: envs, 
        repository: repositoryURL
    ],
    removedJobAction: 'DELETE',
    removedViewAction: 'DELETE'

DSL如下:

pipelineJob("${project} pipeline") {
    displayName('Pipeline')
        definition {
            cps { 
                script(readFileFromWorkspace(pipeline.groovy))
            }
        }
    }

管道.groovy:

pipeline {
    agent any

    environment {
        REPO = repository
    }

    parameters {
        choice name: "ENVIRONMENT", choices: environments
    }

    stages {
        stage('Deploy') {
            steps {
                echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
            }
        }
    }
}

我在 additionalParameters 中传递的变量在 jobDSL 脚本中被解释;确实生成了具有正确名称的管道。问题是变量没有传递给从工作区读取的管道脚本——生成的管道的 Jenkins 配置看起来与文件完全一样,没有对变量进行任何解释。

我做了很多尝试来解释字符串,包括“${environments}”、${environments}、$environments、\$environments 的很多变体……我找不到任何工作。我还尝试将文件作为 gstringImpl 读取:

script("${readFileFromWorkspace(pipeline.groovy)}")

有没有人知道如何让变量向下传播到管道脚本?我知道我可以只使用 for 循环在脚本文本上执行 string.replaceAll() ,但这看起来很麻烦;一定有更好的方法。

最佳答案

我想出了一种方法来完成这项工作。这不是我想要的,它在创建作业期间隐式解释文件的字符串内容,但它确实有效;它只是增加了一个额外的步骤。

import groovy.text.SimpleTemplateEngine

def fileContents = readFileFromWorkspace "pipeline.groovy"

def engine = new SimpleTemplateEngine()
template = engine.createTemplate(fileContents).make(binding.getVariables()).toString()

pipelineJob("${project} pipeline") {
    displayName('Pipeline')
    definition {
        cps { 
            script(template)
        }
    }
}

这会从您的工作区读取一个文件,然后将其用作具有绑定(bind)变量的模板。完成这项工作所需的其他更改是转义 Jenkinsfile 脚本中使用的任何变量,例如 \${VARIABLE} 以便它们在运行时扩展,而不是在您构建作业时扩展。您希望在创建作业时扩展的任何变量都应引用为 ${VARIABLE}

关于Jenkins pipelineJob DSL 不解释管道脚本中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331170/

相关文章:

git - ERROR : Couldn't find any revision to build. 验证此作业的存储库和分支配置

groovy - 在groovy中读写文件

jenkins - 如何有条件地在 groovy 中使用包装 block ?

jenkins-workflow - Jenkins Pipeline 为 jenkinsfile 拉取整个源代码

jenkins - 从管道内调用 Jenkins CLI

java - 在Java中测试MongoDB : concurrency problems

groovy - 如何使用groovy脚本将子元素动态添加到SOAPUI中的SOAP请求

maven - docker maven 镜像的 Jenkins 管道脚本退出状态 -1

docker - 如何使用 Jenkins 管道在 docker 容器中安装 Jenkins 工作区

gradle - 使用gradle时无法推断groovy类路径