terraformaws-api-gatewayterraform-provider-awsamazon-vpcapi-gateway

How to Use Stage Variables for connection_id in aws_api_gateway_integration with Terraform?


I'm working with AWS API Gateway and Terraform, and I need some help with using stage variables in the connection_id field of an aws_api_gateway_integration resource.

I want to use a stage variable "${stageVariables.vpcLinkId}" to dynamically set the connection_id for an API Gateway integration that uses a VPC Link.

resource "aws_api_gateway_integration" "vpc_integration_delete" {
  rest_api_id             = aws_api_gateway_rest_api.example.id
  resource_id             = aws_api_gateway_resource.example.id
  http_method             = "DELETE"
  type                    = "HTTP_PROXY"
  integration_http_method = "POST"
  uri                     = "http://example.com/resource"
  connection_type         = "VPC_LINK"
  connection_id           = "${stageVariables.vpcLinkId}" 
}

Terraform doesn't seem to support using stageVariables.vpcLinkId in the connection_id field directly. When I apply the configuration its give an error like this "A managed resource "stageVariables" "vpcLinkId" has not been declared in the root module." but I have already defined the stage variable in the aws_api_gateway_stage resource like this:

resource "aws_api_gateway_stage" "example_stage" {
  stage_name   = "dev"
  rest_api_id  = aws_api_gateway_rest_api.example.id
  deployment_id = aws_api_gateway_deployment.example.id

  variables = {
    vpcLinkId = aws_api_gateway_vpc_link.example.id
  }
}

Is there a way to use stage variables like stageVariables.vpcLinkId in the connection_id field of an aws_api_gateway_integration resource in Terraform? If not, what would be the best approach to dynamically set the connection_id based on the stage variable, while still managing everything through Terraform?

I have already defined the stage variable in the aws_api_gateway_stage resource like this:

resource "aws_api_gateway_stage" "example_stage" {
  stage_name   = "prod"
  rest_api_id  = aws_api_gateway_rest_api.example.id
  deployment_id = aws_api_gateway_deployment.example.id

  variables = {
    vpcLinkId = aws_api_gateway_vpc_link.example.id
  }
}

Solution

  • The problem is that API Gateway and Terraform use the same syntax for templating, namely ${...}. Stage variable substitution is something API Gateway is supposed to do, not terraform. Therefore you need to make sure that terraform ignores the template strings by escaping it. The syntax for escaping it is $${...}:

    connection_id = "$${stageVariables.vpcLinkId}" 
    

    this will result in ${stageVariables.vpcLinkId} actually being sent to the API Gateway instead of terraform interpreting it.