How to Use Data Source in Terraform: Syntax and Example
In Terraform, a
data source lets you fetch information about existing resources outside your configuration. You define a data block with the resource type and required arguments, then use its attributes elsewhere in your Terraform code.Syntax
A data block in Terraform has three main parts:
- Type: The kind of resource you want to read (e.g.,
aws_ami). - Name: A local name to reference this data source.
- Arguments: Filters or identifiers to find the exact resource.
You can then use the data source's attributes with data.<type>.<name>.<attribute>.
terraform
data "aws_ami" "example" { most_recent = true filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-ebs"] } owners = ["amazon"] }
Example
This example fetches the latest Amazon Linux 2 AMI ID and uses it to launch an EC2 instance.
terraform
provider "aws" { region = "us-east-1" } data "aws_ami" "amazon_linux" { most_recent = true filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-ebs"] } owners = ["amazon"] } resource "aws_instance" "example" { ami = data.aws_ami.amazon_linux.id instance_type = "t2.micro" }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
instance_id = "i-0abcd1234efgh5678"
Common Pitfalls
- Not specifying required filters can cause errors or unexpected results.
- Using data sources without a provider configured leads to failures.
- Referencing data source attributes before they are defined causes errors.
- Assuming data sources create resources; they only read existing ones.
terraform
/* Wrong: Missing filter causes error or wrong AMI */ data "aws_ami" "bad_example" { owners = ["amazon"] } /* Right: Add filter to narrow down AMI */ data "aws_ami" "good_example" { most_recent = true filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-ebs"] } owners = ["amazon"] }
Quick Reference
Remember these tips when using data sources in Terraform:
- Use
datablocks to read existing resources. - Always specify filters or identifiers to get the correct resource.
- Access attributes with
data.<type>.<name>.<attribute>. - Data sources do not create or modify resources.
Key Takeaways
Use
data blocks to fetch existing resource information in Terraform.Always provide filters or identifiers to accurately select the resource.
Access data source attributes with
data.type.name.attribute syntax.Data sources only read data; they do not create or change infrastructure.
Configure the provider before using data sources to avoid errors.