Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用boto3列出具有特定应用程序标记的自动缩放组名称_Python_Python 2.7_Amazon Web Services_Boto3_Autoscaling - Fatal编程技术网

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

Python 使用boto3列出具有特定应用程序标记的自动缩放组名称,python,python-2.7,amazon-web-services,boto3,autoscaling,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 ['prd-dcc-ein-w2', 'dev-ccc-hap', 'dev-ccc-wfd', 'dev-ccc-sdf'] dev-ccc-hap-sdf dev-ccc-hap-gfh dev-ccc-hap-tyu dev

我试图获取应用程序标记值为“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
['prd-dcc-ein-w2', 'dev-ccc-hap', 'dev-ccc-wfd', 'dev-ccc-sdf']
dev-ccc-hap-sdf
dev-ccc-hap-gfh
dev-ccc-hap-tyu
dev-ccc-mso-hjk
我在下面编码的脚本给出的输出包括一个没有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
我得到的结果如下:

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
['prd-dcc-ein-w2', 'dev-ccc-hap', 'dev-ccc-wfd', 'dev-ccc-sdf']
dev-ccc-hap-sdf
dev-ccc-hap-gfh
dev-ccc-hap-tyu
dev-ccc-mso-hjk
其中as
'prd-dcc-ein-w2'
是具有不同标签的asg
'gweb'
。ccc asg列表中的最后一个
(dev ccc msp agt asg)
丢失。我需要如下输出:

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
['prd-dcc-ein-w2', 'dev-ccc-hap', 'dev-ccc-wfd', 'dev-ccc-sdf']
dev-ccc-hap-sdf
dev-ccc-hap-gfh
dev-ccc-hap-tyu
dev-ccc-mso-hjk

我遗漏了什么吗?

我在下面的脚本中找到了它

#!/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
如果您有任何疑问,请随时询问。

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

从boto3文档:

JMESPath是一种JSON查询语言,可直接用于 分页结果。您可以使用JMESPath在客户端筛选结果 通过应用于每个结果页的表达式 页面迭代器的搜索方法

使用JMESPath表达式进行筛选时,将显示 通过JMESPath表达式映射paginator生成的。如果 JMESPath表达式返回一个不是数组的值, 这种价值是直接产生的。如果应用JMESPath的结果 表达式到一页的结果是一个列表,然后是列表的每个值 单独生成(基本上实现平面图)

下面是在Python代码中,对于自动缩放组的
Application
标记,它的值为
CCP
时的样子:

导入boto3
client=bot3.client('autoscaling')
paginator=client.get\u paginator('description\u auto\u scaling\u groups')
page_iterator=paginator.paginate(
PaginationConfig={'PageSize':100}
)
过滤的\u asgs=页面\u迭代器.search(
'AutoScalingGroups[]|[?包含(标记[?键==`{}`].Value,`{}`])].format(
“应用程序”、“CCP”)
)
对于过滤后的asg中的asg\u asg:
打印asg['AutoScalingGroupName']

在详细阐述Michal Gasek的答案时,这里有一个选项可以根据标记:值对的dict过滤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
例如:


它希望只有一个结果,并通过尝试使用next()获取另一个结果来检查这一点。StopIteration是一个“好”的例子,它会打破paginator循环。

正确的方法不是通过
description\u auto\u scaling\u groups
,而是允许您在服务器端进行过滤

您可以构造一个筛选器,该筛选器要求标记应用程序实例具有以下任意值:

Filters=[
        {
            'Name': 'key',
            'Values': [
                'Application',
            ]
        },
        {
            'Name': 'value',
            'Values': [
                'CCC',
            ]
        },
    ],
然后,当匹配的标记应用于自动缩放组时,您的结果(在响应中的
标记中
)。您必须多次拨打电话,每次有电话时都要传回
NextToken
,才能查看所有页面的结果


每个结果都包含一个应用匹配标记的ASG ID。拥有所有感兴趣的ASG ID后,可以调用
descripe\u auto\u scaling\u groups
获取它们的名称。

client.descripe\u auto\u scaling\u groups()
在单个API调用中最多返回100个自动缩放组。如果您有更多ASG,则必须使用分页并使用
nextToken
参数再次调用
description\u auto\u scaling\u groups
,否则您将得到不正确的结果。看到我的答案了吗?是的!我在下面看到了你的评论。这真的很有帮助。谢谢:)非常感谢@Michal,这真的很有效。我上面的脚本只列出了以应用程序作为第一个标记的asg名称。但是你的名字已经用CCP标签列出了所有asg的名字。真的很有帮助:)一个问题<代码>分页配置={'PageSize':100}
。这有什么用?这是我们应该设定的限制吗?。关于这一点,上面的代码可以工作,但是对于python的最新版本,您将得到错误
“generator”对象没有属性“next”
。要解决此错误,请使用
asg=next(filtered\u asgs)
asgX=next(filtered\u asgs)
。我在尝试您的方法时遇到此错误:“botocore.exceptions.ClientError:发生错误(ValidationError)调用DescribeTags操作时:筛选器类型MyCusstomTag不正确。允许的筛选器类型为:自动缩放组键值在启动时传播”。你真的运行了你的代码吗?它已经适应了这个问题,但是这种制作过滤器的方法正是我在我的一个应用程序中使用的。您不应该替换
;这些字符串必须是文本<在我给出的示例中,code>mycustomtag
必须替换
Application