在 AWS sam 模板文件中有条件地启用事件计划

Conditionally enabling an event schedule in AWS sam template file

这是我的(缩短的)template.yml 文件:

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

我想做的是仅在 EnvType 参数设置为 qc1 时启用该计划。问题是,我无法让 Equals condition or the If condition 工作。我已经尝试了以下所有方法:

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

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]

在测试所有这四种情况之间,我删除了整个堆栈,而不是尝试更新它们,作为 中的评论,我还三次检查传入的参数不是 qc1,并且也只需将 Enabled 标志设置为 False 以确保它实际上会禁用计划,它确实这样做了。在这一点上我很困惑,有没有人知道我做错了什么或者我可以尝试什么?

我遇到了同样的问题。显然 Enabled 属性 不能很好地与 !If!Equals 一起使用。我在 Schedule 属性:

中用 hack 修复了它
 Events:
   InvocationLevel:
     Type: Schedule
     Properties:
        Schedule: !If [IsQcEnv, "rate(2 hours)", "cron(0 0 31 2 ? *)"]

如果envType 不是qc1,将使用cron 表达式。该表达式将在 2 月 31 日执行您的函数。这意味着它永远不会执行。

我在这些答案的帮助下找到了这个解决方案: