Day 4 – Terraform Modules and State
Today's Focus
Organise Terraform with modules, manage remote state, and apply cost management practices.
Tasks
- Refactor your Terraform into modules: create
modules/networking/(VPC, subnets, IGW, NAT),modules/ecs/(cluster, task definition, service), andmodules/alb/(ALB, target group, listener). Each module should havevariables.tf,main.tf, andoutputs.tf. Call them from a rootmain.tf. - Configure remote Terraform state: create an S3 bucket and DynamoDB table for state locking. Add a
backend "s3"block to your root module. Runterraform init -migrate-stateto move local state to S3. Verify theterraform.tfstateis now in S3 and your local file is empty. - Add resource tagging consistently: create a
locals.tfwith acommon_tagsmap containingEnvironment,Project,ManagedBy = "terraform". Apply this to every resource usingtags = local.common_tags. Tagging enables cost allocation. - Use the AWS Cost Explorer (or
aws ce get-cost-and-usageCLI) to view the cost of resources you provisioned this week. Identify the most expensive component. Set up a billing alert: create a CloudWatch alarm that triggers when estimated charges exceed $5. - Run
terraform planon your refactored code and confirm zero changes (pure refactor, no infrastructure changes). This validates your module extraction was correct. - Write a
README.mdfor each module documenting inputs, outputs, and an example usage block.