Iterate thru ec2 describe instance boto3

user2040074 picture user2040074 · Jun 30, 2016 · Viewed 27.6k times · Source

I am trying to get specific values for a describe instance call. So for example, if I want to get the 'Hypervisor' value or the Ebs has 'DeleteOnTermintation' value from the output. Below is the current code I am currently using to make the call and iterate thru the dictionary output.

import boto3
import pprint
from datetime import datetime
import json

client = boto3.client('ec2')

filters = [{  
'Name': 'tag:Name',
'Values': ['*']
}]


class DatetimeEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
    elif isinstance(obj, date):
        return obj.strftime('%Y-%m-%d')
    # Let the base class default method raise the TypeError
    return json.JSONEncoder.default(self, obj)    


output = json.dumps((client.describe_instances(Filters=filters)), cls=DatetimeEncoder)  

pprint.pprint(output)

for v in output:
  print v['Hypervisor']

Getting this error:

TypeError: string indices must be integers, not str

Using the pprint to see all the values available from the output.

Answer

John Rotenstein picture John Rotenstein · Jul 2, 2016

Here's how you could display the information via the AWS Command-Line Interface (CLI):

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Hypervisor, NetworkInterfaces[0].Attachment.DeleteOnTermination]'

Here's some Python:

import boto3

client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
  for i in r['Instances']:
    print i['InstanceId'], i['Hypervisor']
    for b in i['BlockDeviceMappings']:
      print b['Ebs']['DeleteOnTermination']