Terraform Data Sources
Sometimes you need to fetch information about existing infrastructure that was created outside Terraform or in a different configuration. Data sources allow you to read and reference such resources without managing them.
What Is a Data Source?
A data source queries the provider’s API and returns information about existing resources. It does not create or modify resources. Common uses: look up an AMI ID, fetch a VPC ID, or get the current AWS caller identity.
Data sources let you read external or pre‑existing infrastructure into your configuration.
Data Source Syntax
Use a
data block with a type and name, plus query arguments.data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}Using Data Source Attributes
After declaring a data source, you can access its exported attributes using
data.<type>.<name>.<attribute>:resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
}Example: Fetch Existing VPC
data "aws_vpc" "default" {
default = true
}
resource "aws_subnet" "main" {
vpc_id = data.aws_vpc.default.id
cidr_block = "10.0.1.0/24"
}Common Data Sources
- aws_ami – look up AMI IDs
- aws_vpc – fetch VPC details
- aws_subnet – get subnet info
- aws_security_group – reference existing SGs
- aws_caller_identity – get current AWS account ID
- aws_region – current region
Dependencies with Data Sources
Terraform queries data sources during the planning phase. They do not create dependencies like resources do, but if a data source depends on a resource (e.g., you create a resource and then look it up), you may need to use
depends_on or restructure.Two Minute Drill
- Data sources read information about existing resources.
- Syntax:
data "type" "name" { ... }. - Access attributes with
data.type.name.attribute. - Useful for AMI lookup, VPC info, and account details.
Need more clarification?
Drop us an email at career@quipoinfotech.com
