Automating EC2 Instance Start/Stop with AWS Lambda

Durkesh blogsDurkesh blogs
3 min read

Prerequisites

Before you begin, make sure you have:

  • An AWS account

  • At least one EC2 instance

  • Basic familiarity with AWS services like Lambda and EC2


Step 1: Tag Your EC2 Instances

To manage EC2 instances automatically, it's helpful to tag them. This makes it easier to filter which ones should be started or stopped.

  1. Go to the EC2 Console

  2. Select your instance

  3. Click on the Tags tab

  4. Add a new tag:

    • Key: AutoSchedule

    • Value: True


Step 2: Create an IAM Role for Lambda

Lambda needs permissions to manage EC2 instances. Let’s create a role for it:

  1. Go to the IAM Console > Roles > Create Role

  2. Choose AWS service > Lambda

  3. Attach the following policies:

    • AmazonEC2FullAccess (for demo purposes; use least privilege in production)
  4. Name the role: LambdaEC2SchedulerRole

  5. Create the role


Step 3: Create the Lambda Function

  1. Go to the Lambda Console

  2. Click Create function

  3. Choose:

    • Author from scratch

    • Function name: EC2StartStopScheduler

    • Runtime: Python 3.9 (or latest)

    • Execution role: Use existing role > Select LambdaEC2SchedulerRole

  4. Add the following Python code:

  5.  import boto3
    
     ec2 = boto3.client('ec2')
     TAG_KEY = 'AutoSchedule'
     TAG_VALUE = 'True'
    
     def lambda_handler(event, context):
         action = event.get('action')
    
         filters = [{
             'Name': f'tag:{TAG_KEY}',
             'Values': [TAG_VALUE]
         }]
    
         instances = ec2.describe_instances(Filters=filters)
         instance_ids = [
             instance['InstanceId']
             for reservation in instances['Reservations']
             for instance in reservation['Instances']
         ]
    
         if not instance_ids:
             print("No instances found with the specified tag.")
             return
    
         if action == 'start':
             ec2.start_instances(InstanceIds=instance_ids)
             print(f"Started instances: {instance_ids}")
         elif action == 'stop':
             ec2.stop_instances(InstanceIds=instance_ids)
             print(f"Stopped instances: {instance_ids}")
         else:
             print("Invalid action. Use 'start' or 'stop'.")
    
  6. Click Deploy


Step 4: Create CloudWatch Event Rules

To trigger the Lambda function on a schedule:

  1. Go to CloudWatch > Rules > Create Rule

  2. Choose Event Source:

    • Select Schedule

    • Use cron expression:

      • Start: cron(0 9 * * ? *) β†’ every day at 9 AM

      • Stop: cron(0 17 * * ? *) β†’ every day at 5 PM

  3. Add a target:

    • Choose Lambda Function

    • Select EC2StartStopScheduler

  4. Configure input:

    • Choose Constant (JSON text)

    • For start rule:

        {
          "action": "start"
        }
      
    • For stop rule:

        {
          "action": "stop"
        }
      
  5. Click Create

Repeat these steps to create both start and stop events.


Step 5: Test the Setup

You can test your Lambda function manually:

  1. Go to the Lambda function

  2. Click Test

  3. Use test JSON:

     {
       "action": "start"
     }
    

Check if your EC2 instance starts. Then try with "action": "stop" to stop it.


Results & Benefits

Once set up, your EC2 instances will automatically:

  • Start at 9 AM

  • Stop at 5 PM

Benefits:

  • πŸ’Έ Save Costs: Instances only run when needed

  • πŸ” Consistent Operations: Reduce human error

  • πŸ“ˆ Scalable: Apply to multiple instances with tags

0
Subscribe to my newsletter

Read articles from Durkesh blogs directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Durkesh blogs
Durkesh blogs