← Lessons/Variables, Outputs & Data Sources
← Variables, Outputs & Data Sources

Look up an image with a data source

Learn

Data sources: lookups

data "demo_image" "ubuntu" {
  name = "ubuntu-22.04"
}

resource "demo_server" "web" {
  image = data.demo_image.ubuntu.id
}

A data block reads something that already exists rather than creating it. You reference its result as data.<type>.<name>.<attr>. Unlike a resource, a data source never appears in your plan's add/change/destroy counts and isn't stored as managed state — it's a read, not a write.

Here the server already exists from the last step, so wiring in the looked-up image is an in-place update of it:

demo_server.web: Modifying...
demo_server.web: Modifications complete

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

The throughline: a good config takes inputs (variables), reads what it needs (data sources), and returns what others need (outputs) — instead of hard-coding everything in the middle.

Real configs rarely hard-code an image id — they look it up. Add a data source data "demo_image" "ubuntu" { name = "ubuntu-22.04" }, set the server's image = data.demo_image.ubuntu.id, and add output "image_id" with value = data.demo_image.ubuntu.id. Run apply: the looked-up id flows into the server, and notice the data source never appears in the add/change/destroy counts — it's a read, not a write.

Interview prep

Variables, outputs, and data sources come up constantly — interviewers use them to check you can write config that isn't copy-pasted.

What's the difference between a resource and a data source?

A resource block manages infrastructure — Terraform creates, updates, and destroys it, and records it in state. A data block only reads something that already exists (an image, a VPC, an account ID) so you can use its attributes; Terraform never creates or destroys it and it doesn't show up in the plan's add/change/destroy counts.

When would you use an output?

To surface a value after apply — typically a computed attribute you can't know in advance (an IP, an ARN, an id) — so a human, a script, or a parent module can consume it. Outputs are the documented return values of a configuration or module.

Loading...

State Inspector

State

Terraform's memory

empty — nothing here yet

Real Infrastructure

the actual world

empty — nothing here yet