Using Lambda To Start And Stop Ec2 Instance


In many use cases, you dont need to run EC2 whole day, it will be optimum to stop the ec2 when not in use. This will not just save money for you, it will save energy used to run idle server. Following steps are required to start and stop ec2 automatically. Here we will start and stop ec2 based on cron schedule. 1. create a Lambda function to start and stop ec2. 1. create a policy that will allow to do start and stop action on ec2. 1. attached this policy to lambda function role. 1. create Eventbridge schedule to trigger lambda function which will start/stop ec2. #### lambda function to start ec2 ```python import boto3 region = 'ap-south-1' instances = ['i-111111a22a399999'] ec2 = boto3.client('ec2', region_name=region) def lambda_handler(event, context): ec2.start_instances(InstanceIds=instances) print('stopped your instances: ' + str(instances)) ``` #### Lamnda function to stop ec2 ```python import boto3 region = 'ap-south-1' instances = ['i-111111a22a399999'] ec2 = boto3.client('ec2', region_name=region) def lambda_handler(event, context): ec2.stop_instances(InstanceIds=instances) print('stopped your instances: ' + str(instances)) ``` ### policy to allow ec2 start and stop ```json { "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": "*" } ] } ``` **Note:** please add this policy to lambda roles from IAM, otherwise, you will get below error ```terminal [ERROR] ClientError: An error occurred (UnauthorizedOperation) when calling the StopInstances operation: You are not authorized to perform this operation. User: arn:aws:sts::012444455555:assumed-role/ec2_start-role-c0asas4ik/ec2_start is not authorized to perform: ec2:StopInstances on resource: arn:aws:ec2:ap-south-1:012444455555:instance/i-i-111111a22a399999 because no identity-based policy allows the ec2:StopInstances action. ``` ### create Eventbridge schedule. Sample expression to run job at 9 AM in morning for all weekdays is as below ` 0 9 ? * MON-FRI * `

This post is written by Pravin

Tags : AWS

Share it :      

Leave a comment

captcha


Tags

Elsewhere

  1. GitHub
Ad below