返回启动配置列表的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 条记录。似乎没有专门记录 boto2
的函数,但 boto3
中的类似函数 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.)
boto2
的 get_all_launch_configurations()
在名称 max_records
和 next_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'])
希望有帮助:)
顺便说一句,如果您正在编写新脚本,请考虑使用 boto3 编写,因为这是当前推荐的版本。
更新 - boto2 与 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。
关于python - 为什么从 python 脚本和 AWS CLI 收到的启动配置数量存在差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349307/