【问题标题】:Handling EC2 Description Rate Limiting In Boto3 Lambda?在 Boto3 Lambda 中处理 EC2 描述速率限制?
【发布时间】:2016-09-12 12:52:24
【问题描述】:

我正在创建一个 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 参数。这是实现我想要的结果的最佳方式/我是否走在正确的轨道上?

【问题讨论】:

    标签: amazon-web-services amazon-ec2 aws-lambda boto3


    【解决方案1】:

    只需遍历直到不返回 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2012-11-15
      • 2021-10-23
      • 2019-05-13
      相关资源
      最近更新 更多