Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate thru ec2 describe instance boto3

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.

like image 226
user2040074 Avatar asked Jun 30 '16 01:06

user2040074


2 Answers

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']
like image 198
John Rotenstein Avatar answered Oct 02 '22 08:10

John Rotenstein


Here's John's answer but updated for Python3

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'])  
like image 27
Ashton Honnecke Avatar answered Oct 02 '22 08:10

Ashton Honnecke