Managing Multiple Environments

Run dev, staging and prod from one Terraform codebase: workspaces and their limits, directory-per-environment layouts, per-environment backends and tfvars, and versioned promotion.

By The Dark DebuggerUpdated 24 min read

Almost every real Terraform codebase deploys the same infrastructure more than once: dev, staging, production, sometimes a performance-test copy. This tutorial compares the two ways to do that, CLI workspaces and one directory per environment, runs both, and then builds the pieces a team actually needs: per-environment variables and backends, promotion of module versions from dev to prod with git tags, and naming and tagging conventions. It assumes you know modules and state and backends.

Why environments need separate state

Picture a checkout service with one Terraform configuration and one state file covering dev, staging and prod. Every plan touches all three. A change you meant to try in dev shows up in the prod plan too, and the only thing between you and an untested production change is someone reading a long plan carefully. A broken provider upgrade blocks every environment at once. And anyone allowed to plan dev can read prod's secrets, because they're in the same state file.

The fix is one state per environment, and the same code (or deliberately different versions of the same code) feeding each one. Terraform gives you two mechanisms for the first part.

Workspaces: one configuration, several states

A workspace is a named state inside one backend. Every configuration starts in a workspace called default, and terraform.workspace holds the current name, so the configuration can adapt to it:

terraform {
  required_version = ">= 1.5"
 
  required_providers {
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
}
 
locals {
  environment = terraform.workspace
 
  settings = {
    default = { replicas = 1, log_level = "debug" }
    staging = { replicas = 2, log_level = "info" }
    prod    = { replicas = 4, log_level = "warn" }
  }
 
  config = local.settings[local.environment]
}
 
resource "local_file" "app_config" {
  filename = "${path.module}/rendered/${local.environment}/checkout.json"
  content = jsonencode({
    service     = "checkout"
    environment = local.environment
    replicas    = local.config.replicas
    log_level   = local.config.log_level
  })
}
 
output "config_file" {
  value = local_file.app_config.filename
}

The rendered JSON file stands in for whatever differs per environment in real life: instance counts, sizes, log levels. Initialize, then apply in the default workspace:

terraform init
terraform workspace show
terraform apply -auto-approve
default
[…]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
config_file = "./rendered/default/checkout.json"

Create a staging workspace. workspace new also switches to it:

terraform workspace new staging
Created and switched to workspace "staging"!
 
You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.
terraform apply -auto-approve
[…]
Plan: 1 to add, 0 to change, 0 to destroy.
[…]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
config_file = "./rendered/staging/checkout.json"

1 to add, even though local_file.app_config already exists in the default workspace: the staging state starts empty. Do the same for prod, then look at what's on disk:

terraform workspace new prod
terraform apply -auto-approve
terraform workspace list
[…]
config_file = "./rendered/prod/checkout.json"
  default
* prod
  staging
tree -a -I '.terraform|.terraform.lock.hcl' .
.
├── main.tf
├── rendered
│   ├── default
│   │   └── checkout.json
│   ├── prod
│   │   └── checkout.json
│   └── staging
│       └── checkout.json
├── terraform.tfstate
└── terraform.tfstate.d
    ├── prod
    │   └── terraform.tfstate
    └── staging
        └── terraform.tfstate

The local backend keeps default in terraform.tfstate and every other workspace under terraform.tfstate.d/NAME/. The S3 backend does the equivalent with key prefixes: the default workspace uses your key, and others go under env:/NAME/ followed by the key. Same resource address, three separate states:

for ws in default staging prod; do
  terraform workspace select $ws > /dev/null
  echo "$ws: $(terraform state list) -> $(terraform output -raw config_file)"
done
default: local_file.app_config -> ./rendered/default/checkout.json
staging: local_file.app_config -> ./rendered/staging/checkout.json
prod: local_file.app_config -> ./rendered/prod/checkout.json
jq . rendered/prod/checkout.json
{
  "environment": "prod",
  "log_level": "warn",
  "replicas": 4,
  "service": "checkout"
}

The TF_WORKSPACE environment variable overrides the selected workspace for one command, which is how CI jobs usually pick one:

terraform workspace select staging
TF_WORKSPACE=prod terraform output -raw config_file; echo
terraform workspace show
Switched to workspace "staging".
./rendered/prod/checkout.json
staging
CommandWhat it does
terraform workspace showPrint the current workspace
terraform workspace listList workspaces; * marks the current one
terraform workspace new NAMECreate a workspace and switch to it
terraform workspace select NAMESwitch (add -or-create to create if missing)
terraform workspace delete NAMEDelete an empty, non-current workspace
TF_WORKSPACE=NAMESelect a workspace for one command or one CI job

When workspaces are the wrong tool

Workspaces are convenient, and for production environments I don't use them. The reasons are structural:

  • One backend, one set of credentials. Every workspace lives in the same backend. If prod is a separate AWS account (it should be), its state belongs in a bucket that dev credentials can't read. Workspaces can't express that.
  • Nothing in the code says which environment you're in. The difference between planning staging and planning prod is invisible state in .terraform/environment. A forgotten workspace select applies dev changes to prod.
  • Every environment runs the same code. You can't try a module upgrade in dev while prod stays on the old version. Everything changes everywhere on the next apply.
  • Differences hide in lookup tables. The settings map above is fine with three values. With thirty, terraform.workspace conditionals spread through the configuration and become hard to review.

HashiCorp's own documentation makes the same point: CLI workspaces aren't meant for deployments that need separate credentials and access controls.

Where workspaces shine is short-lived copies of the same environment: a stack per feature branch for integration tests, or a personal sandbox per engineer in a dev account. They're cheap to create, and terraform workspace delete cleans up the bookkeeping when you're done (after terraform destroy).

One directory per environment

The layout most teams settle on: a directory per environment, each a small root module that calls shared modules with that environment's values.

.
├── envs
│   ├── dev
│   │   ├── backend.tfbackend
│   │   ├── main.tf
│   │   └── terraform.tfvars
│   ├── prod
│   │   ├── backend.tfbackend
│   │   ├── main.tf
│   │   └── terraform.tfvars
│   └── staging
│       ├── backend.tfbackend
│       ├── main.tf
│       └── terraform.tfvars
└── modules
    └── web-service
        ├── main.tf
        ├── outputs.tf
        ├── variables.tf
        └── versions.tf

You always know which environment you're touching, because you cd into it. Each environment gets its own state, its own backend and its own credentials, and differences between environments are visible in files you can diff.

The shared module

web-service stands in for a real service deployment. Its main.tf builds the standard name and tags, which we'll come back to in the naming section:

locals {
  # acme-prod-checkout: project, environment, service, always in that order.
  name = "${var.project}-${var.environment}-${var.service}"
 
  tags = merge(
    {
      Project     = var.project
      Environment = var.environment
      Service     = var.service
      ManagedBy   = "terraform"
    },
    var.extra_tags,
  )
}
 
# Stands in for the real deployment (an ECS service, a Kubernetes
# Deployment): the rendered file is what would be submitted.
resource "local_file" "deployment" {
  filename = "${var.output_dir}/${local.name}.json"
  content = jsonencode({
    name      = local.name
    replicas  = var.replicas
    log_level = var.log_level
    tags      = local.tags
  })
}

Its variables.tf declares project, service, replicas, log_level, extra_tags and output_dir the way the modules tutorial describes, and validates the environment name, so a typo can't create a fourth environment by accident:

variable "environment" {
  description = "Deployment environment."
  type        = string
 
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be one of: dev, staging, prod."
  }
}

