gpt4 book ai didi

jenkins - 在 Jenkins Pipeline 的 shell 脚本部分定义变量

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

我正在尝试动态定义稍后在 Jenkins 管道的一些 shell 命令中使用的变量,并且它抛出异常。我什至尝试从环境部分预定义变量,但无济于事。这是禁止操作吗?我的另一个变量 myVar 似乎工作正常,但它是管道中的常量。

pipeline {
agent any

environment {
py2Ana=""
myVar="ABCDE"
}
stages {
stage('Stage1') {
steps {
sh """
echo myVar=$myVar
echo Find Anaconda2 Python installation...
py2Ana=`which -a python | grep --max-count=1 anaconda2`
if [[ -z "$py2Ana" ]]; then
echo ERROR: must have a valid Anaconda 2 distribution installed and on the PATH for this job.
exit 1 # terminate and indicate error
fi
"""
}
}
}

异常

groovy.lang.MissingPropertyException: No such property: py2Ana for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:242)
at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:288)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:292)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:268)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:268)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:21)

最佳答案

正如 @jxramos 所说,Jenkins 正在尝试解析脚本中的变量。它将任何 $string 解释为需要替换的变量。解决方案是对脚本内变量的 $ 进行转义,如下所示:

pipeline { 
agent any
stages {
stage('test stage'){
steps {
sh """#!/bin/bash
myvar=somevalue
echo "The value is \$myvar"
"""
}
}
}
}

关于jenkins - 在 Jenkins Pipeline 的 shell 脚本部分定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407976/

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