Mallachar Mallachar - 3 months ago 9
JSON Question

Print all matching JSON dictionaries in Python

I am currently using the AWS Boto3 to try to get a list of all of my current running EC2 instances. I am at the point where I am able to use describe_instances to list all of my instances, but I am trying to figure out how to pull out all of the instance ID's so I can print them AND use them for another part of the script. Ultimately, I have one script that spins up all of the instance, next I want one that tears them all down.

JSON Tree bellow.

To select a specifc one, I have to do this,

instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']


But I want to be able to select all instances, regardless of how many instances I have, so trying to do [0][1] etc isn't feasable, so not sure how I would go about saying I want every InstanceId that is in the command.

{
u'Reservations': [
{
u'Groups': [

],
u'Instances': [
{
u'AmiLaunchIndex': 0,
u'Architecture': 'i386',
u'EbsOptimized': False,
u'Hypervisor': 'xen',
u'InstanceId': 'i-6fb4ad61',
}
],
u'OwnerId': '',
u'ReservationId': ''
},
{
u'Groups': [

],
u'Instances': [
{
u'AmiLaunchIndex': 0,
u'Architecture': 'i386',
u'EbsOptimized': False,
u'Hypervisor': 'xen',
u'InstanceId': 'i-afe3faa1',
}
],
u'OwnerId': '',
u'ReservationId': ''
}
],
'ResponseMetadata': {
'HTTPHeaders': {
'content-type': 'text/xml;charset=UTF-8',
'date': 'Thu, 25Aug201623: 44: 09GMT',
'server': 'AmazonEC2',
'transfer-encoding': 'chunked',
'vary': 'Accept-Encoding'
},
'HTTPStatusCode': 200,
'RequestId': ''
}
}


Here is the command I am using to get the instance ID.

launch_instance = ec2.create_instances(ImageId="xxxxxx", MinCount=1, MaxCount=1,SecurityGroupIds=["sg-xxxxxxx"],InstanceType='m3.medium', SubnetId='subnet-xxxxx')


response = ec2client.describe_instances(
InstanceIds=[
launch_instance[0].id],
)

instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']

print instance_id


output is i-6fb4ad61

Answer

Try this

instance_ids = []
for reservations in response['Reservations']:
    for instance in reservations['Instances']:
        instance_ids.append(instance['InstanceId'])