Search code examples
amazon-web-servicesaws-lambdaaws-cloudformationaws-sam

How do I get the rate of the schedule that triggered a lambda?


I have multiple event schedules attached to a single lambda:

  Events:
    1minute:
      Type: Schedule
      Properties:
        Schedule: rate(1 minute)
    2minute:
      Type: Schedule
      Properties:
        Schedule: rate(2 minutes)
    etc...

The lambda does different things based on the schedule. The logic is super simple so it's much simpler to attach multiple schedules to the same function instead of creating multiple separate functions.

I can parse the event name from the event and use that to determine what the schedule is.

Creating them with the sam template though means they wind up having names like:

myapp-myfunction2minutes-ABC123XDJXKDF

I still want them to be created dynamically. I don't want to set static names because that would prevent multiple stacks from existing simultaneously and I want them to be fully namespaced and isolated.

I can certainly parse myapp-myfunction2minutes-ABC123XDJXKDF because it's predictable enough, but it would be even better if I could add some other field with arbitrary metadata so I would not have to do any string parsing. Is this supported?

Edit

Configuring this in a template looks like this:

  Events:
    1minute:
      Type: Schedule
      Input: '{"Key": "Value1"}'
      Properties:
        Schedule: rate(1 minute)
    2minute:
      Type: Schedule
      Input: '{"Key": "Value2"}'
      Properties:
        Schedule: rate(2 minutes)
    etc...

Then "Input" replaces the entire event sent to the lambda. So in the function (if python) can access like event["Key"].

Another thing that tripped me up was that Input seems to be directly connected to the specific lambda it's created under. In testing I deployed the stack with these events configured with inputs, then to do a quick test I attached one of the events (the CloudWatch rule) to a different lambda to try and read the event it created. Doing that didn't work, the other lambda was triggered on the schedule but the event object sent to it didn't have the Input- it was a regular CloudWatch schedule event object.


Solution

  • It seems that you want to know which schedule triggered the Lambda function. Well, you actually asked for the rate, but hopefully knowing which schedule triggered it will be just as good.

    When you add the Lambda trigger, you can specify a Constant, which will be passed through the event. You can use this to trigger the desired behaviour.

    CloudWatch Events rule