Terraform Tutorial — Outputs Across Modules

1 minute read

Outputs are the way modules communicate. A child module exposes values through output blocks, and the parent (root) module accesses them with module.<name>.<output_name>.


Child Module: Expose Outputs

A VPC module might expose the VPC ID and subnet IDs:

# modules/vpc/outputs.tf

output "vpc_id" {
  value       = aws_vpc.main.id
  description = "The ID of the VPC"
}

output "public_subnet_ids" {
  value       = aws_subnet.public[*].id
  description = "List of public subnet IDs"
}

output "private_subnet_ids" {
  value       = aws_subnet.private[*].id
  description = "List of private subnet IDs"
}

Root Module: Consume Outputs

The root module calls the VPC module and references its outputs:

# main.tf

module "vpc" {
  source      = "./modules/vpc"
  cidr_block  = "10.0.0.0/16"
  environment = var.environment
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  subnet_id     = module.vpc.public_subnet_ids[0]

  tags = {
    Name = "web-server"
  }
}

Chain: Module → Module

One module’s output can feed into another module’s input:

module "vpc" {
  source = "./modules/vpc"
}

module "app" {
  source     = "./modules/app"
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.public_subnet_ids
}

Root Module: Re-export Outputs

If you want the root module’s user to see a child module’s output:

# outputs.tf (root)

output "vpc_id" {
  value       = module.vpc.vpc_id
  description = "VPC ID from the networking module"
}

output "app_url" {
  value       = "http://${module.app.load_balancer_dns}"
  description = "URL of the application"
}

Now terraform output vpc_id returns the VPC ID.


Diagram: Output Flow

┌─────────────┐          ┌─────────────┐
│  VPC Module  │          │  App Module  │
│             │          │             │
│  output:    │  ──────▶ │  input:     │
│  vpc_id     │          │  vpc_id     │
│  subnet_ids │  ──────▶ │  subnet_ids │
└─────────────┘          └─────────────┘
       │                        │
       ▼                        ▼
┌──────────────────────────────────────┐
│          Root Module outputs.tf      │
│  output "vpc_id"                     │
│  output "app_url"                    │
└──────────────────────────────────────┘

What’s Next?

Let’s see practical examples of outputs you’ll use in real projects.


← Sensitive Outputs Practical Output Examples →