Its outputs are name, tags and deployment_file.

The environment root modules

main.tf is identical in all three environment directories. Everything that differs lives next to it in two small files:

terraform {
  required_version = ">= 1.5"
 
  required_providers {
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
 
  # Partial configuration: the path comes from -backend-config at init time.
  backend "local" {}
}
 
variable "environment" {
  type = string
}
 
variable "replicas" {
  type = number
}
 
variable "log_level" {
  type = string
}
 
variable "extra_tags" {
  type    = map(string)
  default = {}
}
 
module "checkout" {
  source = "../../modules/web-service"
 
  project     = "acme"
  environment = var.environment
  service     = "checkout"
  replicas    = var.replicas
  log_level   = var.log_level
  extra_tags  = var.extra_tags
  output_dir  = "${path.root}/rendered"
}
 
output "name" {
  value = module.checkout.name
}
 
output "tags" {
  value = module.checkout.tags
}

Terraform loads terraform.tfvars from the working directory automatically, so each environment's values sit right there. envs/dev/terraform.tfvars:

environment = "dev"
replicas    = 1
log_level   = "debug"

envs/staging/terraform.tfvars:

environment = "staging"
replicas    = 2
log_level   = "info"

envs/prod/terraform.tfvars:

environment = "prod"
replicas    = 4
log_level   = "warn"
 
extra_tags = {
  CostCenter = "cc-1042"
  OnCall     = "payments-oncall"
}

A reviewer can now answer "how is prod different from staging?" with diff envs/staging/terraform.tfvars envs/prod/terraform.tfvars.

Per-environment backends with -backend-config

The backend "local" {} block is deliberately empty. That's a partial configuration: the missing arguments come from terraform init -backend-config, either as key=value pairs or as a file. Each environment has a backend.tfbackend file. In this lab a local tfstate/ directory stands in for the state bucket:

cat envs/prod/backend.tfbackend
path = "../../../tfstate/prod/checkout.tfstate"
cd envs/dev
terraform init -backend-config=backend.tfbackend
Initializing the backend...
 
Successfully configured the backend "local"! Terraform will automatically
use this backend unless the backend configuration changes.
 
Initializing modules...
- checkout in ../../modules/web-service
[…]
terraform apply -auto-approve
[…]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
name = "acme-dev-checkout"
tags = {
  "Environment" = "dev"
  "ManagedBy" = "terraform"
  "Project" = "acme"
  "Service" = "checkout"
}

After the same init and apply in staging and prod:

cd ../prod
terraform output
name = "acme-prod-checkout"
tags = {
  "CostCenter" = "cc-1042"
  "Environment" = "prod"
  "ManagedBy" = "terraform"
  "OnCall" = "payments-oncall"
  "Project" = "acme"
  "Service" = "checkout"
}
tree ../../../tfstate
../../../tfstate
├── dev
│   └── checkout.tfstate
├── prod
│   └── checkout.tfstate
└── staging
    └── checkout.tfstate

What it looks like on AWS

With S3, the block in main.tf becomes backend "s3" {} and each environment's file names its own bucket. My recommendation is a separate bucket in each environment's own AWS account, so dev credentials can't even read prod's state:

bucket       = "acme-tfstate-prod"
key          = "checkout/terraform.tfstate"
region       = "eu-west-1"
use_lockfile = true

I can't run S3 without an AWS account, but two checks work offline. Without any -backend-config (and with -input=false, as in CI), init lists exactly what's missing:

terraform init -input=false
Initializing the backend...
 
 
Error: Missing Required Value
 
  on main.tf line 2, in terraform:
   2:   backend "s3" {}
 
The attribute "bucket" is required by the backend.
[…]
Error: Missing Required Value
[…]
The attribute "key" is required by the backend.
[…]
Error: Missing region value
[…]
The "region" attribute or the "AWS_REGION" or "AWS_DEFAULT_REGION"
environment variables must be set.

With the file above saved as prod.s3.tfbackend and dummy credentials, init accepted the configuration and stopped at the AWS credential check, which is as far as you can get without an account:

terraform init -input=false -backend-config=prod.s3.tfbackend
Initializing the backend...
Error: validating provider credentials: retrieving caller identity from STS: operation error STS: GetCallerIdentity, https response error StatusCode: 403, RequestID: 425ecfa1-64eb-44f8-bbe0-eefff810269d, api error InvalidClientTokenId: The security token included in the request is invalid.

The single-directory variant, and its trap

Some teams keep one root module and switch environments with flags: -backend-config=env/prod.tfbackend at init and -var-file=env/prod.tfvars at plan and apply. It works, but the backend is remembered between commands, so switching environments means re-initializing. After applying dev, this is what happens when you init for prod:

terraform init -backend-config=env/prod.tfbackend
Initializing the backend...
 
Initializing modules...
 
 
Error: Backend configuration changed
 
A change in the backend configuration has been detected, which may require
migrating existing state.
 
If you wish to attempt automatic migration of the state, run "terraform init
-migrate-state".
If you wish to store the current configuration with no changes to the state,
run "terraform init -reconfigure".

The right answer here is -reconfigure, which points the directory at prod's state without touching anything. The wrong answer, -migrate-state, offers to copy dev's state into prod's backend. Directory-per-environment avoids the question entirely, which is the main reason I prefer it.

Promoting changes: dev, then staging, then prod

With source = "../../modules/web-service", all three environments read the module from the same working copy. Change the module, and the next apply in any environment picks the change up, prod included. There's no way to say "this version is in dev but not prod yet".

The fix is to version the module. Move it into its own repository and tag releases, and each environment pins the tag it runs. In the lab, a bare repository served by git daemon on localhost stands in for GitHub or GitLab:

git add web-service
git commit -m "web-service: first release"
git tag v1.0.0
git push origin main --tags
git log --oneline --decorate
64d7425 (HEAD -> main, tag: v1.0.0, origin/main) web-service: first release

Each environment's main.tf now points at the tag. The double slash selects the web-service directory inside the repository:

module "checkout" {
  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.0.0"
  # ... inputs unchanged
}
terraform init
terraform plan
[…]
Initializing modules...
Downloading git::git://localhost/platform-modules.git?ref=v1.0.0 for checkout...
- checkout in .terraform/modules/checkout/web-service
[…]
No changes. Your infrastructure matches the configuration.

Switching the source from a local path to the tagged copy of the same code changes nothing, in all three environments. (In real life the URL would be git::https://... or git::ssh://...; the plain git:// protocol has no authentication and is only for this lab.)

Releasing v1.1.0

The platform team adds health-check settings to the module, a health_check_path variable defaulting to /healthz plus this change to the rendered deployment:

@@ -21,6 +21,10 @@ resource "local_file" "deployment" {
     name      = local.name
     replicas  = var.replicas
     log_level = var.log_level
-    tags      = local.tags
+    health_check = {
+      path     = var.health_check_path
+      interval = 15
+    }
+    tags = local.tags
   })
 }

