Last active
February 17, 2023 06:53
-
-
Save aalokt89/fd2453f58dd152438b213b301711137a to your computer and use it in GitHub Desktop.
stops AWS EC2 instances by tag key/value and state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import json | |
ec2 = boto3.resource('ec2', region_name='us-east-1') | |
def lambda_handler(event, context): | |
filteredInstances = [] | |
successMessage = f"Successfully stopped {len(filteredInstances)} instances." | |
errorMessage = "Error: There are no running instances with the selected filters." | |
ec2Filters = [ | |
{ | |
'Name': 'tag:Environment', | |
'Values': ['Dev'] | |
}, | |
{ | |
'Name': 'instance-state-name', | |
'Values': ['running'] | |
}] | |
# get instances by tag and 'running' state | |
instances = ec2.instances.filter(Filters=ec2Filters) | |
# get filtered instance ids and add them to filteredInstances list | |
for instance in instances: | |
filteredInstances.append(instance.id) | |
if len(filteredInstances) > 0: | |
ec2.instances.filter(InstanceIds=filteredInstances).stop() | |
print(successMessage) | |
return { | |
"statusCode": 200, | |
"body": json.dumps(successMessage) | |
} | |
else: | |
print(errorMessage) | |
return { | |
"statusCode": 100, | |
"body": json.dumps(errorMessage) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment