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.
- Login to the AWS account and look for IAM service.
2. Select Roles and click on Create Role.
3. Choose Lambda service to call on behalf of you in service section.
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.
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.
6. After adding appropriate tags, click on review and give the name to role and click on create role.
- Following are the steps to create Lambda function.
- Select Lambda under Compute service.
3. Select Create Function.
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.
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.
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.
- From the function’s console, opt out the CloudWatch Events trigger from left panel.
2. Now configure that event, Create a new rule.Give appropriate name to the event and select rule type as a “Schedule expression”.
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.
You can take a look here to set cron expression values.
4. The Summary of the rule will be like shown in below.
5. When Lambda function runs successfully at schedule time logs looks like below.