在 Boto3 Lambda 中处理 EC2 描述速率限制?

Handling EC2 Description Rate Limiting In Boto3 Lambda?

我正在创建一个 Lambda 函数,目的是用它们的快照备份我的 EC2 实例。但是,我注意到阅读 boto 文档时,对 ec2.describe_instances 的调用受到 MaxResults/NextToken 的速率限制。我怎样才能将这两者结合起来,一次安全地遍历 50 个列表?以下是我正在进行的工作:

import boto3
import datetime
import time

ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    try:
        print("Creating snapshots on " + str(datetime.datetime.today()) + ".")
        maxResults = 50
        schedulers = ec2.describe_instances(Filters=[{'Name':'tag:GL-sub-purpose', 'Values':[Schedule]}], MaxResults=maxResults)
        nextToken = schedulers['NextToken']
        totalSchedulers = len(schedulers)
        while totalSchedulers == maxResults:
        schedulers = ec2.describe_instances(Filters=[{'Name':'tag:GL-sub-purpose', 'Values':[Schedule]}], MaxResults=maxResults, NextToken=nextToken)
        nextToken = result['NextToken']
        totalSchedulers = len(schedulers)
        print("Performing backup on " + str(len(schedulers)) + " schedules.")
        successful = []
        failed     = []
        for s in schedulers:
           #[...] More operations here, done 50 at a time.

我不太确定我在这里是否正确或有效地使用了 MaxResults/NextToken 参数。这是实现我期望的最佳方式吗result/am我走在正确的轨道上?

只是遍历直到 NextToken 没有返回。下面是一个示例代码,用于遍历一批实例。更改它以满足您的需要。

import boto3

ec2 = boto3.client('ec2')
insts = ec2.describe_instances(MaxResults=50)
while True:
  #
  # Process Instances (insts)
  #
  if 'NextToken' not in insts: break
  next_token = insts['NextToken']
  insts = ec2.describe_instances(MaxResults=50, NextToken=next_token)