Open In App

How To Create Cron Job In AWS Lambda?

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

What are Cron Jobs?

Cron jobs are scheduled tasks that enable the automated execution of operations by running at predetermined times or intervals. They are defined using cron expressions, which, for daily execution at midnight UTC, provide the schedule in a succinct style such as “0 0 * *?” This makes it possible for regular maintenance, backups, and data processing to be carried out on a regular basis without the need for human participation. To learn more about the cron job, refer to this link.

Amazon CloudWatch events

Amazon CloudWatch is used in AWS Lambda to notify users whenever any changes occur. For example, if I add any resources or make any changes, then CloudWatch will send me a message as a notification. Now, in this, we can set up anything, such as if our server resource will automatically scale up, then run the Lambda function. In CloudWatch, we can also schedule the time. If we want to shut down all the instances at 6 PM and start at 8 AM, then we can do so.

What is a lambda function?

When managing EC2 instances, lambda functions concentrate on specifying why they are there in order to launch and stop instances quickly. For implementation, use Python with Boto3, making sure to follow clean code guidelines and handle errors appropriately. To ensure a smooth integration of the function into your AWS environment, configure IAM roles with granular permissions.

Here are a few benefits of using the lambda function:

  • The overhead of managing servers is eliminated with serverless architecture.
  • Under changing workloads, automatic scaling guarantees consistent performance.
  • A pay-per-use pricing strategy that only charges for compute time optimizes expenses.

IAM Role

The administration of EC2 instances by the AWS Lambda function places emphasis on the establishment of an IAM role that grants rights such as AmazonEC2FullAccess in order to guarantee correct execution. Furthermore, emphasize how this role may be attached to the Lambda function for easy integration and efficient management of EC2 resources. For more details on how to create the AWS IAM role, refer to this link.

Lambda Permission

Before defining the Lambda function’s permissions, make sure to include IAM roles that grant the required access, like AmazonEC2FullAccess, to allow smooth EC2 instance management. To improve security posture and restrict access to only the required assets and actions, make sure that the least privilege principles are followed. Finally, to facilitate seamless integration and execution within the AWS environment, link the IAM role to the Lambda function.

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.

stop_status

  • Stopped Instance: The scheduled task or job (using cron syntax) that will be executed periodically to perform the ec2 instance stop action.

Stoped_instance

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.

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.'
}

Running the cron job

Here is the lambda function triggered successfully and the ec2 instance started successfully for your reference refer the below screenshots.

  • Lambda test status for starting the instance: The AWS Lambda function is involved, which likely tests the status of an EC2 instance to determine if it needs to be start based on certain conditions.

running_status

  • Running Instance: The scheduled task or job (using cron syntax) that will be executed periodically to perform the running action.

Running_instance

With this setup, you can automate the process of stopping and starting EC2 instances based on a schedule using Lambda and CloudWatch events. This helps you save costs by only running instances when they’re needed.

Cleaning up your Lambda Function

Here is the steps to delete the lambda function on AWS console.

  • Select the lambda function you want to delete.
  • Click on the function name to open its details.
  • In the top-right corner of the function details page, click on the “Actions” dropdown menu.
  • From the dropdown menu, select “Delete function.”
  • Confirm the deletion when prompted.

Delete

Conclude

Lambda is a function which helps to perform all type of task in AWS. And with the help of CloudWatch even, we can get the notification of any changes and then we can access all the services using AWS SDK.

Cron job in AWS Lambda – FAQs

How do I create a cron Lambda?

  • Write a Lambda function code to execute your desired task.
  • Set up a CloudWatch Events rule with a cron expression to trigger the Lambda at scheduled

Is Lambda good for cron jobs?

Yes, AWS Lambda is suitable for cron jobs:

  • Allows you to run code without managing servers.
  • Ideal for periodic tasks using scheduled events or CloudWatch Events.

How do I set Lambda execution time?

For effective resource allocation and prevent long-running employment opportunities, configure the function’s timeout setting in the AWS Lambda console or via the CLI to set the maximum length for execution.

Which language is faster in AWS Lambda?

Python and Node.js are both well-liked options for AWS Lambda; but, because of its event-driven architecture and non-blocking I/O, Node.js typically provides marginally faster execution times, making it a good choice for effectively managing asynchronous tasks inside Lambda functions. Nevertheless, for the majority of use cases, the performance difference between the two languages is frequently insignificant, therefore application requirements and developer comfort should come first.

How do I set cron timings?

A cron expression, which consists of five fields denoting the minute, hour, day of month, month, and day of week, respectively, can be used to set cron timings. To define the timetable, you can enter exact values, ranges, or wildcards in each field.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads