0
0
TerraformHow-ToBeginner · 3 min read

How to Define Output in Terraform: Syntax and Examples

In Terraform, you define output values using the output block, which lets you display useful information after applying your configuration. Each output has a name and a value expression that specifies what to show. Outputs help you see important resource details or pass data to other configurations.
📐

Syntax

The output block defines a named output value in Terraform. It has these parts:

  • name: The identifier for the output.
  • value: The expression or resource attribute to display.
  • description (optional): A short explanation of the output.
  • sensitive (optional): Marks output as sensitive to hide it in logs.
terraform
output "example_output" {
  value       = "Hello, Terraform!"
  description = "A simple example output"
  sensitive   = false
}
💻

Example

This example shows how to output the public IP address of an AWS EC2 instance after creation. It helps you quickly find the instance's IP without searching the state file.

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

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

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

Common Pitfalls

Common mistakes when defining outputs include:

  • Using incorrect resource references in the value field, causing errors.
  • Not marking sensitive outputs as sensitive = true, exposing secrets.
  • Forgetting to run terraform apply before outputs show values.

Always verify resource names and attributes exist and are accessible.

terraform
output "wrong_reference" {
  value = aws_instance.nonexistent.public_ip
}

# Correct way:
output "correct_reference" {
  value = aws_instance.example.public_ip
}
📊

Quick Reference

PropertyDescription
nameUnique identifier for the output
valueExpression or resource attribute to display
descriptionOptional text explaining the output
sensitiveOptional boolean to hide output value

Key Takeaways

Use the output block with a name and value to define outputs in Terraform.
Outputs display important info after apply and can pass data between configs.
Mark sensitive outputs with sensitive = true to protect secrets.
Always verify resource references in output values to avoid errors.
Run terraform apply before outputs show actual values.