Cloudgls Cloudgls - 22 days ago 5
Python Question

AWS Lambda function stops all instances even the filter is configured

By running this code, I want to stop only insances with the tag Class:ClassB.
After testing the function, it shuts down all instances:

import boto3

ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
filters = [{'Name': 'tag:Class', 'Values':['ClassB']},{'Name': 'instance-state-name', 'Values': ['running']}]
instances=ec2.instances.filter(Filters=filters)
for instance in instances:
ec2.instances.stop()
print 'stop your instances: ' + str(instances)


Where the problem is?

Answer

It should be:

instance.stop()

Your code is incorrect:

ec2.instances.stop()