使用 boto3 过滤掉 AutoScalingGroupName 中包含字符串的 ASG

Filter out ASGs that contain string in AutoScalingGroupName using boto3

我正在尝试过滤掉 AutoScalingGroupName 中包含字符串 'base' 的自动缩放组。我正在尝试使用 JMESpath 查询语言,但找不到任何有关按值过滤的示例,仅针对键。

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)

这个returns

None
None

我也试过了

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"

这是正确的语法:

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

如果您更喜欢 "format-syntax" 而不是 f 弦,您当然也可以这样写:

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

如果子串'base'是常量也可以直接写到表达式中:

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

大多数时候您对响应语法的全部内容并不感兴趣。如果只关心组名,可以这样写:

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

如果你更喜欢列表而不是生成器,你可以简单地将周围的括号替换为方括号:

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