They commit it, tag v1.1.0 and push:

3f9cbc9 (HEAD -> main, tag: v1.1.0, origin/main) web-service: add health check settings
64d7425 (tag: v1.0.0) web-service: first release

Nothing has changed in any environment yet. Promotion starts with dev: edit envs/dev/main.tf to say ?ref=v1.1.0. A plan right away fails, because a changed source must be downloaded first:

terraform plan
Error: Module source has changed
 
  on main.tf line 30, in module "checkout":
  30:   source = "git::git://localhost/platform-modules.git//web-service?ref=v1.1.0"
 
The source address was changed since this module was installed. Run
"terraform init" to install all modules required by this configuration.
terraform init
terraform plan
Initializing modules...
Downloading git::git://localhost/platform-modules.git?ref=v1.1.0 for checkout...
- checkout in .terraform/modules/checkout/web-service
[…]
Terraform will perform the following actions:
 
  # module.checkout.local_file.deployment must be replaced
-/+ resource "local_file" "deployment" {
      ~ content              = jsonencode(
          ~ {
              + health_check = {
                  + interval = 15
                  + path     = "/healthz"
                }
                name         = "acme-dev-checkout"
                tags         = {
                    Environment = "dev"
                    ManagedBy   = "terraform"
                    Project     = "acme"
                    Service     = "checkout"
                }
                # (2 unchanged attributes hidden)
            } # forces replacement
        )
      […]
    }
 
Plan: 1 to add, 0 to change, 1 to destroy.

Apply it in dev, let it soak, then make the same one-line change in staging. Prod stays on v1.0.0 until its own pull request:

cd ../prod
terraform plan | grep -E 'No changes|Plan:'
cd ..
grep -H 'ref=' */main.tf
No changes. Your infrastructure matches the configuration.
dev/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.1.0"
prod/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.0.0"
staging/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.1.0"

That grep is the whole release status of the platform, in version control. The promotion rules I'd hold a team to:

  • Promote the same artifact. Prod gets exactly the tag staging ran, never "the same change, re-applied by hand".
  • One pull request per environment bump, each with its own plan output attached for review.
  • Prod applies a saved plan, so what was reviewed is what runs. The Testing and CI tutorial builds that pipeline.

Naming and tagging conventions

Two habits pay for themselves the first time someone opens a cloud bill or a console with three hundred resources in it.

A fixed name pattern. The module builds every name as project-environment-service (acme-prod-checkout), computed once in a local and used everywhere. Never let callers pass a free-form name for things that exist in every environment, or you'll get checkout-prod, prod_checkout and checkoutProd within a quarter.

A standard tag set, merged with environment-specific extras, as the module's local.tags does. On AWS the provider can apply the common tags to every resource it creates with default_tags, so individual resources only add what's specific to them:

