'Cognito User Pool Authorizer defined in openapi without hardcoded values

I have a API Gateway Rest Api resource defined with this template:

AWSTemplateFormatVersion: '2010-09-09'
Description: "Api gateway"
Resources:
  ApiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      BodyS3Location: "./openapi-spec.yaml"

And the contents of openapi-spec.yaml (based on this example) being:

openapi: "3.0.2"
info:
  title: SampleApi
paths:
  /test:
    get:
      summary: Test
      responses:
        "200":
          description: Ok
      security:
        - UserPool: [ ]
      x-amazon-apigateway-integration:
        # ....

components:
  securitySchemes:
    UserPool:
      type: apiKey
      name: Authorization
      in: header
      x-amazon-apigateway-authtype: cognito_user_pools
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          ### THIS VALUE ###
          - "arn:aws:cognito-idp:eu-west-1:123456789012:userpool/eu-west-1_abcd12345"

I'd like to be able to deploy this template in multiple environments/account and having this hardcoded providerARN is limiting that. So my questions are:

How can values for the providerARNs field be passed in dynamically?

If that can't be done, then are there any workarounds to this so that I don't have to hardcode the providerArns here?

Note: Already tried to use stage variables and they don't seem to work here.



Solution 1:[1]

If you don't have an existing Cognito user pool then you would have to define one using AWS::Cognito::UserPool in CloudFormation, then you can simply reference the arn of this user pool using !GetAtt.

But if you have an existing Cognito user pool then you can also import it to a stack using CloudFormation following these steps.

Here's an example:

template.yaml

Resources:
  ApiGateway:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      BodyS3Location: "./openapi-spec.yaml"

  CognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      # ....

openapi-spec.yaml

openapi: "3.0.2"
# ....
components:
  securitySchemes:
    UserPool:
      type: apiKey
      name: Authorization
      in: header
      x-amazon-apigateway-authtype: cognito_user_pools
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          - !GetAtt CognitoUserPool.Arn

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1