Multiple Environments with Terraform
In this article we'll go over how to set up multiple environments, such as development and production, in Terraform without duplicating any files.
Overview
The goal of this is to have way to configure to distinct environments using the same files.
This is done by using the configurable backends feature of Terraform.
In a nutshell, we set up a normal providers.tf
file with a backend
block.
However, we remove the normal key
or path
parameter from the backend
move that into a separate files,
which are then loaded on terraform init
.
The full example can be seen this repo.
Setup
We start with providers.tf
:
terraform {
backend "s3" {
bucket = "s3-bucket-name"
region = "us-east-1"
dynamodb_table = "dynamodb-table-name"
}
}
provider "aws" {
region = "us-east-1"
}
While AWS is assumed, this will work with any provider.
Nothing special is required in the backend
configuration apart from the missing key
parameter.
For the local
backend, the missing parameter would be path
and so on.
We then specify two files, first env/dev-backend.tfvars
:
key = "dev.tfstate"
and env/prod-backend.tfvars
:
key = "prod.tfstate"
These tell Terraform that we'd like to use different key
parameters for each environment.
Theoretically, any backend
parameter can be configured this way, so if you wanted to use a different profile,
S3 bucket, region, or anything else for managing the state file per environment, you can do that.
To switch between each environment, we use this command:
terraform init -backend-config=env/dev-backend.tfvars -reconfigure
Any Terraform commands executed after the init will take place in that environment.
That's all there is to it. Always double-check what environment you're about to deploy to!
Resources
- Terraform Backends
- Backend Configuration
- Future article rewrite: Terraform workspaces