Cannot add Auth property of AWS::Serverless::Api resource conditionally

Viewed 318

I'm attempting to add the Auth property to an AWS::Serverless::Api resource conditionally using an Fn::If conditional function like below so that the ResourcePolicy is only added when I deploy to production.

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
        <...>

Running sam validate on this template I get the error below

Error: [InvalidResourceException('RestApi', "Invalid value for 'Auth' property")] ('RestApi', "Invalid value for 'Auth' property")

When I remove the !If function and add the Auth properties directly to the resource, the API deploys as expected with the attached resource policy.

I've also tried adding the !If function under the ResourcePolicy resource in combination with the AWS::NoValue pseudo parameter like below.

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"

Using the above snippet in my template, I don't get any errors when running sam validate. However, I get the error below in the CloudFormation events when running sam deploy.

Invalid policy document. Please check the policy syntax and ensure that Principals are valid. (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException; Request ID: bce87a44-07d1-49a3-a983-3370b0d0bd09; Proxy: null)

1 Answers
Related