Day 4 of 5
⏱ ~60 minutes
Terraform in 5 Days — Day 4

Modules: Reusable Infrastructure

Extract configurations into modules, use the Terraform Registry, and structure a multi-environment repo.

Creating a Module

Directory Structure
infrastructure/
├── main.tf
├── variables.tf
├── outputs.tf
└── modules/
    └── web-server/
        ├── main.tf       ← module resources
        ├── variables.tf  ← module inputs
        └── outputs.tf    ← module outputs
modules/web-server/variables.tf
variable "instance_type" {
  type    = string
  default = "t3.micro"
}

variable "name" {
  type = string
}

variable "subnet_id" {
  type = string
}

variable "security_group_ids" {
  type = list(string)
}
Root main.tf — using the module
module "web" {
  source = "./modules/web-server"

  name               = "production-web"
  instance_type      = "t3.small"
  subnet_id          = aws_subnet.public.id
  security_group_ids = [aws_security_group.web.id]
}

# Public registry modules
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.1.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
  azs  = ["us-east-1a", "us-east-1b"]
}
💡
The Terraform Registry (registry.terraform.io) has community modules for everything: VPCs, EKS clusters, RDS databases. Using terraform-aws-modules/vpc/aws is better than writing your own VPC from scratch — it handles edge cases you haven't thought of yet.
📝 Day 4 Exercise
Build a Reusable Module
  1. E
  2. x
  3. t
  4. r
  5. a
  6. c
  7. t
  8. y
  9. o
  10. u
  11. r
  12. E
  13. C
  14. 2
  15. +
  16. s
  17. e
  18. c
  19. u
  20. r
  21. i
  22. t
  23. y
  24. g
  25. r
  26. o
  27. u
  28. p
  29. i
  30. n
  31. t
  32. o
  33. a
  34. m
  35. o
  36. d
  37. u
  38. l
  39. e
  40. .
  41. C
  42. a
  43. l
  44. l
  45. i
  46. t
  47. t
  48. w
  49. i
  50. c
  51. e
  52. w
  53. i
  54. t
  55. h
  56. d
  57. i
  58. f
  59. f
  60. e
  61. r
  62. e
  63. n
  64. t
  65. n
  66. a
  67. m
  68. e
  69. s
  70. a
  71. n
  72. d
  73. i
  74. n
  75. s
  76. t
  77. a
  78. n
  79. c
  80. e
  81. t
  82. y
  83. p
  84. e
  85. s
  86. .
  87. U
  88. s
  89. e
  90. t
  91. h
  92. e
  93. o
  94. u
  95. t
  96. p
  97. u
  98. t
  99. s
  100. f
  101. r
  102. o
  103. m
  104. t
  105. h
  106. e
  107. m
  108. o
  109. d
  110. u
  111. l
  112. e
  113. i
  114. n
  115. t
  116. h
  117. e
  118. r
  119. o
  120. o
  121. t
  122. m
  123. o
  124. d
  125. u
  126. l
  127. e
  128. .

Day 4 Summary

  • Modules are directories of .tf files. Call them with a module block and pass variables.
  • Module inputs = variables.tf. Module outputs = outputs.tf. Reference: module.name.output.
  • Registry modules save time. Version-pin them: version = "5.1.0".
  • Multi-environment: call the same module with different variables for dev vs prod.
Finished this lesson?