Search code examples
amazon-web-servicesaws-cloudformationaws-event-bridge

Conditionally enabling an event schedule in AWS sam template file


This is my (shortened) template.yml file:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: CF template for foobar

Parameters:
  EnvType:
    Type: String
    Description: The environment to deploy to.
    AllowedValues:
      - dev1
      - qc1
      - uat1
    Default: dev1

  VeryImportantFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/very_important/
      Handler: app.very_important
      Runtime: python3.8
      {unrelated policies and environment variables}
      Events:
        VeryImportantSchedule:
          Type: Schedule
          Properties:
            Schedule: 'rate(2 hours)'
            Enabled: True

What I am trying to do is only enable that schedule when the EnvType parameter is set to qc1. The problem is, I can't get either the Equals condition or the If condition to work. I have tried all of the following:

Enabled: !Equals [!Ref EnvType, qc1]
Enabled: !Equals [!Ref EnvType, "qc1"]

and

Conditions:
  IsQcEnv: !Equals [!Ref EnvType, qc1]
  {and}
  IsQcEnv: !Equals [!Ref EnvType, "qc1"]

....
....
....
      Events:
        VeryImportantSchedule:
          Type: Schedule
          Properties:
            Schedule: 'rate(2 hours)'
            Enabled: !If [IsQcEnv, True, False]

In between testing all four of those cases, I deleted my entire stack rather than trying to update them, as a comment in this post suggested. I also triple checked that the parameter being passed in is not qc1, and also just set the Enabled flag to False to make sure that it would actually disable the schedule, which it did. At this point I'm stumped, does anyone have any idea of what I'm doing wrong or what I could try?


Solution

  • I had the same problem. Apparently the Enabled property does not work well with !If or !Equals. I fixed it with a hack in the Schedule property:

     Events:
       InvocationLevel:
         Type: Schedule
         Properties:
            Schedule: !If [IsQcEnv, "rate(2 hours)", "cron(0 0 31 2 ? *)"]
    

    If the envType is not qc1, the cron expression will be used. This expression will execute your function on February 31st. Which means it will never execute.

    I found this solution with help from those answers:

    https://stackoverflow.com/a/65214717/517173

    https://stackoverflow.com/a/13938155/517173