Why Terraform?
Terraform enables declarative infrastructure management across multiple cloud providers. It provides consistency, repeatability, and collaboration through Infrastructure as Code.
Project Structure
infrastructure/
โโโ modules/
โ โโโ networking/
โ โ โโโ main.tf
โ โ โโโ variables.tf
โ โ โโโ outputs.tf
โ โโโ compute/
โ โโโ database/
โโโ environments/
โ โโโ dev/
โ โ โโโ main.tf
โ โ โโโ terraform.tfvars
โ โ โโโ backend.tf
โ โโโ staging/
โ โโโ prod/
โโโ global/
โโโ iam/State Management
Remote State
Always use remote state for team collaboration:
terraform {
backend "s3" {
bucket = "company-terraform-state"
key = "prod/networking/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}State Locking
Use DynamoDB (AWS) or Azure Blob leases to prevent concurrent modifications.
State Isolation
Separate state files by environment and component:
states/
โโโ prod/networking/terraform.tfstate
โโโ prod/compute/terraform.tfstate
โโโ staging/networking/terraform.tfstate
โโโ staging/compute/terraform.tfstateModule Best Practices
Module Design
// modules/networking/variables.tf
variable "vpc_cidr" {
description = "CIDR block for VPC"
type = string
validation {
condition = can(cidrhost(var.vpc_cidr, 0))
error_message = "Must be a valid CIDR block."
}
}
variable "environment" {
description = "Environment name"
type = string
}
variable "tags" {
description = "Tags to apply to resources"
type = map(string)
default = {}
}Module Versioning
module "networking" {
source = "git::https://github.com/company/terraform-modules.git//networking?ref=v1.2.0"
vpc_cidr = "10.0.0.0/16"
environment = "prod"
}Code Quality
Formatting and Validation
# Format code
terraform fmt -recursive
# Validate configuration
terraform validate
# Security scanning
tfsec .
# Cost estimation
infracost breakdown --path .Pre-commit Hooks
# .pre-commit-config.yaml
repos:
- repo: https://github.com/antonbabenko/pre-commit-terraform
hooks:
- id: terraform_fmt
- id: terraform_validate
- id: terraform_tfsecCI/CD Pipeline
# GitHub Actions example
jobs:
terraform:
steps:
- uses: hashicorp/setup-terraform@v2
- run: terraform init
- run: terraform fmt -check
- run: terraform validate
- run: terraform plan -out=tfplan
- run: terraform apply tfplan # Only on main branchSecrets Management
- Never commit secrets to version control
- Use environment variables or secret managers
- Reference secrets from Vault or AWS Secrets Manager
Conclusion
Following these best practices ensures your Terraform codebase remains maintainable, secure, and collaborative as your infrastructure grows.