Auto Start & Stop EC2 Instances using Lambda

Rahul K
FAUN — Developer Community 🐾
5 min readSep 26, 2021

--

This blog was originally published at https://fitdevops.in

All the Latest updates and Content will be published there.

Don’t forget to check as I will post content every day…

In this article, I have explained how you can reduce the usage of EC2 instances by stopping and starting them automatically.

Services Involved:

We will be using the following AWS services to implement this setup.

EC2 : A running EC2 Instance , which will be automatically start and stop at regular intervals by lambda function.

IAM : We need a custom IAM policy and execution role for the lambda function.

Cloudwatch Event : A cloudwatch event rule , where we will setup scheduled cron to trigger the function.

Lambda : We will configure the function here and we will provide the details of EC2 instances.

Create an IAM policy and Role

We need to create an IAM policy with the execution role and then we will attach this policy to the lambda function so that it will be able to manage the EC2 instances.

To create the IAM policy, Go to IAM Console,

Choose Policy in the left pane, click Create Policy

You will see the following page, Choose JSON

Remove the default values and copy/paste the below configuration,

{
"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": "*"
}
]
}

Click Review Policy, Give a name for the policy and choose to Create policy.

Now We have to create a Role and attach the policy which we have created.

To create a role, Choose Roles, Click Create Role

Under AWS Services , Choose Lambda

Click Next: Permissions

type the name of the IAM policy we created earlier, Check the policy and Choose Next: Tags

Provide a name for the Role and then click Create Role.

Now , The Role with the required permissions for the lambda function is ready, Lets go ahead and create a lambda function.

Creating Lambda Function

To create a Lambda function , Go to Lambda Console,

Choose Create function, choose Author from Scratch

For Function name, Give a unique name that describes the purpose of this function. eg: autostartstopec2

For Runtime , Choose Python 3.7

Under permissions, expand choose or create execution role

Under execution role , Choose to use an existing role (We should select the role which we have created).

Under the Existing role, choose what you have created.

Choose Create function.

Under the Function Code section, Copy and paste the below code.

Don't forget to change the instance id and the region where you’re running EC2 instances. Here is the code to stop the EC2 Instances based on the Instance ID provided.

import boto3
region = 'ap-southeast-1'
instances = ['i-032db5ef733jdsid8', 'i-03395bs7e87rbsu6522']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)

Set the timeout to 10 sec, But you can give the timeout and Memory as per your requirements.

Choose Save.

We have a lambda function with requirement permission to manage EC2 Instance, Let's test it.

Testing Lambda Functions

To test the lambda function, Choose the function you have created.

Choose Actions and Create a test event by clicking configure test events

Give a name for the event and click Create.

Click Test.

If everything is configured properly, You should see that the instances should be in a stopped state.

Create Cloudwatch Event Rule to Trigger Lambda Function

Go to Cloudwatch Console,

Choose Rules under Events,

Click Create Rule, In the Event source, You can choose either Fixed rate in hours , minutes , days or based on the Scheduled Cron expression.

Under Targets, Choose the function which you have created.

Choose Configure details, Give the name for the rule and Check enabled

Choose Create Rule.

Now Based on the Cloudwatch event rule, The lambda function will be triggered and the EC2 instances will be stopped.

To Auto-start the EC2 Instance:

We have to follow the same steps to start the instance Automatically.

IAM Role

You can use the same IAM role which we have already created.

LAMBDA

You need to create a new lambda function with the same settings, Named: startec2instance.

But we have to make small changes in the function code. use the below code for this function.

import boto3 
region = 'ap-southeast-1'
instances = ['i-032dgdh6fef37a33d8', 'i-03395bd738n5dbf1522']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.start_instances(InstanceIds=instances)
print 'started your instances: ' + str(instances)

Make sure you have configured with the correct region and instance ids.

Cloudwatch Event

We have to create a new Cloudwatch event rule and configure an expression that triggers the Lambda function when to start the instance.

Once everything is configured properly, EC2 instances will be automatically started as per the scheduled expression.

We have successfully automated the process of starting and stopping the instances to reduce the usage of EC2 Instance during Non-production hours.

If you have liked it, Please do check out my other articles.

Originally published at https://fitdevops.in.

Join FAUN: Website 💻|Podcast 🎙️|Twitter 🐦|Facebook 👥|Instagram 📷|Facebook Group 🗣️|Linkedin Group 💬| Slack 📱|Cloud Native News 📰|More.

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇

--

--

Pro-Active Devops Engineer with 5+ years of experience in Linux , Amazon Web Services, Azure , GCP , Devops tools. Blogs here : https://fitdevops.in