使用boto3列出具有特定应用程序标签的自动缩放组名称

时间:2017-04-25 09:56:11

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

我试图获取自动缩放组,其应用标记值为' 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

我错过了什么吗?。

5 个答案:

答案 0 :(得分:9)

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

来自boto3 docs:

  

JMESPath是JSON的查询语言,可以直接使用   分页结果。您可以使用JMESPath过滤客户端的结果   通过表达式应用于每个结果页面的表达式   PageIterator的搜索方法。

     

使用JMESPath表达式进行过滤时,每个结果页面都是   由paginator产生的是通过JMESPath表达式映射的。如果   JMESPath表达式返回不是数组的单个值,   该值直接产生。如果应用JMESPath的结果   表达式到结果页面是一个列表,然后是列表的每个值   是单独产生的(基本上是实施平面地图)。

以下是使用Auto Scaling Group的CCP标记提到的Application值的Python代码中的样子:

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']

答案 1 :(得分: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是“好”的情况,然后突破了paginator循环。

答案 2 :(得分:1)

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

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)

答案 3 :(得分:0)

我使用下面的脚本。

#!/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

随意询问您是否有任何疑问。

答案 4 :(得分:0)

执行此操作的正确方法完全不是通过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以获得其名称。