Search code examples
jsonamazon-web-servicesjqaws-cliaws-resource-group

Using jq to filter AWS resources based on their tags


Using the command aws resourcegroupstaggingapi get-resources --profile (profile_name) returns an array of JSON object with the Resource ARNs value and their tags (another array of JSON of objects with tag's key and value.

Here's a anonymized example:

{
  "ResourceTagMappingList": [
    {
      "ResourceARN": "arn:aws:acm:eu-west-1:123456789000:certificate/XXXXX-YYYY-8888-9999-CCCCCCCCCCCCC",
      "Tags": [
        {
          "Key": "Environment",
          "Value": "BAR"
        }
      ]
    },
    {
      "ResourceARN": "arn:aws:acm:eu-west-1:123456789000:certificate/XXXXX-YYYY-8888-9999-CCCCCCCCCCCCC",
      "Tags": [
        {
          "Key": "Environment",
          "Value": "FOO"
        }
      ]
    },
    {
      "ResourceARN": "arn:aws:ec2:eu-west-1:123456789000:elastic-ip/eipalloc-112345440809463",
      "Tags": [
        {
          "Key": "Component",
          "Value": "somethingCool"
        },
        {
          "Key": "DeployID",
          "Value": "di-01"
        },
        {
          "Key": "Name",
          "Value": "eip-nat-somethingCool-di-01"
        }
      ]
    },
    {
      "ResourceARN": "arn:aws:ec2:eu-west-1:123456789000:elastic-ip/eipalloc-19853410278439394i3",
      "Tags": [
        {
          "Key": "Component",
          "Value": "somethingCool"
        },
        {
          "Key": "DeployID",
          "Value": "bla-internal-goku"
        },
        {
          "Key": "Name",
          "Value": "eip-nat-somethingCool-bla-internal-goku"
        }
      ]
    },
    {
      "ResourceARN": "arn:aws:elasticloadbalancing:eu-west-1:123456789000:targetgroup/tf-20190624192221842800000004/oisajhiuweniçqej82u23948u3",
      "Tags": [
        {
          "Key": "Component",
          "Value": "somethingCool"
        },
        {
          "Key": "DeployID",
          "Value": "env01-bla00"
        },
        {
          "Key": "Environment",
          "Value": "env01"
        },
        {
          "Key": "Estate",
          "Value": "something"
        },
        {
          "Key": "Name",
          "Value": "target-group-lala-somethingCool-env01-bla00-vsquad"
        }
      ]
    }
  ]
}

So I would like to know if I can use the cli tool jq to filter the objects based on a specific tag Value? And if it is possible to list out all Value of a specific Tag Key?


Solution

  • Filter objects based on a specific tag value:

    aws resourcegroupstaggingapi get-resources --region REGIONCODE \
        | jq '.ResourceTagMappingList[] | select(.Tags[0].Value == "VALUETYPE")'
    

    List all values of a specific tag key:

    aws resourcegroupstaggingapi get-tag-values --key KEYNAME