1. Introduction

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.

2. Project Overview

3. Core Logic Behind the Automation


4. Step-by-Step Setup

Step 1: Start Script (Lambda to Start Instances)

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)

Step 2: Stop Script (Lambda to Stop Instances)

At 5:00 PM, the following script stops the running EC2 instances that are tagged for automation.