Data sources

Data sources

A data source reads information from existing infrastructure or external systems. Unlike a resource, Terraform does not create, update, or delete anything — it only fetches data for use elsewhere in your configuration.

  flowchart LR
    resource["resource block"] -- "creates, updates,<br/>deletes" --> managed["Object managed<br/>by Terraform"]
    data["data block"] -- "reads only" --> existing["Existing object managed<br/>elsewhere"]

Declare a data source using a data block:

main.tf
1
2
3
data "local_file" "settings" {
  filename = "settings.json"
}

A data source has a type (local_file) and a local name (settings), just like a resource. The arguments inside the block tell the provider what to look up.

Reference the fetched data using the data.<TYPE>.<NAME>.<attribute> syntax:

main.tf
1
2
3
4
5
6
7
8
data "local_file" "settings" {
  filename = "settings.json"
}

resource "local_file" "settings_backup" {
  filename = "settings.json.bak"
  content  = data.local_file.settings.content
}

A common real-world use case is looking up infrastructure managed outside of your configuration, e.g. the latest machine image for a virtual machine:

main.tf
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"] # Canonical

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-*-amd64-server-*"]
  }
}

resource "aws_instance" "web_server" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
}

Terraform reads data sources during terraform plan, so the fetched values are always up to date when Terraform calculates what to change.

Best practices

  • Use data sources instead of hardcoding IDs and other values that already exist in your infrastructure.
  • Make lookup arguments specific enough to match exactly one object — ambiguous queries cause errors or, worse, the wrong object being used.
  • If your configuration both creates an object and reads it back, use a resource reference instead of a data source.