Sitemap
solutionamardba

solutionamardba

Starting /Stopping EC2 Instance using Lambda on different Date & Time

2 min readMay 18, 2023
Press enter or click to view image in full size
Picture Melvin L

lamba_function.py

import boto3
import datetime

region = 'ap-south-1'
instances = ['i-0sdfsdf3434']

def lambda_handler(event, context):
current_time = datetime.datetime.now().time()
current_day = datetime.datetime.now().weekday()

ec2 = boto3.client('ec2', region_name=region)

if current_day == 4 and current_time >= datetime.time(22, 0):
ec2.stop_instances(InstanceIds=instances)
print('Stopped your instances: ' + str(instances))
elif current_time >= datetime.time(20, 0):
ec2.stop_instances(InstanceIds=instances)
print('Stopped your instances: ' + str(instances))
else:

print('No action required at the current time.')
Press enter or click to view image in full size
Lambda Function Python Code to Start & Stop EC2
  1. The code uses the datetime module to get the current time and day of the week.
  2. Inside the lambda_handler function, it checks if the current day is Friday (current_day == 4) and the current time is equal to or greater than 10 PM (current_time >= datetime.time(22, 0)).
  • If the condition is true, it stops the instances using ec2.stop_instances() and prints a message.

3. If the current time is equal to or greater than 8 PM (current_time >= datetime.time(20, 0)), it stops the instances using ec2.stop_instances() and prints a message. This condition applies to all days except Friday.

Get solutionamardba’s stories in your inbox

Join Medium for free to get updates from this writer.

4. If the current time and day do not match any of the conditions, it prints a message stating that no action is required at the current time.

Make sure to replace ‘i-0sdfsdf3434’ with the actual instance ID you want to start and stop. Additionally, ensure that you have the necessary permissions in your AWS Lambda function to start and stop EC2 instances.

--

--