0

I'm trying to list the EC2 instances in a specific AWS account using named profiles and boto3 in Python.

The error says:

File ".\aws_ec2_list_instance_info.py", line 18, in <module>
    running_instances = ec2.instances.filter(Filters=[{
  File "C:\Users\tdunphy\AppData\Local\Programs\Python\Python37-32\lib\site-packages\botocore\client.py", line 601, in __getattr__
    self.__class__.__name__, item)
AttributeError: 'EC2' object has no attribute 'instances'

This is my code:

from collections import defaultdict
import boto3
aws_account = input("Enter the name of the AWS account you'll be working in: ")
# Connect to EC2
session = boto3.Session(profile_name=aws_account)
ec2 = session.client('ec2')
# Get information for all running instances
running_instances = ec2.instances.filter(Filters=[{
    'Name': 'instance-state-name',
    'Values': ['running']}])

What am I doing wrong?

2
  • Can you edit your question to include which version of Boto 3 you are using. The current Boto 3 (ver. 1.9.108) documentation does not list instances as a method of EC2.Client. Mar 6, 2019 at 18:08
  • Ok. How do I determine the version of boto3 that I'm using?
    – bluethundr
    Mar 6, 2019 at 18:52

2 Answers 2

0

There doesn't seem to be an instance function for ec2 client. Maybe something like this is what you're looking for?

describe_instances, https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances

5
  • Ok, I can probably alter the code to use describe_instannces. But I notice if I switch to boto3.resource the code I have works, without switching accounts:ec2 = boto3.resource('ec2') running_instances = ec2.instances.filter(Filters=[{ 'Name': 'instance-state-name', 'Values': ['running']}]) returns ------ Name: USAWSCDLX00061 Instance ID: i-0463897140af217f8 Type: m4.large State: running Private IP: 10.48.136.41 Public IP: None Launch Time: 2017-12-20 14:26:30+00:00
    – bluethundr
    Mar 6, 2019 at 18:47
  • I have two questions. What's the difference between boto3.resource and boto3.client? Is there any way to do account switching using boto3.resource?
    – bluethundr
    Mar 6, 2019 at 18:47
  • I'm going to point to you this post that explains it pretty well, stackoverflow.com/a/48867829/11149832
    – noobius
    Mar 6, 2019 at 18:51
  • OK perfect! Thanks I will check this out.
    – bluethundr
    Mar 6, 2019 at 18:52
  • Update. This works when I switch it to a boto3 resource instead of a client. And I am able to switch accounts: session = boto3.Session(profile_name=aws_account) ec2 = session.resource('ec2')
    – bluethundr
    Mar 6, 2019 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.