Terraform, API Gateway and Cognito

I’d like to control API Gateway as an HTTP Proxy to an ALB for an ECS Task.

Unfortunately, Terraform’s support of Cognito isn’t quite there.

There are some features missing:

In this context, I need to add a Cognito Authorizer for an existing User Client Pool.

Currently, Terraform only supports making an authorizer for a lambda only. So creating an authorizer for cognito is a manual step. Creating a cognito authorizer is documented but creating it with the AWS console is easy. Just make it of type COGNITO then select the pool you want.

Next you need to attach the authorizer to the aws_api_gateway_method resources desired. Your methods would look similar to this:

resource "aws_api_gateway_method" "api-gateway-method-post" {
  rest_api_id   = "${aws_api_gateway_rest_api.api-gateway.id}"
  resource_id   = "${aws_api_gateway_resource.api-gateway-resource.id}"
  http_method   = "POST"
  authorization = "COGNITO_USER_POOLS"
  authorizer_id = "${var.cognito-authorizer-id}"

variable "cognito-authorizer-id" {
  default = "9rvrci"

Setting authorization to COGNITO_USER_POOLS isn’t documented but it currently works.

The hard part here is finding the authorizer id. I found this by setting using it manually in the AWS console then running terraform plan to see what terrafrom would change the value of a current method from to empty. I’m sure there are better ways.


Process for API Gateway with Cognito Authorizer

  • Create API Gateway (minus authorizer) with Terraform
  • Create Cognito User Pool (maybe without Terraform)
  • Create Cognito Authorizer on the API Gateway (without Terraform)
  • Add Cognito Authorizer details to the Terraform configuration then apply

One day soon, Terraform will support all this 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s