【问题标题】:List out auto scaling group names with a specific application tag using boto3使用 boto3 列出具有特定应用程序标签的 Auto Scaling 组名称
【发布时间】:2017-09-22 06:34:11
【问题描述】:

我试图获取应用程序标记值为“CCC”的自动缩放组。

名单如下,

gweb
prd-dcc-eap-w2
gweb
prd-dcc-emc
gweb
prd-dcc-ems
CCC
dev-ccc-wer
CCC
dev-ccc-gbg
CCC
dev-ccc-wer

我在下面编写的脚本给出的输出包括一个没有 CCC 标签的 ASG。

#!/usr/bin/python
import boto3

client = boto3.client('autoscaling',region_name='us-west-2')

response = client.describe_auto_scaling_groups()

ccc_asg = []

all_asg = response['AutoScalingGroups']
for i in range(len(all_asg)):
    all_tags = all_asg[i]['Tags']
    for j in range(len(all_tags)):
        if all_tags[j]['Key'] == 'Name':
                asg_name = all_tags[j]['Value']
        #        print asg_name
        if all_tags[j]['Key'] == 'Application':
                app = all_tags[j]['Value']
        #        print app
        if all_tags[j]['Value'] == 'CCC':
                ccc_asg.append(asg_name)

print ccc_asg

我得到的输出如下,

['prd-dcc-ein-w2', 'dev-ccc-hap', 'dev-ccc-wfd', 'dev-ccc-sdf']

'prd-dcc-ein-w2' 是一个带有不同标签 'gweb' 的 asg。而 CCC ASG 列表中的最后一个(dev-ccc-msp-agt-asg) 也不见了。我需要如下输出,

dev-ccc-hap-sdf
dev-ccc-hap-gfh
dev-ccc-hap-tyu
dev-ccc-mso-hjk

我错过了什么吗?

