0
0
TerraformHow-ToBeginner · 3 min read

How to Use Data to Read Existing Resource in Terraform

In Terraform, use a data block to read information about existing resources without managing them. This lets you reference existing infrastructure by specifying the resource type and required identifiers inside the data block.
📐

Syntax

The data block in Terraform lets you fetch details about existing resources. It has three main parts:

  • data: keyword to declare a data source
  • resource_type: the type of resource you want to read (e.g., aws_vpc)
  • resource_name: a local name to reference this data source
  • arguments: parameters to identify the existing resource (like id or filter)
terraform
data "resource_type" "resource_name" {
  argument = "value"
}
💻

Example

This example reads an existing AWS VPC by its ID and outputs its CIDR block. It shows how to declare a data block and use its attributes elsewhere.

terraform
provider "aws" {
  region = "us-east-1"
}

data "aws_vpc" "example" {
  id = "vpc-0bb1c79de3EXAMPLE"
}

output "vpc_cidr_block" {
  value = data.aws_vpc.example.cidr_block
}
Output
vpc_cidr_block = "10.0.0.0/16"
⚠️

Common Pitfalls

Common mistakes when using data sources include:

  • Using incorrect or missing identifiers like id, causing Terraform to fail to find the resource.
  • Confusing data blocks with resource blocks; data only reads existing resources and does not create or modify them.
  • Not refreshing the state after changes outside Terraform, leading to stale data.
terraform
/* Wrong: Trying to create a resource with data block */
data "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16"  # This is invalid for data source
}

/* Right: Use id to read existing VPC */
data "aws_vpc" "example" {
  id = "vpc-0bb1c79de3EXAMPLE"
}
📊

Quick Reference

Remember these tips when using Terraform data sources:

  • Use data blocks to read existing resources only.
  • Always provide correct identifiers like id or filters.
  • Use the data source attributes to reference resource details in your configuration.
  • Run terraform refresh if external changes happen.

Key Takeaways

Use data blocks to read existing resources without managing them.
Provide correct identifiers like id to locate the resource.
Do not confuse data sources with resource blocks.
Use attributes from data sources to reference resource details in your Terraform code.
Refresh Terraform state if resources change outside Terraform.