2016-09-12 1 views
1

私のラムダスクリプトは、私のEC2インスタンスの一部をバックアップする作業です。私は代入の直後にinstanceIdの値を表示し、驚いたことにインスタンスIDではなく文字列 'Instances'を返しました。私はここで応答の期待されるフォーマットを確認しました:http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instancesと私は正しく呼び出していると思います。私はまずリストからインスタンス項目だけを取得し(schedule_instances = schedulers ['Instances'])、その新しいリストからインスタンスIDを取得しようとします。これは正しいです? VolumeIdの取得についても同様の疑問があります。AWSラムダスクリプトがインスタンスIDの代わりに「インスタンス」を返すのはなぜですか?

from __future__ import print_function 
import json 
import boto3 
import datetime 
import time 

ec2 = boto3.client('ec2') 

def lambda_handler(event, context): 
    try: 
     print("Creating snapshots on " + str(datetime.datetime.today()) + ".") 
     schedulers = ec2.describe_instances(MaxResults=50, Filters=[{'Name':'tag:GL-sub-purpose', 'Values':['Schedule']}]) 
     print("Performing backup on " + str(len(schedulers)) + " schedules.") 
     successful = [] 
     failed  = [] 
     schedule_instances = schedulers['Instances'] 
     for s in schedulers: 
      try: 
       instanceId=s['InstanceId'] 
       print (instanceId) 
       snapshotDescription = instanceId + "-" + str(datetime.date.today().strftime('%Y-%m-%d')) + "-46130e7ac954-automated" 
       ec2.create_snapshot(
       VolumeId=s['VolumeId'], 
       Description=snapshotDescription 
       ) 
       successful.append(instanceId) 
      except Exception as e: 
       print(e) 
       failed.append(instanceId + " :\t" + str(e)) 
     print("Performed backup on " + str(len(successful)) + " schedulers. Failed backup on " + str(len(failed)) + " schedulers. ") 
     sendEmail(successful, failed) 
     return "Success" 
    except Exception as e: 
     print(e) 
     return "Failed" 
+0

フィルタに一致するすべてのインスタンスのインスタンスIDを取得しますか?この情報を取得する方法はずっと簡単です。 – helloV

+0

私の目標は、指定したタグを使ってリスト内のすべてのインスタンスを繰り返し、スナップショットを作成することです。したがって、ループが実行されるたびにその特定の項目でインスタンスIDが必要になります。 –

答えて

1

forループのセクションがJson Keyの値を通過していないように見えます。

あなたは、これがアウトに役立ちますあなたのコード内で同じループ(複数のインスタンスが必要な場合は、使用のループ)のための

希望を実装することができます

import boto3 

ec2 = boto3.client('ec2') 

schedulers = ec2.describe_instances(InstanceIds=['i-xxxxxxxx']) 

for i in schedulers['Reservations']: 
    print i['Instances'][0]['InstanceId'] 

Boto3

を使用してインスタンス-のIdsを取得するための次のコードを使用します。

+0

ああ、これは正しい方向に私を置く。予約辞書を解析してから、結果の予約リストを最初に解析しなければなりませんでした。助けてくれてありがとう! –

関連する問題