Step-by-step scheduled events to execute AWS Lambda functions
Defining the AWS Lambda function
By following the below steps, we can create the lambda function and schedule the cron events to start and stop the virtual machines at the scheduled time. To learn how to create the lambda function, refer to this link.
Step 1: Setting up the demo
Create a Lambda function in Python using Boto3 to stop EC2 instances, adhering to best practices for code structure, error handling, security, and configuration, and deploy it using AWS. Here’s a simple Python example:
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:
# Stop the specified instance
response = ec2.stop_instances(InstanceIds=[instance_id])
# Log success message
print(f"Instance {instance_id} stopped successfully.")
# Return success response
return {
'statusCode': 200,
'body': f'EC2 instance {instance_id} stopped 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 stop EC2 instance {instance_id}. Check CloudWatch logs for more information.'
}
Step 2: Set Up CloudWatch Event Rule
Next, create a CloudWatch event rule to trigger the Lambda function on a schedule. For example, to stop instances every weekday at 7 PM UTC, create a rule with the following cron expression: cron(0 19 ? * MON-FRI *).
- Lambda test status for stopping the instance: The AWS Lambda function is involved, which likely tests the status of an EC2 instance to determine if it needs to be stopped based on certain conditions.
- Stopped Instance: The scheduled task or job (using cron syntax) that will be executed periodically to perform the ec2 instance stop action.
Step 3: Test the Setup
After creating the CloudWatch event rule, you can manually trigger it to test if the Lambda function is executed successfully. Check the CloudWatch Logs for the Lambda function to verify the execution and any potential errors.
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