terraform {
  required_version = ">= 1.5"
 
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}
 
variable "environment" {
  type    = string
  default = "staging"
}
 
provider "aws" {
  region = "eu-west-1"
 
  # Applied to every taggable resource this provider creates.
  default_tags {
    tags = {
      Project     = "acme"
      Environment = var.environment
      ManagedBy   = "terraform"
      Repository  = "github.com/acme/platform"
    }
  }
}
 
resource "aws_s3_bucket" "assets" {
  bucket = "acme-${var.environment}-checkout-assets"
 
  tags = {
    Service = "checkout"
  }
}

I planned this with dummy credentials and the offline_override.tf file from the state tutorial. The resource's own tags hold one key, and tags_all shows what AWS will actually get:

      + bucket                      = "acme-staging-checkout-assets"
[…]
      + tags                        = {
          + "Service" = "checkout"
        }
      + tags_all                    = {
          + "Environment" = "staging"
          + "ManagedBy"   = "terraform"
          + "Project"     = "acme"
          + "Repository"  = "github.com/acme/platform"
          + "Service"     = "checkout"
        }
[…]
Plan: 1 to add, 0 to change, 0 to destroy.
TagExampleWhy
ProjectacmeGroups cost and ownership across services
EnvironmentprodCost split, access policies, "is this safe to delete?"
ServicecheckoutWhich team to page
ManagedByterraformWarns people off console edits
Repositorygithub.com/acme/platformWhere the code that owns it lives
CostCentercc-1042Finance's chargeback, usually prod only

Where you'll use this

The complete pattern from this tutorial is what a small platform team's repository looks like in practice:

  • modules/ (or a separate module repository with tags) holds the building blocks.
  • envs/dev, envs/staging, envs/prod are thin root modules with terraform.tfvars and backend.tfbackend, each pinned to a module version.
  • Each environment's state lives in that environment's account, initialized with terraform init -backend-config=backend.tfbackend.
  • CI runs plan for every environment directory a pull request touches. A merge applies dev automatically; staging and prod apply after an approval, from saved plans.
  • A release is a tag in the module repository plus three small pull requests that bump ?ref=.

Workspaces still earn a place next to this: a CI job that spins up a throwaway copy of dev for integration tests can run terraform workspace select -or-create pr-1234, apply, test, destroy and delete the workspace, all against the dev backend.

Common mistakes

A workspace the configuration doesn't know

terraform workspace new qa
terraform plan
Created and switched to workspace "qa"!
[…]
Error: Invalid index
 
  on main.tf line 18, in locals:
  18:   config = local.settings[local.environment]
    ├────────────────
    │ local.environment is "qa"
    │ local.settings is object with 3 attributes
 
The given key does not identify an element in this collection value.

Any workspace name can be created; the configuration has to cope. Failing like this is the good outcome. The bad one is a lookup() with a default that silently treats qa as production-sized.

Deleting a workspace that still owns resources

