SERVERLESS EC2 INSTANCE SHUT DOWN SCHEDULER FOR ORGANISATION WORKING HOURS
** Scenario:**: In some companies, there is no need to run EC2 instances round the clock. they require instances to operate during specific time periods. To address this, We will implement Lambda function for stopping the instances and set up cloudwatch events that will triger the lambda fucntion at exactly 12:00.
Steps:
Step 1
Creating Instances or use existing instances
Step 2:
Creating the Policy:
-
Navigate to the IAM Console
-
Select services as Ec2.
-
And Actions are DescribeInstances, StopInstances
-
NB: change the policy name to stop-ec2-instance and the description to stop ec2 running instances -
Now that we have created a policy for stopping instances, we are going to create a Lambda function with its role and attach the policy to that role.
Step 3
Creating the Lambda functions:
-
Navigate to Lambda on the management console
-
Follow the outlined steps below
-
Remove the default function and paste stop-ec2-instance-py python code
-
Click on "Deploy" to save the changes
-
Click on "Test"
-
Click on " Configuration" on the Lambda functin Tab and click on the "Stop-Ec2-Instances-role-ik9mtlab". It will open a new tab to add permision to the role
-
Select the policy you created before and click "Add permision"
-
Now go back to the Lambda console and then test the code. You will see Execution succeeded and the instances in stopped state.
-
Now we are ready to proceed and create schedules for this Functions
Step 4
Creating the Schedues Using Cloud watch
-
Navigate to the CloudWatch console
-
Follow the outlined steps below
-
Click "Continue in EventBrigde Scheduler"
-
Select "Recurring Schedule" and "Cron-Based Schedule"
-
Set the Cron Tab as follow to automatically triger by 12:00 based on your time zone
-
Choose your Lambda function to stop ec2 instance and click " Next"
-
Also choose "NONE" from the Action after schedule completion
We have successfully cretaed a Lambda function that will be triggered by CloudWatch EventBridge schedule to shut down running ec2 instances by 12:00am everyday.
-












