Stop EC2 instances by Scheduling with AWS Lambda Function -(Python)

In this article I will show you how to create AWS Lambda using Python to stop EC2 instances in all regions in one go. The purpose of this Lambda function is to reduce a cost of AWS account which is used for development/POC (proof of concept) in organization. The Lambda function will get triggered on scheduled time and stop the running EC2 instances intentionally.

To work this solution smoothly will need to create IAM role with necessary permissions and attached it to the Lambda function.

  • Following are the steps to create IAM role.
  1. Login to the AWS account and look for IAM service.

Main AWS console

2. Select Roles and click on Create Role.

3. Choose Lambda service to call on behalf of you in service section.

Configure service to IAM role

4. Click on next to set permissions. We will create custom policy as don’t want add unnecessary permissions which has no use. Next click on Create Policy, look for EC2 service, then add actions shown in below image. Then click on review policy and save changes.

IAM policy permissions

5. Now search for newly created custom policy to be attached to the role being created. Check the policy and click on next to add tags.

Custom Policy

6. After adding appropriate tags, click on review and give the name to role and click on create role.

IAM role summary
  • Following are the steps to create Lambda function.
  1. Select Lambda under Compute service.

AWS main console

3. Select Create Function.

Lambda Function Dashboard

4. Select “Author from scratch” and enter the appropriate name to the function.

5. Select Python 3.7 as Runtime and for role “Choose an existing role” and select role which is created earlier and create function.

Parameters to create function

6. Add below python code in to function, test it and save it.

import boto3def lambda_handler(event, context):
    client = boto3.client('ec2')
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
        RunningInstances = [instance.id for instance in instances]
        for i in RunningInstances:
            stoppingInstances = ec2.instances.stop(i)
            print(stoppingInstances)NOTE- You may require indentation formatting if you use this code. 

Python Code in Function

7. Scroll down and look for “Basic settings” set “30 sec” in Timeout section and click on save.

  • The last part is to add trigger to the function.
  1. From the function’s console, opt out the CloudWatch Events trigger from left panel.

Select CloudWatch Event

2. Now configure that event, Create a new rule.Give appropriate name to the event and select rule type as a “Schedule expression”.

Configure trigger part-1

3. Enter the specific time and date on which this event will triggered. In our case, this event is scheduled to run everyday at 10PM IST (cron expressions are in UTC). The cron expression will be “cron(30 16 * * ? *)”. Check the Enable trigger. Click on Add and Save the changes.

Configure trigger part-2

You can take a look here to set cron expression values.

4. The Summary of the rule will be like shown in below.

Summary of Rule

5. When Lambda function runs successfully at schedule time logs looks like below.

Successful event logs

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.