0

After testing this code, I get this error:

'EC2' object has no attribute 'instances': AttributeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 11, in lambda_handler
instances=ec2.instances.filter(Filters=filters)
AttributeError: 'EC2' object has no attribute 'instances'

Line 11 is the last line in the code bellow

ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    filters = [{ 'Name': 'instance-state-name', 'Values': ['running']}]
    instances=ec2.instances.filter(Filters=filters)

Where exactly is the error here?

2 Answers 2

6

Use the EC2.Client.describe_instances() method:

instances=ec2.describe_instances(Filters=filters)
Sign up to request clarification or add additional context in comments.

Comments

2

Alternatively to Leon's answer you can use the EC2.ServiceResource class:

ec2 = boto3.resource('ec2', region_name=region)

Because calling ec2.instances.filter() has the benefit of returning a list of resources list(ec2.Instance) (instead of a dict), on which you can call methods like start(), stop(), etc. directly:

filters = [{ 'Name': 'instance-state-name', 'Values': ['running']}]
instances=ec2.instances.filter(Filters=filters)

for instance in instances:
    instance.stop()

Comments

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.