Matthew Perrott
Matthew Perrott

Reputation: 309

jq - Filtering instances for not contain is not working

I am trying to filter instances within my AWS environment that are currently running. I am using jq to filter the instances:

INSTANCE_METADATA=$(aws ec2 --profile $ACCOUNT describe-instances | jq --arg env $ENVIRONMENT '.Reservations|map(select((.Instances[0].Tags[].Value==$env) and (.Instances[0].State.Name=="running") ))')

I am then creating a variable for the InstanceIDs:

RUNNING_INSTANCE_IDS=$(jq -r '.[].Instances[0].InstanceId' <<<"${BEANSTALK_INSTANCE_METADATA}")

This works perfectly fine.

However, there is one instance within the environment that I do not want to include in this list, so I have tried to include another filter within the original jq. I have tried it 2 different ways:

$(aws ec2 --profile $ACCOUNT describe-instances | jq --arg env $ENVIRONMENT '.Reservations|map(select((.Instances[0].Tags[].Value==$env) and (.Instances[0].State.Name=="running") and (.Instances[0].Tags[].Value|contains("NFTPerformanceTest")|not)) ))')

and

$(aws ec2 --profile $ACCOUNT describe-instances | jq --arg env $ENVIRONMENT '.Reservations|map(select((.Instances[0].Tags[].Value==$env) and (.Instances[0].State.Name=="running") and (.Instances[0].Tags[].Value!="NFTPerformanceTest") ))')

Neither of these successfully filter out the Instance in question. What am I missing here?

Upvotes: 0

Views: 147

Answers (1)

peak
peak

Reputation: 116919

Each time you write .Tags[], you are iterating over .Tags, so the way you've written the selection criterion cannot achieve the desired effect.

One way to reformulate your query would be to use any/2 and/or all/2 as appropriate. Presumably, for example, the criterion you want based on .Value would be (equivalent to):

all(.Instances[0].Tags[].Value; 
    contains("NFTPerformanceTest")|not)

Example

For efficiency, it would make sense to re-order the selection criteria, so you might end up with something like:

.Reservations
| map(select(.Instances[0]
             | ( .State.Name=="running" and
                 any(.Tags[]; .Value==$env) and
                 all(.Instances[0].Tags[].Value;
                     contains("NFTPerformanceTest")|not) )))

Upvotes: 2

Related Questions