我需要在Jenkins的多行shell脚本中访问Groovy定义的变量(例如var1)。我需要使用双引号"""在sh。 (我指的是here)
但我也需要读取和更改os系统变量(例如aws_api_key)。它需要使用单引号'''在sh并使用\来逃避美元$符号。 (我指的是here)
我如何同时使用它们?任何帮助都感激不尽。
e.g。
node ("Jenkins-Test-Slave") {
stage ("hello world") {
echo 'Hello World'
}
def var1="bin"
stage ("test") {
withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
echo var1
sh '''
echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
echo default value of aws_api_key is \$aws_api_key
aws_api_key='changed in shell'
echo new value of aws_api_key is \$aws_api_key
export newvar='newxxx'
echo the new var value is \$newvar
'''
}
}
}
结果是:
+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx
答案 0 :(得分:4)
使用多行GString('''
)来使字符串插值工作,而不是多行字符串("""
),然后${var1}
将按预期进行插值:
sh """
echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
echo default value of aws_api_key is \$aws_api_key
aws_api_key='changed in shell'
echo new value of aws_api_key is \$aws_api_key
export newvar='newxxx'
echo the new var value is \$newvar
"""
答案 1 :(得分:3)
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(isIn);
DOMHelper.useIdAsXmlId(doc.getDocumentElement());
KeyStore ks = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
ks.load(null, null);
CertificateValidationProvider validationProviderMySigs = new PKIXCertificateValidationProvider(ks, false, null);
XadesVerificationProfile instance = new XadesVerificationProfile(validationProviderMySigs);
XadesVerifier verifier = instance.newVerifier();
XAdESVerificationResult r = verifier.verify(getSigElement(doc), null);
所以,在你的情况下只需使用
def var1 = 'bin'
//the following are `groovy` strings (evaluated)
sh "echo var1 = $var1"
//outputs> echo var1 = bin
sh "echo var1 = ${var1}"
//outputs> echo var1 = bin
sh """echo var1 = ${var1}"""
//outputs> echo var1 = bin
sh "echo var1 = \$var1"
//outputs> echo var1 = $var1
//the following are usual strings (not evaluated)
sh 'echo var1 = $var1'
//outputs> echo var1 = $var1
sh '''echo var1 = $var1'''
//outputs> echo var1 = $var1