0
0
TerraformHow-ToBeginner · 4 min read

How to Use Output Value in Terraform: Simple Guide

In Terraform, use output blocks to define output values that show information after deployment or share data between modules. Reference these outputs in other configurations or view them with terraform output command.
📐

Syntax

An output block defines a named value to be displayed or shared after Terraform applies changes. It includes a value attribute that specifies what to output.

  • output "name": The name you give to the output.
  • value: The expression or resource attribute you want to output.
  • description (optional): Explains what the output means.
terraform
output "example_output" {
  value       = aws_instance.example.public_ip
  description = "The public IP address of the example instance"
}
💻

Example

This example creates an AWS EC2 instance and outputs its public IP address. After applying, Terraform shows the IP, which you can use to connect to the instance.

terraform
provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

output "instance_ip" {
  value       = aws_instance.example.public_ip
  description = "Public IP of the EC2 instance"
}
Output
instance_ip = "54.210.123.45"
⚠️

Common Pitfalls

Common mistakes when using outputs include:

  • Referencing outputs before applying Terraform, which causes errors because outputs don't exist yet.
  • Not using terraform output command to view outputs after apply.
  • Trying to output sensitive data without marking it as sensitive = true, which can expose secrets.

Always run terraform apply before accessing outputs and mark sensitive outputs properly.

terraform
output "secret_key" {
  value     = aws_instance.example.private_key
  sensitive = true
}

# Wrong: Trying to access output before apply
# terraform output instance_ip  # Error if not applied yet

# Right: Apply first, then output
# terraform apply
# terraform output instance_ip
📊

Quick Reference

TermDescription
output "name"Defines the output block with a unique name
valueExpression or resource attribute to output
descriptionOptional explanation of the output
sensitiveMarks output as secret to hide in CLI
terraform outputCommand to display outputs after apply

Key Takeaways

Define outputs with output blocks to share or display values after deployment.
Always run terraform apply before accessing outputs to avoid errors.
Use terraform output command to view output values.
Mark sensitive outputs with sensitive = true to protect secrets.
Outputs help connect modules and show useful info like IP addresses or IDs.