Managing Multiple Environments
7 min read
π Introduction
Welcome back, Terra-former! π
By now, youβve probably spun up an EC2 instance, maybe an S3 bucket, and felt that rush of power when terraform apply turns green. But here is a scary thought: What if you make a typo in your configuration and accidentally delete the production database used by actual paying customers? π±
In the software world, we have a golden rule: Never test in Production.
To solve this, we use Environments. You need a sandbox to break things (dev), a place to simulate production (stage), and the holy grail (prod).
Today, we will learn how to manage these environments in Terraform. We will look at the quick way (Workspaces) and the professional way (Directory Separation).
1. Workspaces: Managing Multiple Environments in a Single Directory
π§ Definition
A Terraform Workspace allows you to maintain multiple separate state files within the same configuration directory.
π The Problem
Imagine you have a main.tf defining a server. You deploy it. Now you want a second server for testing features, but you don't want to copy-paste the code into a new folder. If you just run terraform apply again with different variables, Terraform might try to update the existing server instead of creating a new one, because itβs looking at the same terraform.tfstate file.
π The Solution
Workspaces tell Terraform: "Hey, keep the state for Dev in this box, and the state for Prod in that box, but use the same code for both."
Under the hood, Terraform creates a hidden directory .terraform/environment/ to store these alternative state files.
π» Hands-On: Using Workspaces
By default, you are always in the default workspace. Let's see how to switch.
Step 1: List Workspaces
terraform workspace listOutput:
* defaultStep 2: Create a New Workspace
Let's create a dev environment.
terraform workspace new devOutput:
Created and switched to workspace "dev"!Step 3: Use the Workspace in Code
Terraform provides a variable called terraform.workspace that you can use in your HCL code.
resource "aws_s3_bucket" "my_bucket" {
# This creates "app-bucket-dev" or "app-bucket-prod" automatically
bucket = "app-bucket-${terraform.workspace}"
}Step 4: Switch Workspaces
To go back to default or switch to production:
terraform workspace select defaultβοΈ Industry Reality Check
Should you use Workspaces?
- Yes: For quick feature branches (e.g.,
feature-login-page) where you want to test code without impacting the main dev environment. - No: For
DevvsProd. - Why? Workspaces share the same backend configuration and the same plugin versions. It is very easy to forget which workspace you are in and accidentally run
terraform destroyon Prod when you thought you were in Dev. Visual separation is safety.
2. Directory Separation: The Enterprise Way to Structure Environments
π§ Definition
Directory Separation involves creating physical folders for each environment (dev/, prod/), where each folder contains its own set of Terraform configuration files.
π The Problem
With Workspaces, a single main.tf controls everything. If you edit main.tf to test a crazy new feature for Dev, you have technically modified the code that Prod relies on. If you make a syntax error, both environments are effectively broken until you fix it.
π The Solution
We separate the environments completely. However, we don't want to duplicate code (violating the DRY - Don't Repeat Yourself principle). To fix this, we use Terraform Modules.
- Modules store the reusable logic (the blueprints).
- Environment Directories call those modules with specific parameters.
π» Hands-On: The Folder Structure
This is the standard pattern you will see in 90% of serious DevOps setups.
my-project/
βββ modules/ # The Blueprints
β βββ web-server/
β βββ main.tf
β βββ variables.tf
β βββ outputs.tf
βββ environments/ # The Actual Deployments
β βββ dev/
β β βββ main.tf # Calls the module with Dev settings
β β βββ outputs.tf
β β βββ backend.tf # State storage for Dev
β βββ prod/
β βββ main.tf # Calls the module with Prod settings
β βββ outputs.tf
β βββ backend.tf # State storage for ProdThe Code Implementation
1. The Module (modules/web-server/main.tf):
variable "instance_size" {}
variable "env_name" {}
resource "aws_instance" "app" {
ami = "ami-12345678"
instance_type = var.instance_size
tags = {
Name = "web-server-${var.env_name}"
}
}2. The Dev Environment (environments/dev/main.tf):
module "web_server" {
source = "../../modules/web-server"
instance_size = "t2.micro" # Cheap for testing!
env_name = "dev"
}3. The Prod Environment (environments/prod/main.tf):
module "web_server" {
source = "../../modules/web-server"
instance_size = "m5.large" # Powerful for users!
env_name = "prod"
}π§ Why is this better?
- Isolation: You can mess up the
devfolder completely, and theprodfolder remains untouched. - Clarity: It is obvious which environment you are deploying to based on the folder you are in.
- Versioning: You can point Dev to version 1.0 of a module and Prod to version 0.9 until you are ready to upgrade.
Funny Fact: In the early days, people used to copy-paste the entire code folder and rename it
prod_final_v2_real. We have evolved. Please don't do that.
3. Using .tfvars Files for Environment-Specific Configurations
π§ Definition
A .tfvars file is a file containing key-value pairs that set values for your input variables. Think of it as a "settings file" or a "config file."
π The Problem
In the Directory Separation method above, we hardcoded "t2.micro" inside main.tf. If we want to change that, we have to edit the code. It's better to keep configuration separate from logic.
π The Solution
We strip the values out of main.tf and put them into files like dev.tfvars and prod.tfvars.
π» Hands-On: Implementation
Let's refactor our single directory approach (or the module call) to use variables.
1. Define Variables (variables.tf):
variable "instance_count" {
type = number
}
variable "enable_logging" {
type = bool
}2. Create Config Files:
File: dev.tfvars
instance_count = 1
enable_logging = falseFile: prod.tfvars
instance_count = 5
enable_logging = true3. Applying the Configuration:
When you run Terraform, you explicitly tell it which file to read.
For Dev:
terraform apply -var-file="dev.tfvars"For Prod:
terraform apply -var-file="prod.tfvars"π‘ Pro Tip: terraform.tfvars
If you name a file exactly terraform.tfvars, Terraform loads it automatically. This is great for "defaults," but for multiple environments, using specific names (like prod.tfvars) and passing the -var-file flag is safer to avoid ambiguity.
4. Best Practices for Environment Isolation and State Separation
You now know the mechanics. Now let's talk about safety.
π 1. Remote State is Mandatory
Never store terraform.tfstate on your laptop for team projects. Use a remote backend.
- Why? If your laptop breaks, the state is lost. If your colleague runs apply, they overwrite your changes.
- Standard: AWS S3 for storage + DynamoDB for locking.
Example backend.tf:
terraform {
backend "s3" {
bucket = "my-company-terraform-states"
key = "dev/app.tfstate" # CHANGE THIS per environment
region = "us-east-1"
dynamodb_table = "terraform-locks"
}
}Note the key. In Dev, it is dev/app.tfstate. In Prod, it must be prod/app.tfstate.
π‘ 2. State Locking
Imagine you start a deployment to Prod. Two seconds later, your coworker also starts a deployment to Prod.
Without locking, Terraform might corrupt the state file.
DynamoDB (in the config above) acts as a traffic light. If you are deploying, it writes a "Lock" ID. Your coworker's Terraform will say:
Error acquiring the state lock: ConditionalCheckFailedException.
𧨠3. Limit the Blast Radius
This is a fancy DevOps term. It means: "If this explodes, how much stuff breaks?"
- Bad: One giant
main.tffor the whole company. If it fails, the whole company stops. - Good: Separate states for Networking (VPC), Database, and App.
- If the App deployment fails, the Database is still running fine.
- This is done by having separate folders/states for layers, not just environments.
π€ 4. CI/CD Integration
Humans are bad at remembering flags. We forget to add -var-file="prod.tfvars".
- Practice: Use a pipeline (GitHub Actions, GitLab CI, Jenkins).
- Script:
terraform apply -var-file="${BRANCH_NAME}.tfvars"
This ensures that themainbranch always deploys to Prod, anddevelopbranch always deploys to Dev.
π Summary Checklist
- Small Projects / Rapid Prototyping: Use Workspaces.
- Enterprise / Long-term Projects: Use Directory Separation + Modules.
- Configuration: Use .tfvars files to keep logic and data separate.
- Safety: Always use Remote Backend with State Locking.
Now go forth and build your environments! Just remember: If you delete Production, delete your browser history and run. (Just kidding. That's what version control is for!) ππ¨
π References & Further Reading
Challenge
Challenge: Refactor to a Modular, Multi-Environment Configuration
You have been tasked with refactoring a monolithic Terraform configuration. The current setup dangerously manages both dev and prod environments from a single set of files, increasing the risk of accidental production changes.
Your goal is to implement the industry-standard Directory Separation pattern using Modules, Remote Backends, and .tfvars files.
Instructions:
Create a Reusable Module: In the virtual path
modules/web_server/, define a reusable module that creates anaws_instanceand anaws_s3_bucket.- The module should accept the following input variables:
instance_type,ami_id,bucket_prefix, andenv_name. - The
aws_instanceresource should be tagged with aNamethat includes theenv_namevariable (e.g.,web-server-prod). - The
aws_s3_bucketname should be unique and incorporate thebucket_prefixandenv_namevariables.
- The module should accept the following input variables:
Configure
devEnvironment: Create the configuration for thedevenvironment in the virtual pathenvironments/dev/.- Backend: Define a remote backend using AWS S3. The state file key must be
environments/dev/terraform.tfstate. Configure state locking using a DynamoDB table namedterraform-state-lock-db. - Module Call: Call the
web_servermodule you created. The module source should be../../modules/web_server. - Variables: Pass values to the module using a virtual
dev.tfvarsfile. Uset2.microfor the instance type andmyapp-dev-datafor the bucket prefix.
- Backend: Define a remote backend using AWS S3. The state file key must be
Configure
prodEnvironment: Create the configuration for theprodenvironment in the virtual pathenvironments/prod/.- Backend: Define a remote backend using AWS S3, similar to
dev. The state file key must beenvironments/prod/terraform.tfstate. Use the same DynamoDB table for state locking. - Module Call: Call the
web_servermodule. The module source should be../../modules/web_server. - Variables: Pass values to the module using a virtual
prod.tfvarsfile. Uset4g.smallfor the instance type andmyapp-prod-datafor the bucket prefix.
- Backend: Define a remote backend using AWS S3, similar to
Note: Write all your code in the single editor below, using the commented file paths to delineate your code sections.
Expected result
Your solution should be a single block of HCL code, organized into sections using comments that simulate a proper directory structure.
Here is a breakdown of the expected contents for each virtual file:
modules/web_server/variables.tf
variable "instance_type" { type = string }
variable "ami_id" { type = string }
variable "bucket_prefix" { type = string }
variable "env_name" { type = string }modules/web_server/main.tf
This file should contain resource blocks for aws_instance and aws_s3_bucket that reference the variables defined above. For example:
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = var.instance_type
tags = {
Name = "web-server-${var.env_name}"
}
}
resource "aws_s3_bucket" "data" {
bucket = "${var.bucket_prefix}-${var.env_name}"
}environments/dev/backend.tf & environments/prod/backend.tf
Each file should contain a terraform block defining the remote state backend. The key must be different for each environment.
# For dev
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "environments/dev/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-state-lock-db"
}
}
# A similar block for prod with key = "environments/prod/terraform.tfstate"environments/dev/main.tf & environments/prod/main.tf
Each file should contain a module block that calls the web_server module and provides the appropriate environment-specific values.
# For dev
module "app_server" {
source = "../../modules/web_server"
instance_type = "t2.micro"
ami_id = "ami-0c55b159cbfafe1f0"
bucket_prefix = "myapp-dev-data"
env_name = "dev"
}
# A similar block for prod with its specific values (e.g., "t4g.small")