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

Why there is a difference in the number of launch configurations received from the python script and AWS CLI?

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

为什么偏差这么大?

因为 get_all_launch_configurations 的默认限制是每次调用 50 returned 记录。它似乎没有专门记录 boto2 的功能,但 boto3 的类似功能 describe_launch_configurations 提到:

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

Parameters

MaxRecords (integer) -- The maximum number of items to return with this call. The default value is 50 and the maximum value is 100.

NextToken (string) -- The token for the next set of items to return. (You received this token from a previous call.)

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

首先使用 NextToken="" 进行调用,您将获得前 50 个(或最多 100 个)启动配置。在 returned 数据中查找 NextToken 值并继续重复调用,直到 returned 数据返回时没有 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 与 boto3:

看起来 boto2 没有 return NextToken 在 return 值列表中。使用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。