我正在尝试编写一个 JQ 过滤器,用于根据资源属性从 AWS cloudformation 模板中过滤特定资源。
例如,当从以下(缩短的)cloudformation 模板开始时:
{
"Resources": {
"vpc001": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": "10.1.0.0/16",
"InstanceTenancy": "default",
"EnableDnsSupport": "true",
"EnableDnsHostnames": "true"
}
},
"ig001": {
"Type": "AWS::EC2::InternetGateway",
"Properties": {
"Tags": [
{
"Key": "Name",
"Value": "ig001"
}
]
}
}
}
}
我想构建一个 jq-filter,使我能够根据(一个或多个)属性字段过滤特定资源。
例如:
过滤 Type="AWS::EC2::InternetGateway"时,结果应为
{
"Resources": {
"ig001": {
"Type": "AWS::EC2::InternetGateway",
"Properties": {
"Tags": [
{
"Key": "Name",
"Value": "ig001"
}
]
}
}
}
}
一个额外的好处是能够过滤“OR”组合的值。 因此,“AWS::EC2::InternetGateway”或“AWS::EC2::VPC”的过滤器应该生成原始文档。
任何建议或见解将不胜感激。
发送!
最佳答案
@hek2mgl 的建议可能足以满足您的目的,但它并不能完全产生您所要求的答案。这是一个非常相似的解决方案。它使用 jq 的 map() 和 map_values() 过滤器的泛化,这通常很有用:
def mapper(f):
if type == "array" then map(f)
elif type == "object" then
. as $in
| reduce keys[] as $key
({};
[$in[$key] | f ] as $value
| if $value | length == 0 then . else . + {($key): $value[0]}
end)
else .
end;
.Resources |= mapper(select(.Type=="AWS::EC2::VPC"))
使用您的示例输入:
$ jq -f resources.jq resources.json
{
"Resources": {
"vpc001": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": "10.1.0.0/16",
"InstanceTenancy": "default",
"EnableDnsSupport": "true",
"EnableDnsHostnames": "true"
}
}
}
正如 @hek2mgl 指出的那样,现在指定更复杂的选择标准很简单。 }
关于json - 使用JQ过滤cloudformation堆栈资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34105038/