1

I want to save the value for VolumeId, in a variable as a result of the following:

#!/usr/bin/env python
import boto3
import json
import argparse
import logging
import pprint
parser = argparse.ArgumentParser(
    description='get_ec2_inst_state'
)
parser.add_argument("-v", "--verbose", help="increase output verbosity",
    action="store_true")
args = parser.parse_args()
if args.verbose:
    logging.basicConfig(level=logging.DEBUG)
logging.debug('running debug mode')

ec2client = boto3.client('ec2')
instance_id_value = input("Please enter the ec2 instance id : ")
volume = ec2client.describe_instance_attribute(InstanceId= instance_id_value,Attribute='blockDeviceMapping')
#for key in volume:
#    print (key)
#print (volume)
#pprint.pprint(volume, width=1)
for key,value in volume.items():
    print(key,value)
    #for key,value in value.items():
    #    print(key, ":", value)

result: ./get_ec2_inst_vol.py

Please enter the ec2 instance id : i-09f9696ce9150eb1f
BlockDeviceMappings [{'DeviceName': '/dev/sda1', 'Ebs': {'AttachTime': datetime.datetime(2018, 1, 29, 1, 0, 52, tzinfo=tzlocal()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-0b42c57c7ba0281d6'}}]
InstanceId i-09f9696ce9150eb1f
ResponseMetadata {'RequestId': '6c4bbe79-5583-4ee4-8131-1e3bde5e4fa9', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'date': 'Tue, 13 Mar 2018 11:51:45 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}

Now, how can i get VolumeId from the key BlockDeviceMappings . Keeping in mind that volume object is of type dictionary

-------------------- notes ---------------------------- using resource interface VS client, some links:

  1. When to use a boto3 client and when to use a boto3 resource?
  2. http://boto3.readthedocs.io/en/latest/guide/resources.html
  3. http://boto3.readthedocs.io/en/latest/guide/clients.html
kamal
  • 9,637
  • 30
  • 101
  • 168

1 Answers1

1

boto3 has an awesome feature called Service Resource. The Instance type sub-resource has the attribute block_device_mappings. Make use of it:

ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)
for device in instance.block_device_mappings:
    volume = device.get('Ebs')
    print(volume.get('VolumeId'))
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • Thanks, That did the trick. I have to read up more on using resource vs client. I will add some links hoping it would help someone else. – kamal Mar 13 '18 at 12:41