AWS EventBridge provides a powerful mechanism to automate tasks and respond to changes in your cloud environment. Combining EventBridge with AWS Lambda allows you to create scalable, event-driven architectures. In this blog, we’ll walk through how to create an EventBridge rule using a Lambda function to trigger another Lambda function.
Why Automate with EventBridge and Lambda?
EventBridge simplifies automation by enabling scheduled or event-based task execution. When integrated with Lambda, it eliminates the need for dedicated cron servers, allowing you to define tasks programmatically.
This guide demonstrates a Python-based Lambda function to create an EventBridge rule dynamically, schedule its execution, and target another Lambda function.
Prerequisites
- AWS Account: Ensure you have access to your AWS account.
- IAM Permissions:
events:PutRuleevents:PutTargets - Lambda Functions:
One Lambda to manage the EventBridge rules (creator function).
One target Lambda for testing purposes.
The Lambda Code: Creating EventBridge Rules
Here’s the complete Python code for your Lambda function:
import boto3
import json
from datetime import datetime
def create_cron_expression(input_time, input_date=None):
"""
Generate a cron expression from the given time and optional date.
"""
try:
if input_date:
# Parse the date and time
dt = datetime.strptime(f"{input_date} {input_time}", "%m/%d/%Y %H:%M")
cron_expression = f"cron({dt.minute} {dt.hour} {dt.day} {dt.month} ? {dt.year})"
else:
# Parse only the time, assumes it repeats daily
hour, minute = map(int, input_time.split(":"))
cron_expression = f"cron({minute} {hour} * * ? *)"
return cron_expression
except ValueError as e:
raise ValueError(f"Invalid date/time format: {e}")
def lambda_handler(event, context):
"""
AWS Lambda function to create an EventBridge rule and link it to a target Lambda function.
"""
try:
# Extract parameters from the event
rule_name = event["name"]
data = event["data"]
region = event["region"]
lambda_arn = event["lambda_arn"]
input_time = event["input_time"]
input_date = event.get("input_date") # Optional
# Initialize the EventBridge client
# Create the cron expression
cron_expression = create_cron_expression(input_time, input_date)
# Define the rule name and description
rule_name = f"{rule_name}"
rule_response = eventbridge.put_rule(
Name=rule_name,
ScheduleExpression=cron_expression,
State="ENABLED",
Description=f"Rule to trigger {data}"
)
# Add the Lambda function as the target
target_response = eventbridge.put_targets(
Rule=rule_name,
Targets=[
{
"Id": "1",
"Arn": lambda_arn,
}
]
)
return {
"statusCode": 200,
"body": json.dumps({
"message": "EventBridge rule created successfully.",
"rule_response": rule_response,
"target_response": target_response
})
}
except Exception as e:
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)})
}Breaking Down the Code
- Create a Cron Expression: The
create_cron_expressionfunction generates a valid cron expression for EventBridge, supporting both specific dates and daily schedules. - Lambda Handler:
Extracts required details from the inputevent.
Creates the EventBridge rule usingput_rule.
Links the target Lambda function to the rule usingput_targets. - Error Handling: Comprehensive error handling ensures proper debugging in case of input issues or API failures.
Example Input for Lambda
Here’s an example JSON payload to test the Lambda function:
{
"name": "DailyLambdaTrigger",
"data": "Trigger for processing data",
"region": "us-east-1",
"lambda_arn": "arn:aws:lambda:us-east-1:123456789012:function:YourTargetLambdaFunction",
"input_time": "14:30",
"input_date": "01/15/2025" # Optional
}input_time: The time at which the rule triggers (in HH:MM, 24-hour format).input_date: Use for specific dates.
Deployment Steps
- Upload the Code:
Save the code aslambda_function.py.
Deploy it to your Lambda function via the AWS Management Console or CLI. - Add Permissions: Ensure the Lambda function has permissions to create EventBridge rules and targets.
- Test the Function: Use the above JSON payload as a test event.
Conclusion
This Lambda function provides a flexible and scalable way to automate tasks using EventBridge. With just a few lines of code, you can dynamically schedule events and target resources in your AWS environment.






