Managing API Gateway Deployments with Terraform: Achieving Full Stage Isolation
API Gateway allows you to assocate deployments with stages, each stage representing a logical reference of your api. For example, my gardentour API project needs a
dev and a
prod stage to represent my environments.
I manage infrastructure with terraform, and I needed to achieve full isolation of my stages. It would be impracticable to manage deploys of many API Gateway stages with a single Terraform environment like so:
terraform/ ├─ main.tf ├─ modules/ │ ├─ api-gateway/ │ │ ├─ main.tf │ │ ├─ variables.tf │ │ ├─ outputs.tf │ ├─ api-gateway-stage/ │ │ ├─ main.tf │ │ ├─ variables.tf │ │ ├─ outputs.tf
main.tf for terraform used a single
api-gateway and multiple
api-gateway-stages, I would be locked to single deployment for all of my stages. My
dev stage would not be independent of my
By creating separate Terraform environments for each stage, you can more easily manage and isolate changes to your API Gateway deployments. Your
dev environment be worked on independently of your
test environment, or your
prod environmnet. Terraform environments can be isolated by placing environment specific infrastructure into its own directory.
This approach had a major benefit of knowing which environment was being worked on, and limited myself from messing up my entire project with an accidental deploy.
terraform/ ├─ global/ │ ├─ api-gateway/ │ │ ├─ main.tf ├─ dev/ │ ├─ main.tf ├─ prod/ │ ├─ main.tf ├─ modules/ │ ├─ api-gateway/ │ │ ├─ main.tf │ │ ├─ variables.tf │ │ ├─ outputs.tf │ ├─ api-gateway-stage/ │ │ ├─ main.tf │ │ ├─ variables.tf
There are three environments and one modules directory:
globalrefers to infrastructure that is available across all environments. These can include my IAM roles, Route53 domains and hosted zones, or a global API Gateway instance.
devwould reference the global API Gateway instance as a
datasource. This environment would add a
devstage to the API Gateway.
prodwould also reference the global API Gateway instance as a
datasource, and add a
prodstage to it.
modulesare terraform modules that encapsulate the volatility of some piece of infrastructure. These modules are used across all environments.
This directory structure keeps the lifecycle of my API Gateway stages independent, while using a single API Gateway instance.