Prepare a filter based on your tags requirement and run the query, eventually iterate through the resource.
import boto3
# Connect to EC2
ec2 = boto3.client('ec2', region_name='us-east-1')
def lambda_handler(event,context):
custom_filter = [{
'Name':'tag:Name',
'Values': ['TestServer']}]
instances_to_stop = []
running_instances = ec2.describe_instances(Filters=custom_filter)
for reservation in running_instances.get('Reservations'):
for instance in reservation.get('Instances'):
instances_to_stop.append(instance.get('InstanceId'))
print(f'Stopping following instance Ids : {instances_to_stop}')
response = ec2.stop_instances(InstanceIds=instances_to_stop)
print(response)
Response:
{
"StoppingInstances": [
{
"CurrentState": {
"Code": 64,
"Name": "stopping"
},
"InstanceId": "i-011ac4a33afdsadasd",
"PreviousState": {
"Code": 16,
"Name": "running"
}
}
],
"ResponseMetadata": {
"RequestId": "35a3ab",
"date": "Thu, 04 Feb 2021 16:35:38 GMT",
"server": "AmazonEC2"
},
"RetryAttempts": 0
}
}