Home > Mobile >  jq How to filter array object does not contains Key with case insensitively?
jq How to filter array object does not contains Key with case insensitively?

Time:03-18

I am trying to filter my aws ec2 instances by its Tag Key. I want to get the result that ec2 instance does not have specific Key(in my example, it is env or appname)

aws ec2 describe-instances | jq -c '.Reservations[].Instances[] | select(contains({Tags: [{Key:"env"}]}, {Tags:[{Key:"AppName"}]} | not) | {instanceId: .InstanceId, tags: .Tags}'

which returns However I noticed that I mixed uppercase and lowercase in Key, for example

{
 {
  "InstanceId": "t-1234",
  "Tags": [
         {"Key": "Name",
          "Value": "Foo"},
         {"Key": "env",
          "Value": "prod"}
        ]
 },
{
  "InstanceId": "t-1235",
  "Tags": [
         {"Key": "Name",
          "Value": "Bar"},
         {"Key": "Env",
          "Value": "prod"},
         {"Key": "AppName",
          "Value": "BarApp"}
         ]
 },
{
  "InstanceId": "t-1236",
  "Tags": [
         {"Key": "Name",
          "Value": "Bar"},
         ]
 },
}

With this example, my desired output will be,

{
 {  // this instance does not have AppName
  "InstanceId": "t-1234",
  "Tags": [
         {"Key": "Name",
          "Value": "Foo"},
         {"Key": "env",
          "Value": "prod"}
        ]
 },
{  // this instance does not have AppName and env
  "InstanceId": "t-1236",
   "Tags": [
         {"Key": "Name",
          "Value": "Bar"},
         ]
 },
}

I have been searching and reading that I need to use either ascii_downcase or ascii_uppercase, but keep failing applying. How can I improve my jq statement so that I can filter ec2 instances which do not have specific Key case-insenstiviely(like, env or ENV or Env)?

Thanks

CodePudding user response:

My understanding of the problem description (as opposed to the example) leads me to this jq program:

map(select( any(.Tags[]; .Key | ascii_downcase | IN( "env", "appname")) | not))

Hopefully, the use of any and IN here will guide you to the formulation you want.

  • Related