Created
March 8, 2024 13:19
-
-
Save huevos-y-bacon/d552bc925d5e1e9b245aff0a1d0e0f79 to your computer and use it in GitHub Desktop.
AWS EC2 and RDS - Stop all running EC2 and (optionally) RDS Instances
This file contains 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
#!/usr/bin/env python3 | |
import boto3 | |
ec2 = boto3.resource('ec2') | |
rds = boto3.client('rds') | |
include_rds = False | |
def lambda_handler(event, context): | |
# Stop EC2 instances | |
running_instances = ec2.instances.filter( | |
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) | |
for instance in running_instances: | |
# get instance Name tag | |
instance_name = '' | |
for tag in instance.tags: | |
if tag['Key'] == 'Name': | |
instance_name = tag['Value'] | |
break | |
print('Stopping EC2 instance:', instance.id, ' Name:', instance_name) | |
try: | |
instance.stop() | |
except Exception as e: | |
print('Error stopping instance:', instance.id, ' Error:', e) | |
# Stop RDS instances if include_rds is True | |
if include_rds: | |
rds_instances = rds.describe_db_instances() | |
for instance in rds_instances['DBInstances']: | |
# Get instance Name tag | |
instance_name = '' | |
for tag in instance['TagList']: | |
if tag['Key'] == 'Name': | |
instance_name = tag['Value'] | |
break | |
print('RDS instance:', instance['DBInstanceIdentifier'], ', Name:', instance_name, ', Status:', instance['DBInstanceStatus']) | |
if instance['DBInstanceStatus'] == 'available': | |
print('Stopping RDS instance:', instance['DBInstanceIdentifier']) | |
try: | |
rds.stop_db_instance(DBInstanceIdentifier=instance['DBInstanceIdentifier']) | |
except Exception as e: | |
print('Error stopping RDS instance:', instance['DBInstanceIdentifier'], ' Error:', e) | |
if include_rds: | |
print('All running EC2 and RDS instances are stopped') | |
return 'All running EC2 and RDS instances are stopped' | |
else: | |
print('All running EC2 instances are stopped') | |
return 'All running EC2 instances are stopped' | |
if __name__ == '__main__': | |
# include_rds = True | |
lambda_handler(None, None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment