gpt4 book ai didi

Jenkins:在全局函数体内获取环境变量

转载 作者:行者123 更新时间:2023-12-02 10:10:48 24 4
gpt4 key购买 nike

我在 PublishGitHub.groovy 上有一个共享的全局函数,如下所示:

#!/usr/bin/env groovy
def call(body)
{
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config

echo "\u001B[32mINFO: Publishing...\u001B[m"
body()
echo "\u001B[32mINFO: End Publish...\u001B[m"
}

还有我的 JenkinsFile 上的代码:

environment {
VERSION = "v1.3.${env.BUILD_NUMBER}"
}
stages {
stage ('Publish WebAPI'){
steps{
echo "\u001B[32mINFO: Start Publish...\u001B[m"

PublishGitHub{
echo "This is a body with version: ${env.VERSION}"
}
}
}
}

这是我的输出:

[Pipeline] echo
INFO: Start Publish...
[Pipeline] echo
INFO: Publishing...
[Pipeline] }

并遵循下一个错误:

java.lang.NullPointerException: Cannot get property 'VERSION' on null object

因为在体内我无权访问环境变量?

最佳答案

您的共享库代码在工作流 CPS 上下文之外运行,这就是为什么您传递给 vars 脚本的闭包无法识别 env属性(property)。您可以通过传递对工作流脚本的引用来解决此问题。如果你像这样调用你的函数

PublishGitHub(this) {
echo "This is a body with version: ${env.VERSION}"
}

然后您对 vars/PublishGitHub.groovy 应用一个小修改脚本如下:

#!/usr/bin/env groovy

def call(config, body) {
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config

echo "\u001B[32mINFO: Publishing...\u001B[m"
body()
echo "\u001B[32mINFO: End Publish...\u001B[m"
}

然后您将成功运行管道:

[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Publish WebAPI)
[Pipeline] echo
[32mINFO: Start Publish...[m
[Pipeline] echo
[32mINFO: Publishing...[m
[Pipeline] echo
This is a body with version: v1.3.537
[Pipeline] echo
[32mINFO: End Publish...[m
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

如果您想限制共享库的范围,您可以随时简单地传递 env而不是this并更改vars/PublishGitHub.groovy像这样的事情:

#!/usr/bin/env groovy

def call(env, body) {
def config = [
env: env
]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config

echo "\u001B[32mINFO: Publishing...\u001B[m"
body()
echo "\u001B[32mINFO: End Publish...\u001B[m"
}

在这种情况下,您仅授予共享库对环境变量的访问权限。

关于Jenkins:在全局函数体内获取环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52043397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com