• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

Creating EventBridge Rules in Lambda

Arya P B

  • 3 min read
Creating EventBridge Rules in Lambda

Generating audio, please wait...

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

  1. AWS Account: Ensure you have access to your AWS account.
  2. IAM Permissions:
    events:PutRule
    events:PutTargets
  3. 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

  1. Create a Cron Expression: The create_cron_expression function generates a valid cron expression for EventBridge, supporting both specific dates and daily schedules.
  2. Lambda Handler:
    Extracts required details from the input event.
    Creates the EventBridge rule using put_rule.
    Links the target Lambda function to the rule using put_targets.
  3. 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

  1. Upload the Code:
    Save the code as lambda_function.py.
    Deploy it to your Lambda function via the AWS Management Console or CLI.
  2. Add Permissions: Ensure the Lambda function has permissions to create EventBridge rules and targets.
  3. 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.

  • DevOps
  • AWS
Promotional banner
Promotional banner
Creating EventBridge Rules in Lambda

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • AWS
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Posts by Arya P B

Athena