I don't like the idea of subfolders because this will result in different sources per environment and this tends to drift.
The better approach is to have a single stack for all environments (lets say dev, preprod and prod). To work on a single environment use terraform workspace
.
terraform workspace new dev
This creates a new workspace. This includs a dedicated state file and the variable terraform.workspace
you can use in your code.
resource "aws_s3_bucket" "bucket" {
bucket = "my-tf-test-bucket-${terraform.workspace}"
}
In this way you will get buckets called
- my-tf-test-bucket-dev
- my-tf-test-bucket-preprod
- my-tf-test-bucket-prod
after applying to the workspaces above (use terraform workspace select
to change environments).
To make the code even multi-region-proof do it like this:
data "aws_region" "current" {}
resource "aws_s3_bucket" "bucket" {
bucket = "my-tf-test-bucket-${data.aws_region.current.name}-${terraform.workspace}"
}
to get (for us-east-1 region)
- my-tf-test-bucket-us-east-1-dev
- my-tf-test-bucket-us-east-1-preprod
- my-tf-test-bucket-us-east-1-prod