Home > other >  JQ How to select multiple vlaues when key matches
JQ How to select multiple vlaues when key matches

Time:08-05

Looking somebody who can help me with the following jq manipulation. I have the following json:

{
  "description": "James-only access",
  "groupName": "Route-SGP",
  "ipPermissions": [
    {
      "ipProtocol": "tcp",
      "toPort": 22,
      "ipRanges": [
        "10.32.0.1/32",
        "10.32.0.2/32"
      ]
    }
  ],
  "ownerId": "2222",
  "groupId": "sg-2222",
  "vpcId": "vpc-2222"
}
{
  "groupName": "sg1",
  "ipPermissions": [
    {
      "ipProtocol": "tcp",
      "toPort": 4439,
      "ipRanges": [
        "10.32.0.2/32"
      ]
    },
    {
      "ipProtocol": "tcp",
      "toPort": 3389,
      "ipRanges": [
        "10.32.0.1/32",
        "10.32.0.2/32"
      ]
    },
    {
      "ipProtocol": "icmp",
      "toPort": -1,
      "ipRanges": [
        "10.32.0.0/30"
      ]
    }
  ],
  "ownerId": "1111",
  "groupId": "sg-1111",
  "vpcId": "vpc-1111"
}

I need get the following keys when ipRanges contains "10.32.0.2/32", like that:

ownerId, groupId, groupName, ipProtocol, toPort

"2222","sg-2222","Route-SGP","tcp","22"
"1111","sg-1111","sg1","tcp","4439"
"1111","sg-1111","sg1","tcp","3389"

I tried do something like below but it wont work.

jq 'select(.ipPermissions[]?.ipRanges[] | contains("10.32.0.2/32"))' | jq 'del(.[] | first(select(recurse | objects | has("ipRanges") and (.ipRanges | index("10.32.0.2/32" | not)))))'

CodePudding user response:

Iterate using a variable, and use select to filter

jq -r --arg ip "10.32.0.2/32" '
  .ipPermissions[] as $p | select(IN($p.ipRanges[]; $ip))
  | [.ownerId, .groupId, .groupName, $p.ipProtocol, $p.toPort]
  | @csv
'
"2222","sg-2222","Route-SGP","tcp",22
"1111","sg-1111","sg1","tcp",4439
"1111","sg-1111","sg1","tcp",3389

Demo

CodePudding user response:

I think i figured out:

jq 'select(.ipPermissions[]?.ipRanges[] | index("10.32.0.2/32"))' | jq 'del(.ipPermissionsEgress) | . as $i| "\(.ownerId),\(.groupId),\($i.ipPermissions[] | select(.ipRanges | index("10.32.0.2/32")) | "\(.toPort),\(.ipProtocol)")"'
  • Related