2016-05-14 110 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

好點!我會更新我的答案。感謝您的建設性反饋。 –

相關問題