【问题讨论】:

    标签: python python-2.7 amazon-web-services boto3 autoscaling


    【解决方案1】:

    在 boto3 中,您可以使用Paginators with JMESPath filtering 以更简洁的方式非常有效地执行此操作。

    来自 boto3 文档:

    JMESPath 是一种 JSON 查询语言,可以直接在 分页结果。您可以使用 JMESPath 在客户端过滤结果 通过 PageIterator 的搜索方法。

    当使用 JMESPath 表达式过滤时,每页结果是 分页器产生的结果通过 JMESPath 表达式映射。如果 JMESPath 表达式返回不是数组的单个值, 该值是直接产生的。如果应用 JMESPath 的结果 一页结果的表达式是一个列表,然后列表的每个值 是单独产生的(本质上是实现一个平面地图)。

    下面是它在 Python 代码中的样子,其中提到了 Auto Scaling Group 的 Application 标记的 CCP 值:

    import boto3
    
    client = boto3.client('autoscaling')
    paginator = client.get_paginator('describe_auto_scaling_groups')
    page_iterator = paginator.paginate(
        PaginationConfig={'PageSize': 100}
    )
    
    filtered_asgs = page_iterator.search(
        'AutoScalingGroups[] | [?contains(Tags[?Key==`{}`].Value, `{}`)]'.format(
            'Application', 'CCP')
    )
    
    for asg in filtered_asgs:
        print asg['AutoScalingGroupName']
    

    【讨论】:

    • 非常感谢@Michal,这确实起到了作用。我上面的脚本只列出了应用程序作为第一个标签的 asg 名称。但是您列出了所有带有 CCP 标签的 asg 名称。真的很有帮助:) 一个问题。 !! PaginationConfig={'PageSize': 100} 。这是做什么的?这是我们应该设置的限制吗?问候,阿什法克
    【解决方案2】:

    详细说明 Michal Gasek 的回答,这里有一个选项,它根据标签:值对的字典过滤 ASG。

    def get_asg_name_from_tags(tags):
        asg_name = None
        client = boto3.client('autoscaling')
        while True:
    
            paginator = client.get_paginator('describe_auto_scaling_groups')
            page_iterator = paginator.paginate(
                PaginationConfig={'PageSize': 100}
            )
            filter = 'AutoScalingGroups[]'
            for tag in tags:
                filter = ('{} | [?contains(Tags[?Key==`{}`].Value, `{}`)]'.format(filter, tag, tags[tag]))
            filtered_asgs = page_iterator.search(filter)
            asg = filtered_asgs.next()
            asg_name = asg['AutoScalingGroupName']
            try:
                asgX = filtered_asgs.next()
                asgX_name = asg['AutoScalingGroupName']
                raise AssertionError('multiple ASG\'s found for {} = {},{}'
                         .format(tags, asg_name, asgX_name))
            except StopIteration:
                break
        return asg_name
    

    例如:

    asg_name = get_asg_name_from_tags({'Env':env, 'Application':'app'})
    

    它期望只有一个结果,并通过尝试使用 next() 来获得另一个结果来检查这一点。 StopIteration 是“好”的情况,然后打破分页器循环。

    【讨论】:

    • 上面的代码可以工作,但是对于最新版本的python,你会得到错误'generator' object has no attribute 'next'。要解决错误,请使用asg = next(filtered_asgs) 和asgX = next(filtered_asgs)。
    【解决方案3】:

    我得到了它与下面的脚本一起工作。

    #!/usr/bin/python
    import boto3
    
    client = boto3.client('autoscaling',region_name='us-west-2')
    
    response = client.describe_auto_scaling_groups()
    
    ccp_asg = []
    
    all_asg = response['AutoScalingGroups']
    for i in range(len(all_asg)):
        all_tags = all_asg[i]['Tags']
        app = False
        asg_name = ''
        for j in range(len(all_tags)):
            if 'Application' in all_tags[j]['Key'] and all_tags[j]['Value'] in ('CCP'):
                    app = True
            if app:
                    if 'Name' in all_tags[j]['Key']:
                            asg_name = all_tags[j]['Value']
                            ccp_asg.append(asg_name)
    print ccp_asg
    

    如果您有任何疑问,请随时询问。

    【讨论】:

    • client.describe_auto_scaling_groups() 在单个 API 调用中返回最多 100 个 Auto Scaling 组。如果您有更多的 ASG,您必须使用分页并使用 nextToken 参数再次调用 describe_auto_scaling_groups,否则您将得到不正确的结果。请参阅我处理此问题的答案。
    • 是的!我在下面看到了你的评论。它真的很有帮助。谢谢你:)
    【解决方案4】:

    执行此操作的正确方法根本不是通过describe_auto_scaling_groups,而是通过via describe_tags,这将允许您在服务器端进行过滤。

    您可以构造一个过滤器,要求使用多个值中的任何一个标记应用程序实例:

    Filters=[
            {
                'Name': 'key',
                'Values': [
                    'Application',
                ]
            },
            {
                'Name': 'value',
                'Values': [
                    'CCC',
                ]
            },
        ],
    

    然后您的结果(在响应中的 Tags 中)始终是匹配标签应用于自动缩放组的时间。您将不得不多次拨打电话,每次有一个电话就回传NextToken,以浏览所有结果页面。

    每个结果都包含一个应用了匹配标签的 ASG ID。获得所有您感兴趣的 ASG ID 后,然后您可以致电 describe_auto_scaling_groups 获取他们的姓名。

    【讨论】:

    • 我在尝试您的方法时收到此错误:“botocore.exceptions.ClientError:调用 DescribeTags 操作时发生错误 (ValidationError):过滤器类型 MyCusstomTag 不正确。允许的过滤器类型为:自动-scaling-group 键值在启动时传播”。你真的运行过你的代码吗?
    • 它已经适应了这个问题,但是这种制作过滤器的方式正是我在我的一个应用程序中使用的。你不应该替换key 和value;这些字符串必须是文字。在我给出的示例中,MyCusstomTag 必须替换 Application。
    【解决方案5】:

    另一个解决方案,在我看来很简单,可以扩展:

    client = boto3.client('autoscaling')
    
    search_tags = {"environment": "stage"}
    
    filtered_asgs = []
    
    response = client.describe_auto_scaling_groups()
    
    for group in response['AutoScalingGroups']:
    
        flattened_tags = {
            tag_info['Key']: tag_info['Value']
                for tag_info in group['Tags']
        }
    
        if search_tags.items() <= flattened_tags.items():
            filtered_asgs.append(group)
    
    
    print(filtered_asgs)
    

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2016-01-17
      • 2018-09-30
      • 2017-07-31
      • 2018-07-27
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多