0
0
TerraformHow-ToBeginner · 3 min read

How to Use Output from Module in Terraform

In Terraform, you use output values defined inside a module by referencing them with module... This lets you access data created by the module in your root configuration or other modules.
📐

Syntax

To use an output from a module, first define the output inside the module with output. Then, in the root or calling configuration, access it using module...

Here’s what each part means:

  • module: keyword to access modules
  • <module_name>: the name you gave the module when calling it
  • <output_name>: the name of the output defined inside the module
terraform
module "example" {
  source = "./example-module"
}

output "example_output" {
  value = module.example.example_output
}
💻

Example

This example shows a module that creates a resource and outputs its ID. The root configuration calls the module and uses the output to display the resource ID.

terraform
/* example-module/main.tf */
resource "aws_s3_bucket" "bucket" {
  bucket = "my-example-bucket-12345"
  acl    = "private"
}

output "bucket_id" {
  value = aws_s3_bucket.bucket.id
}

/* root main.tf */
module "s3_bucket" {
  source = "./example-module"
}

output "created_bucket_id" {
  value = module.s3_bucket.bucket_id
}
Output
created_bucket_id = "my-example-bucket-12345"
⚠️

Common Pitfalls

Common mistakes when using module outputs include:

  • Not defining the output inside the module before trying to access it.
  • Using the wrong module name or output name in the root configuration.
  • Expecting outputs from modules that have not been applied yet.

Always run terraform apply after defining outputs to see their values.

terraform
/* Wrong: Trying to access output not defined in module */
output "wrong_output" {
  value = module.s3_bucket.non_existent_output
}

/* Right: Define output inside module first */
output "bucket_id" {
  value = aws_s3_bucket.bucket.id
}

/* Then access it correctly */
output "created_bucket_id" {
  value = module.s3_bucket.bucket_id
}
📊

Quick Reference

ConceptUsage Example
Define output in moduleoutput "name" { value = resource.attribute }
Call module in rootmodule "mod" { source = "./mod" }
Access module outputmodule.mod.name
Use output in rootoutput "out" { value = module.mod.name }

Key Takeaways

Define outputs inside your module to expose values.
Access module outputs using module.. syntax.
Always run terraform apply to generate output values.
Check module and output names carefully to avoid errors.
Use outputs to share data between modules and root configuration.