terraform workspace select default
terraform workspace delete prod
Error: Workspace is not empty
 
Workspace "prod" is currently tracking the following resource instances:
  - local_file.app_config
 
Deleting this workspace would cause Terraform to lose track of any associated
remote objects, which would then require you to delete them manually outside
of Terraform. You should destroy these objects with Terraform before deleting
the workspace.
[…]

(Trying it while prod is selected fails earlier: "You cannot delete the currently active workspace.") Run terraform destroy in the workspace first. -force deletes the state and leaves the real objects orphaned.

Running init without -backend-config

With a partial local backend, terraform init without the file doesn't fail. It quietly uses the default path:

terraform init
terraform state list
Initializing the backend...
 
Successfully configured the backend "local"! Terraform will automatically
use this backend unless the backend configuration changes.
[…]
No state file was found!
 
State management commands require a state file. Run this command
in a directory where Terraform has been run or use the -state flag
to point the command to a specific state location.

That was staging, which has a perfectly good state in tfstate/staging. A plan from here would propose creating everything again. The S3 backend fails loudly instead (the "Missing Required Value" errors above), which is one more reason to wrap init in a script or a Makefile target that always passes the right file.

Switching environments in one directory with -migrate-state

Covered above, but it's worth repeating because the prompt sounds helpful: in a single-directory setup, answering "Backend configuration changed" with -migrate-state copies one environment's state into another's backend. Use -reconfigure to switch.

Summary

  • Each environment needs its own state. Workspaces and directories-per-environment are the two ways to get it.
  • Workspaces give one configuration several states in one backend; the current name is terraform.workspace, and TF_WORKSPACE selects one per command.
  • Workspaces share a backend, credentials and code version, and hide which environment you're in. Use them for short-lived copies, not for prod isolation.
  • Directory-per-environment keeps a thin root module per environment calling shared modules, with terraform.tfvars for values and a partial backend plus -backend-config=FILE for state location.
  • Pin modules to versions (?ref= tags for git, version for registries) so a change can run in dev while prod stays on the previous release. Promote by bumping the pin one environment at a time.
  • Build names from a fixed pattern in one local, and merge a standard tag set (default_tags on AWS) with resource-specific tags.

Exercises

Exercise 1: Add a qa workspace properlyeasy

In the workspace-based checkout project, add a qa environment with one replica and log level info. Create the workspace, apply, and show where its state lives.

Show Solution

Add a line to the settings map:

    qa      = { replicas = 1, log_level = "info" }
terraform workspace new qa
terraform apply -auto-approve | grep -E 'Apply complete|config_file ='
ls terraform.tfstate.d
Created and switched to workspace "qa"!
  + config_file = "./rendered/qa/checkout.json"
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
config_file = "./rendered/qa/checkout.json"
prod
qa
staging

The configuration change has to come first; otherwise you get the "Invalid index" error from Common mistakes.

Exercise 2: Refuse to run in the default workspacemedium

In the same project, default isn't a real environment, but nothing stops someone from applying in it. Add a guard that fails the plan in default with a message telling the user what to do, and confirm the qa workspace still plans cleanly.

Hint

A precondition inside a resource's lifecycle block can test terraform.workspace.

Show Solution
resource "local_file" "app_config" {
  filename = "${path.module}/rendered/${local.environment}/checkout.json"
  content = jsonencode({
    service     = "checkout"
    environment = local.environment
    replicas    = local.config.replicas
    log_level   = local.config.log_level
  })
 
  lifecycle {
    precondition {
      condition     = terraform.workspace != "default"
      error_message = "The default workspace is not an environment. Run: terraform workspace select staging (or prod, qa)."
    }
  }
}
terraform workspace select default
terraform plan
Switched to workspace "default".
[…]
Error: Resource precondition failed
 
  on main.tf line 33, in resource "local_file" "app_config":
  33:       condition     = terraform.workspace != "default"
    ├────────────────
    │ terraform.workspace is "default"
 
The default workspace is not an environment. Run: terraform workspace select
staging (or prod, qa).
terraform workspace select qa
terraform plan | grep -E 'No changes|Plan:'
Switched to workspace "qa".
No changes. Your infrastructure matches the configuration.

