无法有条件地添加 AWS::Serverless::Api 资源的 Auth 属性

时间:2021-04-07 20:39:11

标签: amazon-web-services amazon-cloudformation aws-serverless aws-sam

我正在尝试使用如下所示的 Auth 条件函数有条件地将 AWS::Serverless::Api 属性添加到 Fn::If 资源,以便仅在部署时添加 ResourcePolicy到生产。

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: 'My application'
Parameters:
  ProdEnvironment:
    Type: String
    Default: "false"
    Description: "Should be true or false"
    AllowedValues: [true, false]
Conditions:
  AddResourcePolicy: !Equals [!Ref ProdEnvironment, "true"]
Resources:
  RestApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: "my-api"
      Description: "My API Gateway that I can't deploy"
      DefinitionBody:
        <...>
      Auth:
        !If 
        - AddResourcePolicy
        - ApiKeyRequired: true
          InvokeRole: NONE
          ResourcePolicy:
            CustomStatements:
            - Effect: "Allow"
              Principal: "*"
              Action: "execute-api:Invoke"
              Resource: "execute-api:/*"
              Condition:
                IpAddress:
                  aws:SourceIp:
                  - "<my_approved_ip_1>"
                  - "<my_approved_ip_2>"
        - ApiKeyRequired: true
          InvokeRole: NONE
        <...>

在此模板上运行 sam validate 时出现以下错误

<块引用>

错误:[InvalidResourceException('RestApi', "'Auth' 的值无效 属性")] ('RestApi', "'Auth' 属性的值无效")

当我删除 !If 函数并将 Auth 属性直接添加到资源时,API 会使用附加的资源策略按预期部署。

我还尝试在 ResourcePolicy 资源下添加 !If 函数以及如下所示的 AWS::NoValue 伪参数。

Auth:
  ApiKeyRequired: true
  InvokeRole: NONE
  UsagePlan:
    UsagePlanName: !Join ["-", [!Ref ApiName, Basic]]
    CreateUsagePlan: PER_API
    Description: "User data management basic usage plan"
  ResourcePolicy:
    !If AddResourcePolicy    
    - CustomStatements:
      - Effect: "Allow"
        Principal: "*"
        Action: "execute-api:Invoke"
        Resource: "execute-api:/*"
        Condition:
          IpAddress:
            aws:SourceIp:
              - "<my_approved_ip_1>"
              - "<my_approved_ip_2>"
    - !Ref "AWS::NoValue"

在我的模板中使用上述代码段后,运行 sam validate 时不会出现任何错误。但是,我在运行 sam deploy 时在 CloudFormation 事件中收到以下错误。

<块引用>

无效的政策文件。请检查策略语法并确保 Principals 有效。 (服务:AmazonApiGateway;状态代码:400;错误代码:BadRequestException;请求 ID:bce87a44-07d1-49a3-a983-3370b0d0bd09;代理:null)

1 个答案:

答案 0 :(得分:1)

仅供参考,这似乎是一个悬而未决的问题。见https://github.com/aws/serverless-application-model/issues/1859