Serverless EC2 Instance Scheduler for Company Working Hours
Scenario :
In some companies, there is no need to run their EC2 instances 24/7; they require instances to operate during specific time periods, such as company working hours, from 8:00 AM in the morning to 8:45 PM in the evening. To address this scenario, I will implement two Lambda functions responsible for starting and stopping instances. These Lambda functions will be triggered by two CloudWatch Events in the morning and evening. This solution is fully serverless.
Steps below:
Step 1: Creating the Instance
- Navigate to the EC2 Console.
- Follow the Outlined steps below.
Step 2 :
Creating the Policy :
- Navigate to the IAM Console.
- Click on “Policies” and then Click on “Create policy”
3. Select services as EC2.
4. And Actions are DescribeInstances , StartInstances.
5. Now we have created a policy for starting instances. We also need to create a policy for stopping the instances. This is because we are going to create two Lambda functions: one for starting and one for stopping the instances. Each function will have its own role, and we will attach these two policies to their respective roles.
6. Now we are going to repeat the same steps for Creating Stopping Policy also.
7. Everything is same , Except Actions because we are going to stop the instance.
8. The Actions are DescribeInstances , StopInstances .
9. Keep your Plolicy name as "stop-ec2-instance”.
Step 3 :
Creating the Lambda functions :
- Navigate to the lambda Console.
- Follow the Outlined steps below.
Remove the default python script and replace your code here.
Choose Edit here
Click the Role name URL link here.
Select attach policies and Add your created policy here
Click Test to run the Script and See the result like this.
3. Now we created a lambda function for Starting Instance.
4. We have to repeat the same steps to create a lambda function for the stopping instance. Keep your lambda function name as “Stop-EC2-demo”.
5. The only changes we have to make are to replace the default code with the'stop-ec2-instance.py’ code and attach the policy we created for stopping instances to the role of this Lambda function.
6. As demonstrated above, when I test my Python code, it runs successfully and stops the instance.
7. Now, we are ready to proceed and create schedules for this functions.
Step 5 :
Creating the Schedules Using Cloud Watch :
- Navigate to the Cloud Watch Console.
- Follow the outlined steps below.
- We have now created a schedule for starting the instance every day at 8:00 AM.
- Next, we need to create a schedule for stopping instances.
- To create the schedule for stopping instances, follow the same steps as for starting instance scheduling with a few changes, Keep your rule name as “stop-ec2-rule”.
- The changes include modifying the scheduled time and selecting the appropriate scheduling function.
- We need to change the schedule time to 20:45 because it will stop the Lambda function at 20:45 IST (5:00 PM).
- Now, we have successfully created two schedules: one to start the instance every day at 8:00 AM and the other to stop the instance every day at 8:45 PM.
Start Ec2 Instance Script
import boto3
def lambda_handler(event, context):
# Initialize the EC2 client
ec2_client = boto3.client('ec2', region_name='ap-south-1') # Replace your Region name
# Specify the instance ID of the EC2 instance you want to start
instance_id = 'i-051262059d6f6350a' # Replace your Own Instance ID
# Start the EC2 instance
try:
response = ec2_client.start_instances(InstanceIds=[instance_id], DryRun=False)
print(f"Starting EC2 instance {instance_id}...")
print(f"Response: {response}")
return {
'statusCode': 200,
'body': f"EC2 instance {instance_id} is being started."
}
except Exception as e:
print(f"Error starting EC2 instance: {e}")
return {
'statusCode': 500,
'body': f"Error starting EC2 instance: {str(e)}"
}
Stop ec2 Instance
import boto3
def lambda_handler(event, context):
# Initialize the EC2 client
ec2_client = boto3.client('ec2', region_name='ap-south-1') # Replace your Region name
# Specify the instance ID of the EC2 instance you want to stop
instance_id = 'i-051262059d6f6350a' # Replace your Own Instance ID
# Stop the EC2 instance
try:
response = ec2_client.stop_instances(InstanceIds=[instance_id], DryRun=False)
print(f"Stopping EC2 instance {instance_id}...")
print(f"Response: {response}")
return {
'statusCode': 200,
'body': f"EC2 instance {instance_id} is being stopped."
}
except Exception as e:
print(f"Error stopping EC2 instance: {e}")
return {
'statusCode': 500,
'body': f"Error stopping EC2 instance: {str(e)}"
}
Hope it helps..!
Thank you for reading so far! Before you go:
- 👏 Clap for the story if it helped :)
- 📰 View more content from me https://medium.com/@clouddevsecops