简体   繁体   中英

Filter out ASGs that contain string in AutoScalingGroupName using boto3

I am attempting to filter out auto scaling groups that contain the string 'base' in AutoScalingGroupName. I'm trying to use the JMESpath query language but cannot find any examples on filtering by the value, only for key.

import boto3

session = boto3.Session(profile_name='prod')
asg_client = session.client(
    'autoscaling', 
     region_name='us-west-1'
)

paginator = asg_client.get_paginator('describe_auto_scaling_groups')
page_iterator = paginator.paginate(
    PaginationConfig={'PageSize': 100}
)

filtered_asgs = page_iterator.search(
    'AutoScalingGroups[] | AutoScalingGroupName[?!contains(@, `{}`)]'.format('base')
)

for asg in filtered_asgs:
    pprint.pprint(asg)

This returns

None
None

I've also tried

filtered_asgs = page_iterator.search('AutoScalingGroups[] | [?contains(AutoScalingGroupName[].Value, `{}`)]'.format('base'))
jmespath.exceptions.JMESPathTypeError: In function contains(), invalid type for value: None, expected one of: ['array', 'string'], received: "null"

This is the correct syntax:

substring = 'base'
filtered_args = page_iterator.search(f"AutoScalingGroups[?!contains(AutoScalingGroupName,`{substring}`)][]")

If you prefer the "format-syntax" over f-strings you can of course also write:

filtered_args = page_iterator.search("AutoScalingGroups[?!contains(AutoScalingGroupName,`{}`)][]".format(substring))

And if the substring 'base' is constant you can also write it directly into the expression:

filtered_args = page_iterator.search("AutoScalingGroups[?!contains(AutoScalingGroupName,`base`)][]")

Most of the time you are not interested in the whole content of the response syntax. If you just care about the group name, you can write:

filtered_args = (page['AutoScalingGroupName'] for page in page_iterator.search("AutoScalingGroups[?!contains(AutoScalingGroupName,`base`)][]"))

If you prefer a list as a result over a generator, you can simple replace the surrounding parenthesis with square brackets:

filtered_args = [page['AutoScalingGroupName'] for page in page_iterator.search("AutoScalingGroups[?!contains(AutoScalingGroupName,`base`)][]")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM