Output Values
After Crumb's apply finishes, the developer asks, "What is the server's IP?" You could dig through the console, but Terraform already knows. Outputs are how a configuration hands information back.
The rule
Name it in an output block, read it with terraform output.
An output block has one label, its name, and a value:
output "web_public_ip" {
value = aws_instance.web.public_ip
description = "Public IP address of Crumb's web server"
}
output "assets_bucket" {
value = aws_s3_bucket.assets.bucket
description = "Name of the bucket holding cake photos"
}valueis any expression: an attribute, a string built with interpolation, a list or a map.descriptiondocuments it for whoever reads or uses it.
What happens to outputs:
- During plan, values not yet known show as
(known after apply). - After apply, the root configuration's outputs are printed:
Outputs:
assets_bucket = "crumb-prod-assets"
web_public_ip = "13.233.10.24"- They are saved in state, so you can read them any time without applying again:
terraform output # all outputs
terraform output web_public_ip # one, as HCL: "13.233.10.24"
terraform output -raw web_public_ip # one, bare: 13.233.10.24
terraform output -json # all, as JSON for toolsOutputs are also a module's public interface: when one configuration uses another as a module, it reads that module's outputs as module.<name>.<output>. You will build modules later; the syntax is already the same. Outputs only print for the root configuration, the folder you run Terraform in; a child module's outputs go up to its caller, which decides whether to output them again.
The shortcut
Ask "Who needs this after apply?" A person wants terraform output. A shell script wants -raw. Another program wants -json. Another Terraform module wants module.name.output.
Declare the output
Add
output "web_public_ip"withvalue = aws_instance.web.public_ip.
The trap: using plain terraform output name in a script. It prints the value with quotes, so the script gets "13.233.10.24" including the quote marks.
Drills
Answer fast — trust the rule.
Which argument is required in an output block?
Which command prints one output as a bare string for a shell script?
Where does terraform output read values from?
A parent configuration calls a module named site that has an output bucket. How does the parent read it?
Remember
output "name" { value = ... }exposes a value; add a description.- Shortcut: people use
terraform output, scripts-raw, tools-json, modulesmodule.x.y. - Trap: plain
terraform output nameincludes quotes; scripts want-raw.
