2017-04-13 38 views
1

我正在編寫一些bash腳本來幫助自動管理AWS資源。我正在使用aws-clijq,到目前爲止情況非常好。基於嵌套值的jq過濾器陣列

我用自定義標籤標記我的資源。在某些情況下,我想根據自定義標記的KeyValue篩選資源列表。但是我在編制一個簡潔的jq查詢時遇到了麻煩。

因此,舉例來說,如果(修剪)JSON輸出爲我的EC2實例是這樣的:

[ 
    { 
     "PublicIpAddress": "11.22.33.44", 
     "PrivateIpAddress": "55.66.77.88", 
     "Tags": [ 
      { 
       "Value": "live199.blah.com", 
       "Key": "Name" 
      }, 
      { 
       "Value": "live-standalone", 
       "Key": "hc-class" 
      } 
     ] 
    } 
] 
[ 
    { 
     "PublicIpAddress": "111.222.333.444", 
     "PrivateIpAddress": "555.666.777.888", 
     "Tags": [ 
      { 
       "Value": "staging99.blah.com", 
       "Key": "Name" 
      }, 
      { 
       "Value": "staging-standalone", 
       "Key": "hc-class" 
      } 
     ] 
    } 
] 

...我需要找到在哪裏Tags.Key == "hc-class"Tags.Value = "staging-standalone",我怎麼做它在入門一個簡潔的方式與jq

任何幫助非常感謝。

+1

你可以直接從aws CLI使用JMESPATH來做,看看這個問題http://stackoverflow.com/questions/43354116/using-jmespath-and-aws-ec2-describe-instances-to-output-multiple-標籤值,其中詳細說明了一些示例如何使用該功能 –

+0

「入門」是什麼意思?由於「標籤」是一個數組,因此納入標準還不清楚。如果你給出了預期的輸出,這可能會有所幫助 – peak

+0

[使用jq通過匹配多個對象來過濾JSON對象列表]的可能重複(http://stackoverflow.com/questions/33973816/filtering-json-object-list-with-jq-by-matching-multiple-objects) –

回答

2

在給定的輸入,下面的過濾器生成的輸出,如下圖所示:

.[] | select(any(.Tags[]; .Key == "hc-class" and .Value == "staging-standalone")) 

輸出:

{ 
    "PublicIpAddress": "111.222.333.444", 
    "PrivateIpAddress": "555.666.777.888", 
    "Tags": [ 
    { 
     "Value": "staging99.blah.com", 
     "Key": "Name" 
    }, 
    { 
     "Value": "staging-standalone", 
     "Key": "hc-class" 
    } 
    ] 
} 
+0

太棒了。這正是我需要的。乾杯! –