🎓 A1Learner
🔍
0 of 50 lessons completed

Dev, Staging and Prod

Dev, staging and prod are three copies of the same system at three levels of risk. One module and three variable files keep the copies identical except for the values that must differ.

One module, three calls

The same module builds the same shape in each environment. The inputs are the only difference.

module "app_dev" {
  source = "./modules/app"
  name   = "app-dev"
}

module "app_prod" {
  source = "./modules/app"
  name   = "app-prod"
}

Three variable files

Each environment gets its own small file of values. Nothing else changes.

# dev.tfvars
name = "app-dev"

# prod.tfvars
name = "app-prod"

Apply one environment

Pick the file for the environment you mean to change. The other environments stay untouched.

terraform apply -var-file="dev.tfvars"

Example

# modules/greeting/main.tf
variable "name" {
  type = string
}

resource "local_file" "greeting" {
  content  = "Hello from ${var.name}."
  filename = "${path.module}/${var.name}.txt"
}

output "message" {
  value = local_file.greeting.content
}

# main.tf
module "dev" {
  source = "./modules/greeting"
  name   = "dev"
}

module "staging" {
  source = "./modules/greeting"
  name   = "staging"
}

module "prod" {
  source = "./modules/greeting"
  name   = "prod"
}

output "messages" {
  value = [module.dev.message, module.staging.message, module.prod.message]
}

Key points

  • Dev is the safe place to try changes.
  • Staging is the copy that should match prod as closely as possible.
  • Prod is the live system that real users depend on.
  • Three separate copies of the same code drift apart over time.
  • One module called three times keeps the shape the same in every environment.
  • Only the variable values change between environments.

The module is written once and called three times, once per environment. Each call builds its own file, and the three variable files from the snippets above are the usual next step: move the names into dev.tfvars, staging.tfvars and prod.tfvars and pick one with -var-file.

Note

A variable file is chosen with the -var-file flag at apply time.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why use one module with three variable files instead of three copies of the code?