Scheduled Lambda with Pulumi
2 min readJan 9, 2023
This post assumes you have working knowledge of AWS Lambda and Pulumi Framework.
Lambda is great to perform simple task, but you can not natively schedule an invocation. You need to use EventBridge (former CloudWatch event) as a trigger.
Here is a working example with Pulumi (using Python) that you can copy/paste. You just need:
- A lambda function running with Pulumi. We assume we can use “myproject_lambda” object in the code (replace it!)
# Create an EventBridge (ex-CloudWatch event) rule
myproject_event_rule = aws.cloudwatch.EventRule(
"myproject-event-rule",
name="myproject-event-rule", # will be inserted in event body
schedule_expression="rate(1 minute)", # replace it with you cron definition
)
# Gives this event the permission to invoke lambda function
myproject_lambda_event_permission = aws.lambda_.Permission(
"myproject-lambda-event-permission",
action="lambda:InvokeFunction",
function=myproject_lambda.name,
principal="events.amazonaws.com",
source_arn=myproject_event_rule.arn
)
# Configure event to invoke lambda function
myproject_event_target = aws.cloudwatch.EventTarget(
"myproject-event-target",
arn=myproject_lambda.arn,
rule=myproject_event_rule.name,
)
In the example the cron definition is “rate(1 minute)” as it is quick to see whether it works. You can change the interval, or use a more standard “cron(* * * * * *)” by following the AWS documentation.
How to handle those invocations in our lambda?
def lambda_handler(event, context):
# Check if the trigger is a scheduled event
if (event
and event.get('source', '') == 'aws.events'
and event.get('detail-type', '') == 'Scheduled Event'):
# We check it comes from a known resource
resources = event.get('resources', [])
if resources and resources[0] \
and resources[0].endswith('myproject-event-rule'):
print('starting myproject invocation')
# PASTE HERE THE ACTUAL CODE YOU WANT TO RUN
return {
'statusCode': 200,
'body': 'myproject invocation complete'
}
# Next handlers...
That’s it! Just “pulumi up” and enjoy!