Skip to content

samarthgarde/ec2-automation-lambda

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“˜ Documentation: Automate EC2 Start/Stop with AWS Lambda and EventBridge:

πŸ“Œ Objective:

To automatically start or stop an EC2 instance using AWS Lambda and EventBridge (CloudWatch Events).

πŸ› οΈ Prerequisites:

  • AWS Account
  • One running EC2 instance
  • IAM Role with proper permissions
  • Basic knowledge of AWS Lambda and IAM

🧾 Step-by-Step Setup:

Steps

1.Create IAM Role for Lambda

  • Go to IAM > Roles > Create role

2.Navigate to IAM β†’ Policies β†’ Create policy

Add Permission policy β†’ Use JSON policy enabling EC2 start/stop and log access:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:StartInstances",
        "ec2:StopInstances",
        "ec2:DescribeInstances"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "*"
    }
  ]
}

3.Create lambda function

  • Lambda β†’ Create Function β†’ Author from scratch

  • Runtime: Python 3.x

  • Change Default execution role--use existing

  • Existing role -->select role name

  • Created functionβœ…

  • Use this code

  • πŸ‘‰ view Code

  • Delpoy it βœ…

IMP- Edit the Instance id in that

View lambda function

4.Test

  • Test manually with
{}

5.Configuration

  • timeout
  • 30 sec
  • configured βœ…

6. Configure EventBridge Schedule Rules

Define Shedule Rules

  • Go to EventBridge β†’ Scheduler β†’ Create schedule

  • Choose a cron expression (e.g., cron(0 3 * * ? *) for 3β€―AM UTC)

  • πŸ“˜ Explanation:

3 β†’ minute (03)

11 β†’ hour (11 AM UTC)

31 β†’ day of month (31st)

7 β†’ July

? β†’ ignore day-of-week

2025 β†’ year

Target: select relevant Lambda function

Pass custom payload like

{ "action": "start/stop" }

Created Function Rule - Update Rule βœ…

Stop Eventbridge created

7. Go to the lambda function

  • Go to configuration
  • Add Trigers:
  • EventBridge (CloudWatch Events): ec2-stop-rule
  • EventBridge (CloudWatch Events): ec2-start-rule

Schedules Triggers

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages