我正在尝试编写一个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过滤器,使我能够根据(一个或多个)属性字段筛选出特定的资源。
例如:
当过滤Type="AWS::EC2::InternetGateway“时,结果应该是
{
"Resources": {
"ig001": {
"Type": "AWS::EC2::InternetGateway",
"Properties": {
"Tags": [
{
"Key": "Name",
"Value": "ig001"
}
]
}
}
}
}一个额外的好处是能够过滤“或”编辑的值组合。因此,"AWS::EC2::InternetGateway“或"AWS::EC2::VPC”的筛选器应生成原始文档。
如有任何建议或见解,将不胜感激。
Tx!
发布于 2015-12-05 14:47:43
@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所指出的,现在只需指定一个更复杂的选择标准就可以了。}
发布于 2015-12-05 14:14:07
使用select()函数:
jq '.Resources[]|select(.Type=="AWS::EC2::VPC")' aws.json如果要按多个条件进行筛选,可以使用or,如下所示:
jq '.Resources[]|select(.Type=="AWS::EC2::VPC" or .Type=="foo")' aws.json发布于 2016-09-28 22:33:49
使用aws cli的-查询参数。完全消除了jq的需求。http://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html#controlling-output-filter
https://stackoverflow.com/questions/34105038
复制相似问题