Thuta Learning
IntermediateDevOpsintermediate

Data Sources

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Data Sources without any of the intimidation
  • Get hands-on running terraform commands and HCL code yourself
  • Apply this concept in a real project right away

Let's think about it this way for a second

A resource block means 'create this from scratch,' but a Data Source block (`data "<type>" "<name>" { ... }`) means 'just read information about a resource that already exists' — it doesn't create, update, or destroy anything, it only queries. You reach for a Data Source when you want to reference a shared resource (a VPC, a security group) that another team already created, without recreating it in your own config.

Let's connect this to a real scenario

If you write `data "aws_vpc" "existing" { tags = { Name = "production-vpc" } }`, Terraform sends a query to AWS, finds the VPC tagged 'production-vpc', and lets you reference the resulting VPC ID as `data.aws_vpc.existing.id` inside your own resources — no need to recreate the VPC yourself.

Let's look at it together

hcl
data "aws_vpc" "existing" {
  tags = {
    Name = "production-vpc"
  }
}

resource "aws_subnet" "app" {
  vpc_id     = data.aws_vpc.existing.id
  cidr_block = "10.0.1.0/24"
}
You should see
$ terraform plan
data.aws_vpc.existing: Reading...
data.aws_vpc.existing: Read complete after 1s

  + resource "aws_subnet" "app" {
      + vpc_id = "vpc-0123456789abcdef0"
    }

5-minute try-it

Write a data source block (for whichever provider you're using), run `terraform plan`, and take a close look at the 'Reading...' step.

A quick word of caution

A data source's query result depends on the moment apply runs — if the target resource gets deleted or changed before the query happens, plan/apply can fail.

Easy traps

  • Mistaking a data source for a resource and expecting it to create or destroy something — a data source is read-only
  • Writing a data source filter (tags, name) too loosely so it matches more than one result (this causes an error)

Now try it yourself

Write a data source block (for whichever provider you're using), run `terraform plan`, and take a close look at the 'Reading...' step.

You'll know it worked when: $ terraform plan data.aws_vpc.existing: Reading... data.aws_vpc.existing: Read complete after 1s + resource "aws_subnet" "app" { + vpc_id = "vpc-0123456789abcdef0" }

Data Sources | Thuta Learning