A precondition is checked during plan, before anything changes, and its message is yours to write. That makes it the right place for "you're probably about to make a mistake" guards.

Exercise 3: Promote v1.1.0 to prodeasy

Staging has been running module v1.1.0 without problems. Promote it to prod and confirm the rendered prod deployment has the health check.

Show Solution

Change ?ref=v1.0.0 to ?ref=v1.1.0 in envs/prod/main.tf, then:

terraform init | grep Downloading
terraform plan | grep -E '^  # |Plan:'
terraform apply -auto-approve | grep 'Apply complete'
jq .health_check rendered/acme-prod-checkout.json
Downloading git::git://localhost/platform-modules.git?ref=v1.1.0 for checkout...
  # module.checkout.local_file.deployment must be replaced
Plan: 1 to add, 0 to change, 1 to destroy.
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
{
  "interval": 15,
  "path": "/healthz"
}

The prod plan should match staging's plan in shape (here: one replacement). If prod's plan shows something staging's didn't, stop and find out why before applying.

Exercise 4: Add a perf environmenthard

The performance team wants a perf environment with 8 replicas and log level info, with its own state. Create it from the staging directory. You'll find that the module rejects the name; fix that with a new module release without changing what dev, staging or prod run.

Show Solution

Create the directory, copying main.tf from staging:

mkdir envs/perf
cp envs/staging/main.tf envs/perf/main.tf
printf 'path = "../../../tfstate/perf/checkout.tfstate"\n' > envs/perf/backend.tfbackend

envs/perf/terraform.tfvars:

environment = "perf"
replicas    = 8
log_level   = "info"

With v1.1.0 the plan fails, and the error points into the downloaded module:

Error: Invalid value for variable
 
  on main.tf line 33, in module "checkout":
  33:   environment = var.environment
    ├────────────────
    │ var.environment is "perf"
 
environment must be one of: dev, staging, prod.
 
This was checked by the validation rule at
.terraform/modules/checkout/web-service/variables.tf:10,3-13.

Release a module version that allows it. In the module repository:

-    condition     = contains(["dev", "staging", "prod"], var.environment)
-    error_message = "environment must be one of: dev, staging, prod."
+    condition     = contains(["dev", "staging", "perf", "prod"], var.environment)
+    error_message = "environment must be one of: dev, staging, perf, prod."
git commit -am "web-service: allow the perf environment"
git tag v1.2.0
git push origin main --tags

Point only envs/perf/main.tf at ?ref=v1.2.0, then:

terraform init -backend-config=backend.tfbackend
terraform apply -auto-approve
[…]
Downloading git::git://localhost/platform-modules.git?ref=v1.2.0 for checkout...
[…]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
Outputs:
 
name = "acme-perf-checkout"
tags = {
  "Environment" = "perf"
  "ManagedBy" = "terraform"
  "Project" = "acme"
  "Service" = "checkout"
}
grep -H 'ref=' envs/*/main.tf
dev/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.1.0"
perf/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.2.0"
prod/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.1.0"
staging/main.tf:  source = "git::git://localhost/platform-modules.git//web-service?ref=v1.1.0"

perf runs v1.2.0; nothing else changed. The other environments pick up v1.2.0 through the normal promotion path when they next upgrade, and since the only change is an extra allowed value, their plans will show no changes.


Tested with: Terraform v1.17.1 on Ubuntu 24.04 (WSL2, linux_amd64), with hashicorp/local v2.9.1 and hashicorp/aws v6.72.0, git 2.43.0, November 2026. The workspace project and all four directory-per-environment root modules were applied for real, with a local directory standing in for the state bucket and a bare git repository served by git daemon on localhost standing in for the module host. Commands ran with -no-color; git push ran with -q, and in exercise 4 the grep ran from inside envs/. Nothing touched AWS: the S3 backend got as far as the credential check with dummy keys, and the default_tags example was planned (not applied) with dummy credentials.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Terraform tutorial here is tested end to end before publishing.