简体   繁体   中英

Extracting output of aws command and assign it to a variable in bash using jq

Following aws command outputs the below json from which I want to extract the resources which is having the string "vm-managed-itg* values ( last two entries in the output)

$aws resourcegroupstaggingapi get-resources --resource-type-filters cloudwatch:alarm --profile acc | jq '.ResourceTagMappingList[] | select(contains({Tags: [{Key: "vm:cost:accountenv"} ]}) | not) | select(contains({Tags: [{Value: "itg"} ]}) | not)'

{
  "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": []
}

I tried adding jq -r '.[].ResourceARN' but it didn't work and instead threw this error

~$ 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"

Use select to return entities only if they match a condition. Substring matches can be tested with contains :

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

Output:

{
  "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": []
}

If you are only interested in the values of ResourceARN , without tags and surrounding objects, then:

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

jq applies the filter to every single JSON entity in its input (which is a stream of objects).

Output:

"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 for raw output without quotes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM