为什么从python脚本和AWS CLI收到的启动配置数量有所不同?

问题描述 投票:1回答:1

返回启动配置列表的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

为什么这么大的偏差?

python boto aws-cli
1个回答
2
投票

因为get_all_launch_configurations每次调用的默认限制为50个返回记录。它似乎没有具体记录boto2的功能,但来自describe_launch_configurations的类似函数boto3提到:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.describe_launch_configurations

参数

MaxRecords(整数) - 此调用返回的最大项目数。默认值为50,最大值为100。

NextToken(string) - 要返回的下一组项的标记。 (您之前的通话中收到了此令牌。)

boto2get_all_launch_configurations()支持相同的参数,名称为max_recordsnext_token,请参阅here

首先与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'])

希望有帮助:)

BTW如果您正在编写新脚本,请考虑将其写入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。

© www.soinside.com 2019 - 2024. All rights reserved.