我有一个类似的JSON文档:
{
"SecurityGroups": [
{
"GroupName": "database",
"GroupId": "sg-xxxxxx",
"VpcId": "vpc-yyyyyyy",
"IpPermissions": [
{
"FromPort": 22,
"ToPort": 22,
"IpProtocol": "tcp",
"IpRanges": [
{
"CidrIp": "10.200.0.0/16"
},
{
"CidrIp": "10.200.30.79/32"
},
{
"CidrIp": "10.200.42.0/24"
}
],
"UserIdGroupPairs": []
},
{
"FromPort": 5555,
"ToPort": 5555,
"IpProtocol": "tcp",
"IpRanges": [
{
"CidrIp": "10.200.0.0/16"
},
{
"CidrIp": "10.200.0.155/32"
}
],
"UserIdGroupPairs": []
},
{
"FromPort": 4506,
"ToPort": 4506,
"IpProtocol": "tcp",
"IpRanges": [
{
"CidrIp": "10.200.0.0/16"
}
],
"UserIdGroupPairs": []
}
]
}
]
}
我需要生成的输出如下:
sg-xxxxxx|database|22|22|tcp|10.200.0.0/16
sg-xxxxxx|database|22|22|tcp|10.200.30.79/32
sg-xxxxxx|database|22|22|tcp|10.200.42.0/24
sg-xxxxxx|database|5555|5555|tcp|10.200.0.0/16
sg-xxxxxx|database|5555|5555|tcp|10.200.0.155/32
sg-xxxxxx|database|4506|4506|tcp|10.200.0.0/16
我能够通过首先使用jq生成GroupId列表然后循环遍历列表以将数据过滤到jq两次来实现。我是这样做的:
cat json.in | jq -r '.SecurityGroups[]|"\(.GroupId) \(.GroupName)"' | while read groupid groupname
do
cat json.in | jq ".SecurityGroups[]|{GroupId,IpPermissions,IpPermissionsEgress}|select(.GroupId == \"$groupid\")" | jq -r '.IpPermissions[]|"\(.FromPort)|\(.ToPort)|\(.IpProtocol)|\(.IpRanges[].CidrIp)"' | sed "s/^/$groupid|$groupname|/"
done
我的解决方案很慢,我想改进它,任何指针?
答案 0 :(得分:4)
这是一种更有效的方法。使用-r
选项,以下过滤器
.SecurityGroups[]
| .GroupId as $gid
| .GroupName as $gname
| (.IpPermissions[], .IpPermissionsEgress[]?)
| .FromPort as $from
| .ToPort as $to
| .IpProtocol as $pro
| .IpRanges[]
| "\($gid)|\($gname)|\($from)|\($to)|\($pro)|\(.CidrIp)"
生成样本数据
sg-xxxxxx|database|22|22|tcp|10.200.0.0/16
sg-xxxxxx|database|22|22|tcp|10.200.30.79/32
sg-xxxxxx|database|22|22|tcp|10.200.42.0/24
sg-xxxxxx|database|5555|5555|tcp|10.200.0.0/16
sg-xxxxxx|database|5555|5555|tcp|10.200.0.155/32
sg-xxxxxx|database|4506|4506|tcp|10.200.0.0/16
请注意,这包括.IpPermissionsEgress[]?
,因为虽然您的示例数据中没有并且在脚本的第二部分中未使用它,但它仍然存在于示例脚本的第一部分中,所以我认为您可以打算包括它。