Coding the AWS Lambda function
Step 4: Modify Lambda Function to Start Instances
Similarly, you can create another Lambda function to start EC2 instances and set up another CloudWatch event rule to trigger it in the morning. Here’s an example of a Lambda function to start instances:
import json
import boto3
def lambda_handler(event, context):
# TODO implement
ec2 = boto3.client('ec2')
# Specify the instance ID of the EC2 instance to stop
instance_id = 'i-00c018f88e8e99967' #Put your instance Id
try:
# Start the specified instance
response = ec2.start_instances(InstanceIds=[instance_id])
# Log success message
print(f"Instance {instance_id} started successfully.")
# Return success response
return {
'statusCode': 200,
'body': f'EC2 instance {instance_id} started successfully!'
}
except Exception as e:
# Log error message
print(f"An error occurred: {str(e)}")
# Return error response
return {
'statusCode': 500,
'body': f'Failed to start EC2 instance {instance_id}. Check CloudWatch logs for more information.'
}
How To Create Cron Job In AWS Lambda?
A Cron job works like scheduling a task in any system. It is mainly used for backups, system maintenance, etc. Cron’s job works on both local systems as well as cloud services. To run the crown job in AWS, we have to use AWS Lambda. In AWS Lambda, we set up the functions and schedule a time to run them.
Contact Us