我正在研究Jenkins DSL脚本,在该脚本中,我需要将一些值从Shell执行传递给Groovy变量。以下是代码-
sh ''' stopPrimary="$(aws ec2 describe-instances --instance-ids ${primaryInstanceId} 2>&1)"
stopSecondary="$(aws ec2 describe-instances --instance-ids ${secondaryInstanceId} 2>&1)"
stopTest="$(aws ec2 describe-instances --instance-ids i-323223232323 2>&1)"
'''
//Testing if both instances are stopped else throwing an error
if ( stopTest.contains("An error occurred") || stopSecondary.contains("An error occurred") ) {
error("One or more actions failed - ${stopPrimary} ${stopSecondary}")
} else {
echo "Storage Servers stopped now - Proceeding with Terraform apply"
}
我需要在shell执行中使用变量的值(stopPrimary,stopSecondary,stopTest)以在下一个if-else代码块中使用。但是,这似乎不起作用。
对我可能做错了任何事情吗?
谢谢
答案 0 :(得分:0)
您的sh
指令正在运行运行bash
的子进程。您的子进程将继承父进程的所有环境变量,并且可能会创建自己的一些变量。子进程死亡后,所有继承和创建的变量都将随之消失。
处理它的方法是以下两种方法之一:
sh "aws ec2 describe-instances --instance-ids ${primaryInstanceId}"
如果此命令返回非0状态,则管道将失败。您可以使用try { ... } catch () { ... }
将其包装起来以引发您自己的错误。
sh script: "...", returnStdout: true
,或者您可能希望将其写入文件并稍后将该文件真实化。