json 提取aws命令的输出并使用jq将其分配给bash中的变量

dtcbnfnu  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(135)

下面的aws命令输出下面的json,我想从其中提取具有字符串“vm-managed-itg* values”的资源(输出中的最后两个条目)
$aws资源组标记api获取资源--资源类型过滤器云监视:警报--配置文件访问|jq '.资源标记Map列表[]| select(包含({标签:[{关键字:“虚拟机:成本:帐户”} ]})|无)|select(包含({标签:[{值:“itg”} ]})|没有)“

{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-uat-test",
  "Tags": []
}
{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-stg-test",
  "Tags": []
}
{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-uat-test3",
  "Tags": []
}
{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-stg-test1",
  "Tags": []
}
{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-itg-test1",
  "Tags": []
}
{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-itg-test",
  "Tags": []
}

我尝试添加jq -r '.[].ResourceARN',但它不起作用,而是抛出此错误

~$ aws resourcegroupstaggingapi get-resources --resource-type-filters cloudwatch:alarm --profile per-acc --output json | jq '.ResourceTagMappingList[] | select(contains({Tags: [{Key: "vm:cost:accountenv"} ]}) | not) | select(contains({Tags: [{Value: "itg"} ]}) | not)' | jq -r '.[].ResourceARN'
jq: error (at <stdin>:4): Cannot index string with string "ResourceARN"
jq: error (at <stdin>:8): Cannot index string with string "ResourceARN"
jq: error (at <stdin>:12): Cannot index string with string "ResourceARN"
jq: error (at <stdin>:16): Cannot index string with string "ResourceARN"
jq: error (at <stdin>:20): Cannot index string with string "ResourceARN"
jq: error (at <stdin>:24): Cannot index string with string "ResourceARN"
pgx2nnw8

pgx2nnw81#

使用select仅返回符合条件的实体。可以使用contains测试子字符串匹配:

select(.ResourceARN|contains("vm-managed-itg"))

输出量:

{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-itg-test1",
  "Tags": []
}
{
  "ResourceARN": "arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-itg-test",
  "Tags": []
}

如果您只对ResourceARN的值感兴趣,而不对标记和周围对象感兴趣,则:

.ResourceARN | select(contains("vm-managed-itg"))

jq将过滤器应用于其输入(对象流)中的每个JSON实体。
输出量:

"arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-itg-test1"
"arn:aws:cloudwatch:us-east-1:xxxx:alarm:vm-managed-itg-test"

jq -r表示不带引号的原始输出)。

相关问题