Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A Three-Tier Application Built from Modules

Assemble a three-tier application from network, database and service modules, deploy it to dev and prod with different settings, and test the wiring with simulations.

This project combines the module chapter with the workflow chapter. You will design a small platform as three modules (network, database, service), compose them in the root, and run it in two environments, dev and prod, that differ only in settings. The goal is not memorizing resource arguments; it is practicing the structure: clear interfaces, stable outputs, environment folders and safe defaults.

HCL is read-only here. Each design step has a runnable model so you can test your thinking.

Requirements

  • A VPC with public and private subnets in two zones.
  • A managed database in private subnets, reachable only from the service.
  • A containerized service behind a load balancer.
  • dev: small and cheap, single database instance. prod: larger, multi-AZ database, three service copies, deletion protection.
  • Separate state per environment, shared module code.

Repository layout

TEXT
infra/
  modules/
    network/   main.tf variables.tf outputs.tf versions.tf
    database/  ...
    service/   ...
  envs/
    dev/       main.tf backend.tf terraform.tfvars
    prod/      main.tf backend.tf terraform.tfvars
flowchart TD
  subgraph Root["envs/prod/main.tf"]
    N["module.network"]
    D["module.database"]
    S["module.service"]
  end
  N -->|"vpc_id, private_subnet_ids"| D
  N -->|"vpc_id, public_subnet_ids, private_subnet_ids"| S
  D -->|"endpoint, security_group_id"| S

Outputs of one module become inputs of the next; the root module is the only place that knows the whole picture.

Step 1: define the interfaces first

Write down what each module needs and returns before writing any resource. This is the single best habit in module design (Designing Good Modules).

HCL
# modules/network/variables.tf
variable "name"     { type = string }
variable "vpc_cidr" { type = string }
variable "az_count" {
  type    = number
  default = 2
  validation {
    condition     = var.az_count >= 2 && var.az_count <= 3
    error_message = "Use 2 or 3 availability zones."
  }
}

# modules/network/outputs.tf
output "vpc_id"             { value = aws_vpc.this.id }
output "public_subnet_ids"  { value = [for s in aws_subnet.public : s.id] }
output "private_subnet_ids" { value = [for s in aws_subnet.private : s.id] }
HCL
# modules/database/variables.tf
variable "name"               { type = string }
variable "vpc_id"             { type = string }
variable "subnet_ids"         { type = list(string) }
variable "instance_class"     { type = string }
variable "multi_az"           { type = bool }
variable "deletion_protection" {
  type    = bool
  default = true
}
variable "allowed_security_group_id" { type = string }

# modules/database/outputs.tf
output "endpoint"          { value = aws_db_instance.this.address }
output "secret_arn"        { value = aws_db_instance.this.master_user_secret[0].secret_arn }

The database module asks for the service's security group ID, so it can allow inbound traffic only from it. That creates a circular worry: the service needs the database endpoint, and the database needs the service's security group. The fix is to create the service security group in the root (or in the network module) and pass it to both. Always look for such cycles while designing the interfaces, because Terraform reports "Cycle" errors only at plan time.

Python Detect a dependency cycle between modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 2: the root module per environment

HCL
# envs/prod/main.tf
terraform {
  required_version = "~> 1.9"
  required_providers { aws = { source = "hashicorp/aws", version = "~> 5.60" } }
}

provider "aws" { region = var.region }

module "network" {
  source   = "../../modules/network"
  name     = "shop-${var.environment}"
  vpc_cidr = var.vpc_cidr
  az_count = var.az_count
}

module "database" {
  source                    = "../../modules/database"
  name                      = "shop-${var.environment}"
  vpc_id                    = module.network.vpc_id
  subnet_ids                = module.network.private_subnet_ids
  instance_class            = var.db_instance_class
  multi_az                  = var.db_multi_az
  deletion_protection       = var.environment == "prod"
  allowed_security_group_id = module.network.app_security_group_id
}

module "service" {
  source             = "../../modules/service"
  name               = "shop-${var.environment}"
  image              = var.image
  desired_count      = var.service_count
  vpc_id             = module.network.vpc_id
  public_subnet_ids  = module.network.public_subnet_ids
  private_subnet_ids = module.network.private_subnet_ids
  security_group_id  = module.network.app_security_group_id
  environment_vars   = { DB_HOST = module.database.endpoint }
}
HCL
# envs/prod/terraform.tfvars
environment       = "prod"
region            = "eu-central-1"
vpc_cidr          = "10.20.0.0/16"
az_count          = 3
db_instance_class = "db.m6g.large"
db_multi_az       = true
service_count     = 3
image             = "ghcr.io/acme/shop:2.3.1"

dev uses the same main.tf structure with db.t4g.micro, db_multi_az = false, service_count = 1 and a different backend key. The module code is identical, which is the whole point: dev is a faithful rehearsal of prod.

Step 3: model the environments

You can check design decisions before paying for anything. This program expands the two tfvars into the resources each environment would contain and prints a rough monthly cost estimate, based on invented illustrative prices (not real AWS pricing).

Python Compare dev and prod

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 4: protect state and roll out

  1. Create envs/dev and envs/prod backends with different keys (dev/shop/..., prod/shop/...) and accounts.
  2. In CI, trigger plan for the folder that changed; require approval for prod (Terraform in CI).
  3. Version the modules (Git tags) and bump the version in dev first when you change a module.
  4. Add a terraform test file per module with mock_provider to check validation and defaults (Testing Modules).

Step 5: test the wiring

Python Check that the interfaces match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Stretch goals

  • Add a monitoring module (alarms, dashboard) with a boolean switch using count.
  • Use for_each to deploy several services (api, worker) from the same service module.
  • Add a policy check that rejects deletion_protection = false in prod (Testing and Policy).
  • Move secrets into AWS Secrets Manager and read them by ARN rather than passing passwords.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the best first step when designing a multi-module system?

    Clear interfaces expose cycles and keep modules independent.
  2. 2. How should dev and prod differ?

    Identical code with different settings makes dev a reliable rehearsal.
  3. 3. Why pass the service's security group ID to the database module?

    The database's ingress rule references that group instead of an IP range.
  4. 4. How do you avoid a cycle where service needs the db endpoint and db needs the service's security group?

    Break the cycle by moving the shared resource upstream of both modules.

Summary

  • Design module interfaces first and check for cycles.
  • Compose network, database and service modules in thin per-environment root modules.
  • Keep environments identical in code and different in variables, state and credentials.
  • Enable deletion protection and multi-AZ where it matters, driven by variables.
  • Test wiring with simulations and terraform test, and roll out dev before prod.

Next: Terraform Best Practices and OpenTofu