gpt4 book ai didi

Jenkins 将阶段计算的值传递给 shell 脚本

转载 作者:行者123 更新时间:2023-12-02 20:23:12 26 4
gpt4 key购买 nike

我正在尝试通过 Jenkins 声明性管道将提交消息连接字符串传递到 shell 脚本。我可以得到连接的字符串,但我不知道如何将它传递给我的 shell 脚本。环境变量在我的 shell 脚本中是可读的,但我无法在阶段之外设置环境变量,因为阶段是我定义 git 连接的地方,如果我在阶段中设置它,它不会更新我调用的环境变量在我的帖子部分。如何将changeString 的值传递给我的bash 脚本(成功)?

pipeline { 
agent any
environment {
CHANGE_STRING = 'Initial default value.'
}
stages {
stage('Build') {
environment {
CHANGE_STRING = 'This change is only available in this stage and not in my shell script'
}
steps {
echo 'Build stage'
git branch: 'develop',
credentialsId: 'blah',
url: 'blah.git'
sh """
npm install
"""
script{
MAX_MSG_LEN = 100
def changeString = ""

def changeLogSets = currentBuild.changeSets
for (int i = 0; i < changeLogSets.size(); i++) {
def entries = changeLogSets[i].items
for (int j = 0; j < entries.length; j++) {
def entry = entries[j]
truncated_msg = entry.msg.take(MAX_MSG_LEN)
changeString += " - ${truncated_msg} [${entry.author}]\n"
}
}

if (!changeString) {
changeString = " - No new changes"
}
//I would like to set CHANGE_STRING here
}
}
}
}
post {
success {
echo 'Successfull build'
sh """
bash /var/lib/jenkins/jobs/my-project/hooks/onsuccess
"""
}
}
}

最佳答案

如果你想从script导出环境变量步骤并在当前阶段之外访问它,您必须使用全局或本地中未指定的变量名 environment {}堵塞。考虑以下示例:

pipeline { 
agent any
environment {
IMMUTABLE_VARIABLE = 'my value'
}
stages {
stage('Build') {
steps {
script{
def random = new Random()
if (random.nextInt(2) == 1) {
env.CHANGE_STRING = "Lorem ipsum dolor sit amet"
} else {
env.CHANGE_STRING = "Foo Bar"
}

env.IMMUTABLE_VARIABLE = 'a new value'

echo "IMMUTABLE_VARIABLE = ${env.IMMUTABLE_VARIABLE}"
}
}
}
}
post {
success {
echo 'Successfull build'
sh '''
echo $CHANGE_STRING
echo "IMMUTABLE_VARIABLE = $IMMUTABLE_VARIABLE"
'''
}
}
}

这只是管道脚本的简化。当我运行它时,我看到以下控制台输出:

[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
IMMUTABLE_VARIABLE = my value
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
Successfull build
[Pipeline] sh
[test-pipeline] Running shell script
+ echo Foo Bar
Foo Bar
+ echo IMMUTABLE_VARIABLE = my value
IMMUTABLE_VARIABLE = my value
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

成功后的 shell 脚本 block 打印 Foo Bar在第一行和 IMMUTABLE_VARIABLE = my value在第二个中。另请注意,即使我已明确尝试覆盖

env.IMMUTABLE_VARIABLE = 'a new value'

它没有产生任何效果,当我做到了

echo "IMMUTABLE_VARIABLE = ${env.IMMUTABLE_VARIABLE}"

它只是回显 environment {} 中的初始值 block :

IMMUTABLE_VARIABLE = my value

希望有帮助。

关于Jenkins 将阶段计算的值传递给 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50771844/

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