Schedule your aws ec2 instance start stop activity using Lambda Function
Hi Guys,
here am going to explain how to create the lambda function to start and stop your ec2 instances in the scheduled time interval.
1.Create IAM Policy
First we are going to create the policy in AWS IAM service.
select the JSON tab and paste the below content.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
give the policy name and create it.
2.Create Lambda Function
Just select create function
author from scracth
In the function name button give your start_instance
In run time select python 3.6
Leave the default option in Change default execution role
now you can see the below screen.
double click the lambda functions.py and clear all content on it. paste the below content.
import boto3
region = 'ap-south-1'
instances = ['i-0a627784fd87373be']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
in the region section mention your ec2 instance region.
in the instance section mention your target instance id's.
after the changes just click deploy. its save your code.
now we want to configure the test event.
using the default hello world template and give the test event name and create it.
now we are going to edit the role that attached in the function. in the configuration section select the execution role.
in the role section just select attach policies.
add the iam policy in to it which we are create in first step.
and attach it.
thats it now we are going to execute our function to start the ec2 server.
output
your function is successfully executed your instance started.
Do the same steps for stop your instance.
cretae the function called stop.
do all the same steps for start function.just change the below code in functions.py.
import boto3
region = 'ap-south-1'
instances = ['i-0a3698100d7fb47c9']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stooped your instances: ' + str(instances))
now we have the two functions to start and stop the ec2 instances.so we going to automate the start and stop actions in the scheduled time.
3.Create cloud watch rules to schedule the fucntion
Open AWS Cloudwatch service and create the rule.
in the event pattern select schulde and select cron expression
then add target aws service.
in the dropdown menu select lambda function.
select which function want to execute it.
In this event we are configure the ec2 instance willbe stopped daily 11:15 pmGMT.
we want to do the same rule for start event.