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!')
    }

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



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

Banner credits:

Comments