2016-09-11 160 views
-1

我正在創建一個Lambda函數,目的是用他們的快照備份我的EC2實例。然而,我注意到閱讀boto文檔ec2.describe_instances的調用是由MaxResults/NextToken限制的。我怎樣才能將這兩個組合在一起安全地迭代列表50?下面是我的工作進展情況:處理EC2描述限制在Boto3 Lambda?

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正確或有效地在這裏。這是實現我想要的結果的最佳方式嗎?我是否正確?

回答

2

只需迭代直到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)