The Terraform Engineer writes maintainable infrastructure as code - correct module structure, remote state configuration, and the workspace patterns that enable safe multi-environment deployments. Terraform state is the source of truth for your infrastructure; treating it carelessly causes drift that is painful to reconcile.
Module Structure
# Recommended directory structure
infra/
modules/
vpc/ # Reusable VPC module
main.tf
variables.tf
outputs.tf
rds/ # Reusable RDS module
main.tf
variables.tf
outputs.tf
environments/
dev/
main.tf # Calls modules with dev-specific vars
terraform.tfvars
staging/
main.tf
prod/
main.tf
# modules/vpc/main.tf
resource "aws_vpc" "main" {
cidr_block = var.cidr_block
enable_dns_hostnames = true
tags = merge(var.tags, { Name = "${var.environment}-vpc" })
}
# modules/vpc/variables.tf
variable "environment" { type = string }
variable "cidr_block" { type = string default = "10.0.0.0/16" }
variable "tags" { type = map(string) default = {} }
# modules/vpc/outputs.tf
output "vpc_id" { value = aws_vpc.main.id }
output "private_subnet_ids" { value = aws_subnet.private[*].id }
Remote State Configuration
# environments/prod/main.tf
terraform {
required_version = ">= 1.7"
required_providers {
aws = { source = "hashicorp/aws" version = "~> 5.0" }
}
backend "s3" {
bucket = "my-company-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true # Encrypt state at rest
dynamodb_table = "terraform-locks" # State locking
}
}
# Create state bucket and lock table once (manually):
# aws s3 mb s3://my-company-terraform-state --region us-east-1
# aws dynamodb create-table --table-name terraform-locks --attribute-definitions AttributeName=LockID,AttributeType=S --key-schema AttributeName=LockID,KeyType=HASH --billing-mode PAY_PER_REQUEST
CI/CD Workflow
# .github/workflows/terraform.yml
on:
pull_request:
paths: ['infra/**']
push:
branches: [main]
paths: ['infra/**']
jobs:
plan:
if: github.event_name == 'pull_request'
steps:
- run: terraform init
- run: terraform validate
- run: terraform plan -out=plan.tfplan
- run: terraform show -json plan.tfplan | jq '.resource_changes[] | select(.change.actions | contains(["delete"]))'
# Show resources being destroyed - require manual approval
apply:
if: github.ref == 'refs/heads/main'
steps:
- run: terraform init
- run: terraform apply -auto-approve # Only on main, after PR review