Skip to main content

Modules Outputs

Imagine you’ve built a Lego set inside your Terraform module like a hospital with doors, windows, and a helipad. Now, your Lego city needs to know the hospital’s address and emergency phone number so other buildings can connect to it.

In Terraform, this sharing of information is done through outputs. Outputs are the way modules expose useful values (like IDs, IPs, or names) to the rest of your configuration, enabling modules to work together like connected neighborhoods in your city.


Key Concepts

1. What is an Output?

  • An output is a value exposed by a module.
  • Defined in outputs.tf.
  • Makes module results available to parent configurations or other modules.

2. Defining Outputs

Example in outputs.tf:

output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.example.id
}

output "public_ip" {
  description = "Public IP of the EC2 instance"
  value       = aws_instance.example.public_ip
}

3. Consuming Outputs

Outputs can be used as inputs to other modules:

module "sg" {
  source = "./modules/security-group"
  vpc_id = module.vpc.vpc_id
}

Access outputs from the root module:

output "web_ip" {
  value = module.web.public_ip
}

4. Why Outputs Matter

  • Chaining modules: Pass values between modules (e.g. VPC ID → EC2 module).
  • Visibility: Print important values after terraform apply.
  • Integration: Feed outputs into CI/CD pipelines or external tools.

Hands‑On Lab / Demo

Lab: Using Outputs to Chain Modules

  1. Run terraform apply → Terraform prints EC2 IP at the end.

Root config prints EC2 public IP:

output "ec2_ip" {
  value = module.ec2.public_ip
}

EC2 module consumes VPC ID:

module "ec2" {
  source  = "./modules/ec2"
  vpc_id  = module.vpc.vpc_id
  ami     = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

VPC module outputs VPC ID:

output "vpc_id" {
  value = aws_vpc.main.id
}

Pro Tips & Best Practices

  • Always add descriptions to outputs for clarity.
  • Expose only necessary values. - avoid leaking sensitive data.
  • Use outputs to simplify debugging (e.g., print resource IDs).
  • Chain modules carefully to avoid circular dependencies.
  • Document outputs in the module’s README.

Summary & Cheatsheet

  • Outputs = Shared values from modules.
  • Define in outputs.tf.
  • Consume with module.<name>.<output>.
  • Use cases: chaining modules, printing values, integrating with pipelines.
Quick mnemonic: Define → Expose → Consume

The Hackers Notebook

Module outputs are the communication channels of Terraform. They let modules share information, connect seamlessly, and integrate with external systems. By mastering outputs, you unlock the ability to build complex, interconnected infrastructure with clarity.


Tips, Tricks, Roadmaps, Resources, Networking, Motivation, Guidance, and Cool Stuff ♥

Updated on Dec 31, 2025