This project automates the starting and stopping of EC2 instances using AWS Lambda and CloudWatch. We will create two Lambda functions: one to start the instances and another to stop them, triggered by CloudWatch EventBridge on a defined schedule.
- An AWS account with administrative access.
- Basic understanding of IAM, Lambda, and EC2.
-
Navigate to the IAM console in AWS.
-
Go to Policies and click Create policy.
-
Choose the JSON tab and enter the following code:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ec2:StartInstances", "Resource": "arn:aws:ec2:region:account-id:instance/instance-id" } ] }
-
Review and name the policy
EC2StartPolicy
.
-
Follow the same steps as above, but use this JSON:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ec2:StopInstances", "Resource": "arn:aws:ec2:region:account-id:instance/instance-id" } ] }
-
Name this policy
EC2StopPolicy
.
- Go to Roles and click Create role.
- Choose AWS service and select Lambda.
- Attach the
EC2StartPolicy
to the role. Name the roleLambdaEC2StartRole
. - Repeat the process for
EC2StopPolicy
, naming the roleLambdaEC2StopRole
.
-
Navigate to the Lambda console and click Create function.
-
Choose Author from scratch, name the function
StartEC2
. -
Choose Python 3.x as the runtime.
-
Attach the
LambdaEC2StartRole
created earlier. -
In the code editor, replace the existing code with the following:
import boto3 def lambda_handler(event, context): ec2 = boto3.client('ec2') response = ec2.start_instances( InstanceIds=['instance-id'], ) print(f'Started EC2 instances: {response}')
-
Click Deploy.
-
Repeat the steps above, but name the function
StopEC2
. -
Attach the
LambdaEC2StopRole
. -
Replace the code with:
import boto3 def lambda_handler(event, context): ec2 = boto3.client('ec2') response = ec2.stop_instances( InstanceIds=['instance-id'], ) print(f'Stopped EC2 instances: {response}')
-
Click Deploy.
- Navigate to the CloudWatch console and go to Rules under Events.
- Click Create rule.
- Under Event Source, choose EventBridge (CloudWatch Events) and select Schedule.
- Define the schedule using a cron expression, e.g.,
cron(0 8 * * ? *)
for 8 AM UTC every day. - Choose the
StartEC2
Lambda function as the target. - Click Create.
- Repeat the steps above, but use a different cron expression, e.g.,
cron(0 20 * * ? *)
for 8 PM UTC every day. - Choose the
StopEC2
Lambda function as the target. - Click Create.
- Go to the Lambda console and select
StartEC2
. - Click Test and create a new test event. The EC2 instance should start.
- Repeat the process with
StopEC2
to stop the instance.
- Wait for the scheduled time or adjust the cron expression for testing purposes.
- Verify that the EC2 instance starts and stops according to the schedule.
This project demonstrates how to automate EC2 instance management using Lambda and CloudWatch. You can expand on this by adding more instances, custom schedules, or additional AWS services.