1

Below is my Lambda script which is a work in progress to back up some of my EC2 instances. I printed out the value of instanceId immediately after assignment and, to my surprise, it returned the string 'Instances' rather than an instance ID. I checked the expected format of the response here: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances and I believe I'm doing the call correctly. I first get just the Instances item from the list (schedule_instances = schedulers['Instances']) and then try to get the instance ID from that new list. Is this correct? I also have similar doubts about getting the VolumeId.

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"
2
  • Do you want to get the instance id of all instances that match the filter? There is a much simpler way to get this info. Commented Sep 12, 2016 at 16:55
  • My goal is to iterate through every instance in the list with the tag I've specified and create a snapshot for it. So I'll need the instance ID at that particular item each time the loop runs. Commented Sep 12, 2016 at 17:06

1 Answer 1

1

Looks like your for loop section isn't going through the Json Key values.

Use the following code for retrieving Instance-Ids using Boto3

import boto3

ec2 = boto3.client('ec2')

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

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

You can implement the for loop same in your code (If multiple instances are required use looping)

Hope this helps out.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, this put me in the right direction. Had to parse the Reservation dictionary and then the resulting list of reservations first. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.