DEV Community

Cover image for How to Update EventBridge Schedules with Lambdas
Federico Navarrete
Federico Navarrete

Posted on • Edited on • Originally published at supernovaic.blogspot.com

How to Update EventBridge Schedules with Lambdas

The EventBridge is a potent tool in AWS that can help us automate our tasks. However, when you need to have dynamic schedules, it can be tricky.

First of all, the Boto3 is not the latest running on Lambdas. The current available for Python 3.9 on Jan 16, 2023, is 1.20.32 (print(boto3.__version__)), and the latest released is 1.26.50:
https://github.com/boto/boto3

Therefore, you have to do the extra steps to zip it and add it as a layer:

  1. Install boto3 to /python directory
    $ pip install boto3 -t ./python

  2. Zip it
    $ zip -r layer.zip ./python

  3. Upload it to AWS as a Layer and configure it:
    https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

After you have done this, you need to create a Lambda function with a similar code to the one I'm sharing:



import json
import boto3

from datetime import datetime, timedelta

scheduler_client = boto3.client('scheduler')

#schedule the EventBridge Schedule to run 5 min from now
schedule_time = datetime.now() + timedelta(minutes=5)

#these values come from the EventBridge schedule itself
event_scheduler_name = 'MY_EVENT_NAME'
target_arn = 'MY_TARGET_ARN'
role_arn = 'MY_ROLE_ARN'

def lambda_handler(event, context):

    scheduler_client.update_schedule(Name=event_scheduler_name,
                                     ScheduleExpression=f'cron({schedule_time.minute} {schedule_time.hour} {schedule_time.day} {schedule_time.month} ? {schedule_time.year})',
                                     FlexibleTimeWindow={
                                        'MaximumWindowInMinutes': 1,
                                        'Mode': 'FLEXIBLE'
                                     },
                                     Target={
                                         'Arn': target_arn,
                                         'RoleArn': role_arn
                                     })

    return {
        'statusCode': 200,
        'body': json.dumps('Working!')
    }


Enter fullscreen mode Exit fullscreen mode

The tricky values, the ARN and the RoleArn, come from the EventBridge Schedule:

Arn

RoleArn

Now, you're ready to create dynamic schedules with Python.

Banner credits:

Boyney123

Follow me on:

Personal LinkedIn YouTube Instagram Cyber Prophets Sharing Your Stories
Personal LinkedIn YouTube Instagram RedCircle Podcast RedCircle Podcast

sponsor me

Top comments (0)