Home > Software design >  Extracting output of aws command and assign it to a variable in bash using jq
Extracting output of aws command and assign it to a variable in bash using jq

Time:11-15

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"

Any help is appreciated.

CodePudding user response:

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).

  • Related