python - 为什么从 python 脚本和 AWS CLI 收到的启动配置数量存在差异?

标签 python boto aws-cli

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

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.)

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'])

希望有帮助:)

顺便说一句,如果您正在编写新脚本,请考虑使用 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/

相关文章:

amazon-web-services - 当我尝试在我的新 Amazon Linux 实例中执行任何操作时,为什么我的 AWS CLI 挂起?

aws-cli - AWS 代码部署 :bucket option must not contain a forward-slash (/)

python - 在没有 conda 的情况下安装 gdcm

boto - gsutil 在 GCE 中不工作

python - 如何编写时间相关的测试 Python

kubernetes - gcsfuse 在 GKE 和/或 python3 boto 中安装存储桶以进行流式写入?

python - 运行 Boto 函数所需的最低 IAM 策略

python - 如何检查最后一次更新 S3 存储桶的时间?

python - 如何使用 NumPy 沿每一行和每一列应用我自己的函数

python - 如何在Python中传递file、BytesIO、StringIO供以后使用?