微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在“serverless.yml”的“Resources”中使用“If”条件?

如何解决如何在“serverless.yml”的“Resources”中使用“If”条件?

我试图在 !If 部分使用 resources 条件但失败了。我想控制是否在我的 lambda 上设置 provisionedConcurrency。 lambda 在 function 部分下定义。


functions:
  getTransactionsHandler:
    ...

resources:
  Conditions:
    CommonPCNotZero: !Not [!Equals [0,'${self:custom.commonPC}']]
  Resources:
    !If 
      - CommonPCNotZero
      - getTransactionsHandler:
        Type: AWS::Lambda::Alias
          Properties:
            FunctionName: !Ref GetTransactionsHandlerLambdaFunction
            FunctionVersion: !Join ['',[!Ref GetTransactionsHandlerLambdaFunction,':$LATEST']]
            ProvisionedConcurrencyConfig:
              ProvisionedConcurrentExecutions: '${self:custom.commonPC}'
      - !Ref AWS::Novalue

运行 sls deploy 时出现以下错误

Error: The CloudFormation template is invalid: Template format error: [/Resources/Fn::If] resource deFinition is malformed

使用 !if 条件的正确方法是什么?

解决方法

对于资源,您只需添加一个 Condition 来包含或排除它。

functions:
  getTransactionsHandler:
    ...

resources:
  Conditions:
    CommonPCNotZero: !Not [!Equals [0,'${self:custom.commonPC}']]
  Resources:
    getTransactionsHandler:
      Type: AWS::Lambda::Alias
      Condition: CommonPCNotZero
      Properties:
        FunctionName: !Ref GetTransactionsHandlerLambdaFunction
        FunctionVersion: !Join ['',[!Ref GetTransactionsHandlerLambdaFunction,':$LATEST']]
        ProvisionedConcurrencyConfig:
          ProvisionedConcurrentExecutions: '${self:custom.commonPC}'

另外,注意你的缩进。 TypeProperties 应该处于同一级别。

,

您不能使用 If 使整个资源成为条件。通常,应使用 Condition 完成以下操作:

resources:
  Conditions:
    CommonPCNotZero: !Not [!Equals [0,'${self:custom.commonPC}']]
  Resources:
     
     MyLambdaAlias: 
        Type: AWS::Lambda::Alias
        Condition: CommonPCNotZero
        Properties:
            FunctionName: !Ref GetTransactionsHandlerLambdaFunction
            FunctionVersion: !Join ['',':$LATEST']]
            ProvisionedConcurrencyConfig:
              ProvisionedConcurrentExecutions: '${self:custom.commonPC}'

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。