amazon-web-servicesaws-clijmespath

Filtering resources when using resourcegroupstaggingapi CLI


I am trying to find resources in my AWS based on certain tag conditions. I have been using jq to achieve it but is there way of using resourcegroupstaggingapi so they provide a direct way to filter resources where any of the specified tags is missing.

I have 2 use cases and this is how I've been filtering them using jq :

  1. When SV tag exists but DM does not : aws resourcegroupstaggingapi get-resources --tags-per-page 100 | jq '.ResourceTagMappingList | map(select(.Tags[] | select(.Key == "SV") and select(.Key != "DM")))'
  2. When either of CostCenter, Environment or Team tag does not exist : aws resourcegroupstaggingapi get-resources --tags-per-page 100 | jq '.ResourceTagMappingList | map(select(.Tags[] | (.Key | IN("CostCenter", "Environment", "Team",) | not)))'

I tried doing the same without using jq like this :

  1. When SV tag exists but DM does not : aws resourcegroupstaggingapi get-resources --tag-filters "Key=SV,Values=*" "Key=DM,Values=NULL"
  2. When either of CostCenter, Environment or Team tag does not exist : aws resourcegroupstaggingapi get-resources --tag-filters "Key=CostCenter,Values=" "Key=Environment,Values=" "Key=Team,Values="

But with jq I am able to get the output for both however without jq, I just get empty result for both

{
    "ResourceTagMappingList": []
}

What exactly am I doing wrong?


Solution

  • The tag-filters option does not seem to support negation. As a workaround, you can use the --query client side filtering option with the not_null function.

    So for the condition "When SV tag exists but DM does not" you can use:

    $ aws resourcegroupstaggingapi get-resources --tags-per-page 100 --query \
    'ResourceTagMappingList[?not_null(Tags[?Key==`SV`]) && !not_null(Tags[?Key==`DM`])]'
    

    and for the condition "When either of CostCenter, Environment or Team tag does not exist" you can use:

    $ aws resourcegroupstaggingapi get-resources --tags-per-page 100 --query \
    'ResourceTagMappingList[?!not_null(Tags[?Key==`CostCenter`]) || !not_null(Tags[?Key==`Environment`]) || !not_null(Tags[?Key==`Team`])]'