问题描述
返回启动配置列表的python脚本如下(对于us-east-1区域):
autoscaling_connection = boto.ec2.autoscale.connect_to_region(region)
nlist = autoscaling_connection.get_all_launch_configurations()
由于某些原因,nlist的长度为50,即我们发现只有50个启动配置。 AWS CLI中的相同查询会产生174个结果:
aws autoscaling describe-launch-configurations --region us-east-1 | grep LaunchConfigurationName | wc
为什么会有这么大的偏差?
1楼
因为get_all_launch_configurations
的默认限制是每个调用返回50条记录。
它似乎并没有被明确记载为boto2
的功能,但有类似的功能describe_launch_configurations
从boto3
提到:
参数
MaxRecords (整数)-通过此调用返回的最大项目数。 默认值为50,最大值为100。
NextToken (string)-下一组要返回的项目的令牌。 (您从上一个呼叫中收到了此令牌。)
boto2
的get_all_launch_configurations()
在名称max_records
和next_token
下支持相同的参数,请参见 。
首先使用NextToken=""
进行呼叫,您将获得前50个(或最多100个)启动配置。
在返回的数据中查找NextToken
值,并继续重复调用,直到返回的数据没有NextToken
为止。
像这样:
data = conn.get_all_launch_configurations()
process_lc(data['LaunchConfigurations'])
while 'NextToken' in data:
data = conn.get_all_launch_configurations(next_token=data['NextToken'])
process_lc(data['LaunchConfigurations'])
希望有帮助:)
顺便说一句,如果您要编写新脚本,请考虑在boto3中编写它,因为这是当前和推荐的版本。
更新-boto2 vs boto3:
看起来boto2不在返回值列表中返回NextToken
。
使用boto3 ,更好,更合逻辑,真的:)
这是一个有效的实际脚本:
#!/usr/bin/env python3
import boto3
def process_lcs(launch_configs):
for lc in launch_configs:
print(lc['LaunchConfigurationARN'])
client = boto3.client('autoscaling')
response = client.describe_launch_configurations(MaxRecords=1)
process_lcs(response['LaunchConfigurations'])
while 'NextToken' in response:
response = client.describe_launch_configurations(MaxRecords=1, NextToken=response['NextToken'])
process_lcs(response['LaunchConfigurations'])
我故意设置MaxRecords=1
进行测试,在实际脚本中将其提高到50或100。