2

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

0

2 Answers 2

2

Try this

instance_ids = []
for reservations in response['Reservations']:
    for instance in reservations['Instances']:
        instance_ids.append(instance['InstanceId'])
Sign up to request clarification or add additional context in comments.

2 Comments

I get this in ipython 'AttributeError: 'dict' object has no attribute 'append''
@Mallachar sorry, I've made a typo :( I've updated my answer
2

You may achieve is via:

>>> instance_ids = [instance['InstanceId'] for reservations in response['Reservations'] for instance in reservations['Instances']]
>>> instance_ids
['i-6fb4ad61', 'i-afe3faa1']

where your JSON structure is saved as response

3 Comments

I get TypeError: string indices must be integers
Actually, for some reason it prints the same one twice for me In [25]: print instance_ids ['i-6fb4ad61', 'i-6fb4ad61']
Sorry! Yes there was one issue with the code. Fixed it. :)

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.