0
0
Terraformcloud~30 mins

Module composition patterns in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Module Composition Patterns in Terraform
📖 Scenario: You are building a simple cloud infrastructure using Terraform. You want to organize your code by creating reusable modules. This project will guide you through composing modules to build a virtual private cloud (VPC) with subnets.
🎯 Goal: Build a Terraform configuration that uses module composition patterns to create a VPC and two subnets inside it. You will create the initial variables, configure module inputs, apply the main module calls, and complete the configuration with outputs.
📋 What You'll Learn
Create a variables file with exact variable names and values
Configure module input variables with correct values
Call modules with proper source and input arguments
Add outputs to expose the created resources
💡 Why This Matters
🌍 Real World
Organizing Terraform code into modules helps manage complex cloud infrastructure by reusing and composing components.
💼 Career
Understanding module composition is essential for cloud engineers and DevOps professionals to build scalable and maintainable infrastructure as code.
Progress0 / 4 steps
1
Create variables for VPC and subnet CIDR blocks
Create a Terraform variables file named variables.tf with two variables: vpc_cidr set to "10.0.0.0/16" and subnet_cidrs set to a list containing "10.0.1.0/24" and "10.0.2.0/24".
Terraform
Need a hint?

Define variables using the variable block with default values.

2
Configure module input variables for VPC and subnet modules
In a new file named modules.tf, declare two module blocks: vpc with source ./modules/vpc and input variable cidr_block set to var.vpc_cidr, and subnets with source ./modules/subnet and input variable cidr_blocks set to var.subnet_cidrs.
Terraform
Need a hint?

Use module blocks with source and input variables referencing var. variables.

3
Use for_each to create multiple subnets from the subnet module
Modify the subnets module block to use for_each over var.subnet_cidrs. Pass each subnet CIDR block to the module input variable cidr_block using each.value. Rename the module block to subnet (singular).
Terraform
Need a hint?

Use for_each = toset(var.subnet_cidrs) and pass cidr_block = each.value inside the module block.

4
Add outputs to expose VPC ID and subnet IDs
Create an outputs.tf file that defines two outputs: vpc_id which gets the id attribute from module.vpc, and subnet_ids which collects the id attributes from all module.subnet instances using values(module.subnet)[*].id.
Terraform
Need a hint?

Define outputs using output blocks and use a for expression to collect subnet IDs.