Chris
Chris

Reputation: 379

Returning AWS EC2 availability_zone attribute using boto3 Python SDK

I am trying to return information about all of the EC2 instances in an AWS account using boto3 API calls in Python, but I cannot get the availability_zone resource to display.

For instance, when I can iterate over all of my EC2 instances successfully using this code:

ec2 = boto3.resource('ec2')

output = defaultdict()

for instance in ec2.instances.all()
    for iface in instance.network_interfaces:
        output[instance.id] = {
            'Instance ID': instance.id,
            'Subnet ID': iface.subnet_id
        }

I am leaving out the rest of the code, but the above works and outputs the values of those resources which I then put into a csv file using Pandas .to_csv.

When I try to add the following as a value in the Python dictionary:

'Availability Zone': instance.availability_zone

I get the following error:

AttributeError: 'ec2.Instance' object has no attribute 'availability_zone'

That's the expected behavior. I then try the following instead:

'Availability Zone': iface.availability_zone

This runs with error, but the output is null. There simple isn't anything in the csv file.

I looked at the boto3 documentation, and availability_zone is an available resource attribute under the NetworkInterface resource, just like subnet_id, which I am using and is working.

What am I missing here? Can anyone point me in the right direction or let me know what I am doing wrong?

Upvotes: 0

Views: 2248

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269370

Availability Zone is an attribute of the Subnet.

Therefore, you can use:

import boto3

ec2 = boto3.resource('ec2')

output = {}

for instance in ec2.instances.all():
    for iface in instance.network_interfaces:
        output[instance.id] = {
            'Instance ID': instance.id,
            'Subnet ID': iface.subnet_id,
            'AZ': iface.subnet.availability_zone
        }

print(output)

Upvotes: 3

Related Questions