When building cloud infrastructure using Terraform, your directory structure matters more than you think.
A well-structured Terraform layout helps you:
- Scale easily across environments
- Reuse code with modules
- Avoid production mistakes
- Automate safely with scripts
In this post, Iβll show you the best practices I follow for organizing Terraform projects used in Dev, Stage, and Prod.
π 1. Environment Separation: Dev, Stage, Prod
Organize each environment in its own folder:
terraform/
βββ dev/
β βββ main.tf
β βββ variables.tf
β βββ outputs.tf
βββ stage/
β βββ ...
βββ prod/
β βββ ...
βββ env/
βββ dev.tfvars
βββ stage.tfvars
βββ prod.tfvars
β Pro tip: Keep
.tfvars
values in a separateenv/
directory for cleaner management.
Why it matters:
- Prevents accidental changes to production
- Clear separation of responsibilities
- Easier CI/CD integration
π¦ 2. Reuse Code with Modules
Instead of copying and pasting the same code, create reusable modules:
modules/
βββ vpc/
β βββ main.tf
β βββ variables.tf
β βββ outputs.tf
βββ ec2/
β βββ ...
Usage example:
module "vpc" {
source = "../../modules/vpc"
cidr_block = var.vpc_cidr
}
Benefits:
π‘ Define once, use everywhere
π Ensures consistency across environments
π§© Simplifies testing and debugging
π€ 3. Automate with Scripts
Use shell scripts to handle Terraform operations like init
, apply
, and destroy
.
scripts/
βββ init.sh # terraform init
βββ plan.sh # terraform plan
βββ apply.sh # terraform apply
βββ teardown.sh # terraform destroy
Why script it?
β±οΈ Saves time
π Reduces manual error
βοΈ Fits into CI/CD pipelines seamlessly
π§ 4. Core Terraform Files
Each environment/module folder typically contains:
-
main.tf
: Infrastructure definitions -
variables.tf
: Variable declarations -
outputs.tf
: Exposed outputs -
terraform.tfvars
: Variable values (optional if usingenv/*.tfvars
) -
provider.tf
: Cloud provider setup -
backend.tf
: Remote state configuration
π‘οΈ Store state remotely (e.g., S3 + DynamoDB) for security and team collaboration.
πΌοΈ Visual: Terraform Directory Structure
Infographic: High-level layout of a scalable Terraform project
β Summary: Why This Structure Works
β
Modular and reusable
β
Safer deployments
β
DevOps- and CI/CD-friendly
β
Environment-ready (Dev, Stage, Prod)
π¬ Whatβs your Terraform setup look like?
Do you structure things differently?
Have tips for managing multiple environments or state files?
Letβs share ideas in the comments π¬π
#Terraform #DevOps #InfrastructureAsCode #AWS #GCP #Azure #CloudEngineering #SRE #CI/CD #IaC
Top comments (0)