I don't think there's a "good" way to do this. Ideally I'd recommend just making all your tags lowercase so you don't have this problem.
What you could do is pull ALL the instances from AWS and then check the tags manually in Python:
import json
import boto3
ec2 = boto3.client('ec2', region_name='ap-south-1')
def lambda_handler(event, context):
ec2_instances = ec2.describe_instances()
ec2_reservations = ec2_instances['Reservations']
for reservation in ec2_reservations:
instances = reservation['Instances']
for instance in instances:
if should_stop_instance(instance):
stop_instance(instance)
def should_stop_instance(instance):
should_stop = False
instance_state = instance['State']['Name']
for tag in instance['Tags']:
if tag['key'].lower() == 'tag:testing' and tag['Value'].lower() == 'testinstance' and instance_state == 'running':
should_stop = True
return should_stop
def stop_instance(instance):
instance_id = instance['InstanceId']
ec2.stop_instances(InstanceIds=[instance_id])
print("The instance is stopped:" + instance_id)
Also, you would benefit from posting more legible code in the future. Naming variables a
, b
and c
makes it really difficult for people to understand it. See how my variables are named in a way that makes it simpler to read and logic is split out in to functions which helps legibility.
I've also moved the ec2 = boto3.client('ec2', region_name='ap-south-1')
out of the handler function. You likely just want to initialise this once when the lambda cold starts and not every time from 'warm' starts.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…