Free — no signup required

Data Sources: Querying Reality

2 min read

Read-Only Infrastructure

Not everything in your cloud environment was created by Terraform. There are VPCs created by a networking team, AMIs built by a CI pipeline, and SSL certificates managed by a security team. Your Terraform code needs to reference these resources without taking ownership of them.

Do not hardcode IDs. An AMI ID like ami-0c55b159cbfafe1f0 is region-specific and changes with every new Ubuntu release. Hardcoding it means your code breaks silently when the AMI is deprecated. Use Data Sources instead — they query the cloud API at plan time and return current, accurate values. A data source can ask "what is the default VPC in this account" or "what is the latest Ubuntu 22.04 AMI in this region, matching this name pattern," and a resource block can then reference that returned ID directly instead of a value someone typed in months ago.

Data sources are evaluated during terraform plan, before any resources are created or modified. If a data source query returns no results (e.g., the AMI filter matches nothing), the plan fails with a clear error — catching the problem before any infrastructure is touched.

A powerful pattern is using data "terraform_remote_state" to read outputs from another Terraform configuration's state file. This is how large organizations share information between separate Terraform codebases (e.g., the networking team's VPC IDs consumed by the application team's EC2 instances) without coupling them into a single monolithic configuration.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free