In this project, we automate the turning on and off of EC2 instances during working hours, helping reduce unnecessary costs. By utilizing AWS Lambda and EventBridge, we ensure that EC2 instances are only running when they are needed.
Tags for Automation: The instances that need to be started and stopped automatically are tagged when they are created with the following:
AutoStoptrue
Working Hours Logic:
AutoStop=true tag.This script is triggered at 9:00 AM to start the EC2 instances that were stopped outside of working hours.
import boto3
ec2 = boto3.resource('ec2')
instance_id = []
def stop_instance(instance_id):
ec2.instances.filter(InstanceIds=instance_id).start()
# Retrieve stopped instances
def filtered_instances():
instances = ec2.instances.filter(
Filters=[
{
'Name': 'instance-state-name',
'Values': ['stopped']
}
]
)
return instances
def lambda_handler(event, context):
instance_id = []
target_tag_key = 'AutoStop'
target_tag_value = 'true'
instances = filtered_instances()
# Loop through each instance
for instance in instances:
if instance.tags:
for tag in instance.tags:
if tag['Key'] == target_tag_key and tag['Value'] == target_tag_value:
instance_id.append(instance.id)
stop_instance(instance_id)
AutoStop=true tag, and starts those instances.At 5:00 PM, the following script stops the running EC2 instances that are tagged for automation.