string.include?不按我的方式工作,我不明白为什么

时间:2016-05-14 08:43:59

标签: ruby

我正在编写脚本以使用Cloudformation模板创建AWS栈,并使用Ruby来编排它。我想在构建之前检查堆栈是否已经存在,因此请使用以下代码片段

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

鉴于describe-stacks的输出是包含"不存在的字符串"如果堆栈不存在,我希望在堆栈存在的情况下进入除非阻塞,如果不存在则跳过它,但是当堆栈没有时,我的脚本输出会低于已经存在。

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 个答案:

答案 0 :(得分:1)

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

我更改了代码如下,将标准错误转移到标准输出,因为后退标记显然不允许您直接捕获标准错误,现在这可以按预期工作...

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