amazon-web-servicesaws-lambdaterraformaws-api-gateway

AWS Terraform Multiple deployments to single apigateway stage


I intend to setup multiple git repositories that has lambda deployment that is deployed to a stage such as “dev”. According to the terraform apigateway documentation to manage a stage, recommendation is to use resource aws_api_gateway_stage.

If I create resource aws_api_gateway_stage in each of my git repositories, there will be failures since there is already a stage “dev” that was created by one of my repos.

Question: How can I reference an existing stage in my lambda git repos that are using the same api gateway.

Terraform has deprecated stage_name attribute for resource aws_api_gateway_deployment

enter image description here

resource "aws_api_gateway_stage" "dev" {
  deployment_id = aws_api_gateway_deployment.deployment.id
  rest_api_id   = data.aws_api_gateway_rest_api.my_api.id
  stage_name    = "dev"
}
resource "aws_api_gateway_deployment" "deployment" {
  depends_on = [
    aws_api_gateway_integration.lambda_integration,
    aws_api_gateway_integration.options_integration,
  ]
  rest_api_id = data.aws_api_gateway_rest_api.my_api.id
}

The above code exists in both lambda git repos. There are couple of issues that i had encountered. If i use the above setup, when one of the lambda is deleted then the stage gets removed. The removal causes the stage dev that affects the other lambda that was deployed to the stage dev.

Second issue is related to duplicate stage creation. See error below.

│ Error: creating API Gateway Stage (dev): operation error API Gateway: CreateStage, https response error StatusCode: 409, RequestID: 9826d9ef-39e6-4113-bc2c-1f1e9fc1de52, ConflictException: Stage already exists

Solution

  • Based on best practice, each repo will have its own stage.

    repo1 -> dev_stage_01
    repo2 -> dev_stage_02
    

    This avoids the deletion and recreation of the common single stage (eg:- dev) reference when any one of the repos are getting deployed to the common single stage(dev).

    While mapping these to Api Gateway Custom Domain, there will be multiple entries.

    API             Stage           Path
    api_gateway -> dev_stage_01 -> /
    api_gateway -> dev_stage_02 -> /