Terraform 16: Data sources — reading existing infrastructure
easy⏱ 5 mincourseterraform
data vs resource
data "<type>" "<name>" performs a read-only lookup during plan. Terraform never modifies or destroys what a data source references — it just fetches attributes you can use elsewhere as data.<type>.<name>.<attr>. Use it to reference shared infra you don't own.
# Look up an EXISTING Key Vault by name (someone else created it).
data "azurerm_key_vault" "shared" {
name = "orders-kv-dev"
resource_group_name = "myorg-orders-dev-rg"
}
# Now use its attributes elsewhere:
output "kv_id" { value = data.azurerm_key_vault.shared.id }
output "kv_uri" { value = data.azurerm_key_vault.shared.vault_uri }
Reading a secret from an existing Key Vault
A common pattern: look up a Key Vault with a data source, then read a secret out of it with another data source. You pass the vault's id from the first data source into the second — never hard-code the secret value in HCL.
data "azurerm_key_vault" "shared" {
name = "orders-kv-dev"
resource_group_name = "myorg-orders-dev-rg"
}
data "azurerm_key_vault_secret" "db_password" {
name = "orders-db-password"
key_vault_id = data.azurerm_key_vault.shared.id
}
# Reference the value where a secret is needed (marked sensitive downstream):
# data.azurerm_key_vault_secret.db_password.value
A missing data source fails the plan
If a data source's target doesn't exist, Terraform errors during plan ("no resource found"). That's a feature — it means your config depends on real, present infrastructure. Unlike a resource, a data block will never create the thing for you.
Simulate a Key Vault data-source lookup
You're given existingVaults, a map of name -> id. Write lookupKeyVault(name) that returns the id if the vault exists, or throws Error("no key vault found: <name>") if it doesn't (a data source fails the plan when its target is missing). Log lookupKeyVault("orders-kv-dev"), then in a try/catch log the error message from lookupKeyVault("ghost-kv").