SCHEDULE AN AWS EC2 INSTANCE SHUTDOWN

Posted on January 31, 2024

0


Event Bridge will trigger the Lambda Function, Lambda will check the assigned role and assigned role will further check the policy permissions of stop EC2 instance
AGENDA
1- Create Policy
2- Create Role
3- Create Lamdba Function
4- Create Schedule

1- Create Policy

Create a policy with stop EC2 instance permission

2- Create Role

Create a role to trigger Lamdba
3- Create Lamdba Function
Below are the start and stop lambda functions. incase you need both to utilize, you can use it
LAMBDA FUNCTION FOR STOP INSTANCE
import boto3

region = 'us-east-1'
instances = ['i-01de805ca39414bee']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
LAMBDA FUNCTION FOR START INSTANCE
import boto3

region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
Now start the EC2 instance and test the Lambda function to makesure that EC2 is getting shutdown thru TEST button in above picture. When you click on test it will offer you to make a test event like below picture
4- Create Schedule

The above picture says the schedule is define 01:10 PM GMT+5. You can set what ever time which you are interested in to trigger
Now when the Schedule trigger on mentioned time it will invoke the Lambda function which then trigger the STOP permission of EC2 which we configure in Policy
Posted in: Tech News