1

I've looked through many other stack overflow questions that are similar, but can't find exactly what I'm looking for. This seems simple, but I cannot get the syntax quite right and I'm tired of throwing spaghetti at the wall. Given this return from the AWS CLI:

{
    "IPSet":{
        "Description":"",
        "Name":"testip",
        "IPAddressVersion":"IPV4",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE1111",
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/ipset/testip/a1b2c3d4-5678-90ab-cdef-EXAMPLE1111",
        "Addresses":[
            "192.0.2.0/16"
        ]
    },
    "LockToken":"447e55ac-2396-4c6d-b9f9-86b67c17f8b5"
}

How would use JQ to determine if it contained a certain IP address? This is my closest guess so far, but not quite right.

echo ${single_ip_set} | jq -c '.IPSet.Addresses[] | contains("255.255.255.8")'

single_ip_set is my variable name. This checks every element in the array and gives a response. So does this:

echo ${single_ip_set} | jq -c '.IPSet.Addresses[] | index("255.255.255.8")'

I really just want one final answer as whether or not the array contains one instance. of my requested IP.

Robert Smith
  • 385
  • 4
  • 15
  • Aside: `echo ${single_ip_set}` needs to be `echo "$single_ip_set"` or `echo "${single_ip_set}"`. Otherwise, if you have `"Description": " * "` in your JSON, you'll see filenames appear in your data (not the only way content can be munged, but one of the more dramatic ones). See [I just assigned a variable, but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Oct 28 '21 at 19:56
  • "contains one instance" or "contains an instance". If you want to check if there is exactly one, then you could use `indices`, though that could (under certain circumstances) be inefficient. Otherwise, why not use IN()? – peak Oct 28 '21 at 20:22

1 Answers1

3

If you want to determine if any value in a sequence is true for a predicate, this is a job for any(). If you want to do an exact string comparison, == is the right tool for that job.

jq -c \
  --arg tgt "192.0.2.0/16" \
  '.IPSet.Addresses | any(. == $tgt)' \
  <<<"$single_ip_set"

...is true, whereas:

jq -c \
  --arg tgt "255.255.255.8" \
  '.IPSet.Addresses | any(. == $tgt)' \
  <<<"$single_ip_set"

...is false.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441