如何将值从Shell执行传递给Jenkins变量?

时间:2020-03-15 11:59:02

标签: shell jenkins-pipeline aws-cli jenkins-job-dsl

我正在研究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代码块中使用。但是,这似乎不起作用。

对我可能做错了任何事情吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您的sh指令正在运行运行bash的子进程。您的子进程将继承父进程的所有环境变量,并且可能会创建自己的一些变量。子进程死亡后,所有继承和创建的变量都将随之消失。

处理它的方法是以下两种方法之一:

  1. 如果您仅需要了解命令成功还是失败,则可以依靠错误状态而不是错误消息。通常,如果运行成功,则linux命令返回0,否则返回非0。詹金斯在任何非0命令上使管道失败。因此,以下 就足够了:
sh "aws ec2 describe-instances --instance-ids ${primaryInstanceId}"

如果此命令返回非0状态,则管道将失败。您可以使用try { ... } catch () { ... }将其包装起来以引发您自己的错误。

  1. 如果需要稍后在管道中使用输出,则必须从输出中获取输出(例如,通过运行sh script: "...", returnStdout: true,或者您可能希望将其写入文件并稍后将该文件真实化。