Terraform Tutorial — Project 5: Multi-Environment
Deploy the same infrastructure to dev and prod using Terraform workspaces and environment-specific .tfvars files.
What You’ll Build
- Workspace-based multi-environment deployment
- Environment-specific sizing (instance types, counts)
- Shared modules with different parameters per environment
- Workspace-aware resource naming
Project Structure
project-5-multi-env/
├── main.tf
├── variables.tf
├── outputs.tf
├── environments/
│ ├── dev.tfvars
│ └── prod.tfvars
└── modules/
└── vpc/
environments/dev.tfvars
instance_type = "t3.micro"
instance_count = 1
vpc_cidr = "10.0.0.0/16"
enable_nat = false
environments/prod.tfvars
instance_type = "t3.large"
instance_count = 3
vpc_cidr = "10.1.0.0/16"
enable_nat = true
main.tf
provider "aws" {
region = var.region
}
module "vpc" {
source = "./modules/vpc"
name = "app-${terraform.workspace}"
cidr_block = var.vpc_cidr
enable_nat_gateway = var.enable_nat
tags = {
Environment = terraform.workspace
}
}
resource "aws_instance" "web" {
count = var.instance_count
ami = data.aws_ami.amazon_linux.id
instance_type = var.instance_type
subnet_id = module.vpc.public_subnet_ids[count.index % length(module.vpc.public_subnet_ids)]
tags = {
Name = "web-${terraform.workspace}-${count.index + 1}"
Environment = terraform.workspace
}
}
Deployment Workflow
# Create workspaces
$ terraform workspace new dev
$ terraform workspace new prod
# Deploy dev
$ terraform workspace select dev
$ terraform apply -var-file="environments/dev.tfvars"
# Deploy prod
$ terraform workspace select prod
$ terraform apply -var-file="environments/prod.tfvars"
# Verify
$ terraform workspace select dev
$ terraform output
$ terraform workspace select prod
$ terraform output
Clean Up
$ terraform workspace select dev
$ terraform destroy -var-file="environments/dev.tfvars"
$ terraform workspace select prod
$ terraform destroy -var-file="environments/prod.tfvars"