JavaQueen
JavaQueen

Reputation: 1205

Error 'EC2' object has no attribute 'instances' in the aws lambda function

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?

Upvotes: 0

Views: 5657

Answers (2)

visit1985
visit1985

Reputation: 497

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()

Upvotes: 2

Leon
Leon

Reputation: 32554

Use the EC2.Client.describe_instances() method:

instances=ec2.describe_instances(Filters=filters)

Upvotes: 6

Related Questions