Typorithm · medium

Data Sources

terraform-data-sourcesterraformdataread-onlylookup
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Data Sources

0%

State & Modules

A data block looks up existing infrastructure read-only. data "aws_ami" finds an image by filters, and you reference its attributes as data.aws_ami.ubuntu.id without managing it.

A data source reads existing infrastructure instead of creating it. Unlike a resource, Terraform never adds, changes, or destroys what a data block queries.

Here data "aws_ami" "ubuntu" searches for an AMI, narrowing with owners and a filter and using most_recent to pick the newest match.

You consume the result through data.<type>.<name>.<attr> — data.aws_ami.ubuntu.id — to feed a value you don't own into a resource you do, like an instance's ami.

01

data blocks read existing infrastructure (read-only).

02

filters and owners narrow the lookup.

03

Reference results as data.<type>.<name>.<attr>.

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]

  filter {
    name   = "name"
    values = ["ubuntu/*"]
  }
}

resource "aws_instance" "web" {
  ami = data.aws_ami.ubuntu.id
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Data block

A data block queries existing infrastructure read-only; it never creates or destroys anything.

data "aws_ami" "ubuntu" {

2. Newest match

most_recent picks the newest AMI when the query matches several images.

most_recent = true

3. Owner filter

owners narrows the search to AMIs published by Canonical's account id.

owners      = ["099720109477"]

4. Name filter

filter restricts results to AMIs whose name matches the ubuntu/* pattern.

filter {
    name   = "name"
    values = ["ubuntu/*"]
  }

5. Referencing the result

data.<type>.<name>.<attr> reads an attribute of the looked-up resource — here the AMI id.

data.aws_ami.ubuntu.id

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Data Sources: Lesson & Practice · Typorithm | ApplyDjinn