Learn Terraform Β· 8/11

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

bash
terraform workspace list

Output:

text
* default

Step 2: Create a New Workspace

Let's create a dev environment.

bash
terraform workspace new dev

Output:

text
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.

hcl
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:

bash
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 Dev vs Prod.
  • 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 destroy on 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.

text
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 Prod

The Code Implementation

1. The Module (modules/web-server/main.tf):

hcl
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):

hcl
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):

hcl
module "web_server" {
  source        = "../../modules/web-server"
  instance_size = "m5.large"  # Powerful for users!
  env_name      = "prod"
}

🧠 Why is this better?

  1. Isolation: You can mess up the dev folder completely, and the prod folder remains untouched.
  2. Clarity: It is obvious which environment you are deploying to based on the folder you are in.
  3. 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):

hcl
variable "instance_count" {
  type = number
}

variable "enable_logging" {
  type = bool
}

2. Create Config Files:

File: dev.tfvars

hcl
instance_count = 1
enable_logging = false

File: prod.tfvars

hcl
instance_count = 5
enable_logging = true

3. Applying the Configuration:
When you run Terraform, you explicitly tell it which file to read.

For Dev:

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

For Prod:

bash
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:

hcl
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.tf for 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 the main branch always deploys to Prod, and develop branch always deploys to Dev.

πŸ“ Summary Checklist

  1. Small Projects / Rapid Prototyping: Use Workspaces.
  2. Enterprise / Long-term Projects: Use Directory Separation + Modules.
  3. Configuration: Use .tfvars files to keep logic and data separate.
  4. 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:

  1. Create a Reusable Module: In the virtual path modules/web_server/, define a reusable module that creates an aws_instance and an aws_s3_bucket.

    • The module should accept the following input variables: instance_type, ami_id, bucket_prefix, and env_name.
    • The aws_instance resource should be tagged with a Name that includes the env_name variable (e.g., web-server-prod).
    • The aws_s3_bucket name should be unique and incorporate the bucket_prefix and env_name variables.
  2. Configure dev Environment: Create the configuration for the dev environment in the virtual path environments/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 named terraform-state-lock-db.
    • Module Call: Call the web_server module you created. The module source should be ../../modules/web_server.
    • Variables: Pass values to the module using a virtual dev.tfvars file. Use t2.micro for the instance type and myapp-dev-data for the bucket prefix.
  3. Configure prod Environment: Create the configuration for the prod environment in the virtual path environments/prod/.

    • Backend: Define a remote backend using AWS S3, similar to dev. The state file key must be environments/prod/terraform.tfstate. Use the same DynamoDB table for state locking.
    • Module Call: Call the web_server module. The module source should be ../../modules/web_server.
    • Variables: Pass values to the module using a virtual prod.tfvars file. Use t4g.small for the instance type and myapp-prod-data for the bucket prefix.

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

hcl
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:

hcl
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.

hcl
# 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.

hcl
# 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")
hcl

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.