Terraform Tutorial · State and Workflow · Lesson 18 of 25
Terraform Data Sources
Data sources read information that exists outside your configuration, such as the latest AMI, the current account or an existing VPC, without managing it.
Reading existing things
A data block looks something up; it never creates or changes anything.
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
}
}
data "aws_caller_identity" "current" {}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
}
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
Refer to data sources as data.<type>.<name>.<attribute>.
terraform {
required_providers {
local = { source = "hashicorp/local", version = "~> 2.5" }
}
}
resource "local_file" "source" {
filename = "${path.module}/version.txt"
content = "2.4.1"
}
data "local_file" "version" {
filename = local_file.source.filename
depends_on = [local_file.source]
}
output "version" {
value = data.local_file.version.content
}
Output
Terraform will perform the following actions:
# data.local_file.version will be read during apply
# (depends on a resource or a module with changes pending)
<= data "local_file" "version" {
+ content = (known after apply)
+ content_base64 = (known after apply)
+ content_base64sha256 = (known after apply)
+ content_base64sha512 = (known after apply)
+ content_md5 = (known after apply)
+ content_sha1 = (known after apply)
+ content_sha256 = (known after apply)
+ content_sha512 = (known after apply)
+ filename = "./version.txt"
+ id = (known after apply)
}
# local_file.source will be created
+ resource "local_file" "source" {
+ content = "2.4.1"
+ content_base64sha256 = (known after apply)
+ content_base64sha512 = (known after apply)
+ content_md5 = (known after apply)
+ content_sha1 = (known after apply)
+ content_sha256 = (known after apply)
+ content_sha512 = (known after apply)
+ directory_permission = "0777"
+ file_permission = "0777"
+ filename = "./version.txt"
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.Run this on your computer — see “Get Started” for setup.
Test yourself
Can a data source create infrastructure?
YesNo
Show answer
Answer: No
Data sources only read. Use a resource to create something.