2016-05-14 111 views
0

我正在编写一个脚本来创建一个使用Cloudformation模板和Ruby编排它的AWS堆栈。我想检查堆栈没有建立之前已经存在,因此有下面的代码片段string.include?不工作我的期望和我不明白为什么

puts("Checking that stack " + stackName + " doesn't already exist") 
puts 

stackExists = `aws cloudformation describe-stacks --stack-name #{stackName}` 

puts(stackExists) 


unless stackExists.include?("does not exist") 
    puts("Stack " + stackName + " already exists. Exiting.") 
    exit(100) 
end 

鉴于描述,堆栈的输出是包含字符串“不存在”,如果堆栈不存在,如果堆栈存在,我希望放入except块,如果不存在,则跳过它,但是,当堆栈不存在时,我的脚本的输出在下面。

Checking that stack myStack doesn't already exist 


A client error (ValidationError) occurred when calling the DescribeStacks operation: Stack with id myStack does not exist 

Stack myStack already exists. Exiting. 

如果我在irb中做了基本相同的事情,我得到了我期望的输出,如下所示。

irb(main):001:0> a = "A client error (ValidationError) occurred when calling the DescribeStacks operation: Stack with id myStack does not exist" 
=> "A client error (ValidationError) occurred when calling the DescribeStacks operation: Stack with id myStack does not exist" 
irb(main):002:0> a.include?("does not exist") 
=> true 

我在做什么错?

+1

至于我看到的,它应该用红宝石工作。我猜可能会有执行的'aws'命令发生不同的事情。你为什么不尝试在irb中执行命令而不是仅仅尝试使用字符串呢?在您的irb中执行'stackExists = \'aws cloudformation describe-stacks --stack-name#{stackName} \''和'stackExists.include?(“does not exist”)',看它是否仍然按预期工作。 此外,还尝试调用字符串对象上的'.strip',以便删除换行符。 'stackExists.strip.include?(“does not exist”)' – aBadAssCowboy

回答

1

啊非常感谢你,我现在可以看到发生了什么。我正在寻找的字符串将标准错误不标准出来,所以stackExists实际上等于零....我现在知道如何解决这个问题,谢谢!

我改变了代码如下疏导标准错误到标准输出作为反引号显然不允许您直接捕获标准错误,这现在可以按预期...

stackExists = `aws cloudformation describe-stacks --stack-name #{stackName} 2>&1`.strip 


unless stackExists.include?("does not exist") 
    puts("Stack " + stackName + " already exists. Exiting.") 
    exit(100) 
end 
+0

而不是说“我现在知道如何解决这个问题”,如果你发布如何解决它在答案 – aBadAssCowboy

+0

好点!我会更新我的答案。感谢您的建设性反馈。 –

相关问题