Data Sources
A resource creates and manages an object. A data source only reads: the latest Ubuntu AMI, the availability zones of a region, the current AWS account id, a VPC another team created, a file on disk. It is declared with data and referenced with a data. prefix:
data "aws_availability_zones" "available" {
state = "available"
}
resource "aws_subnet" "private" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = data.aws_availability_zones.available.names[0]
}Data sources are read during plan (or during apply, shown as <=, when an argument depends on something not created yet). They never appear as "to add" or "to destroy", and nothing is deleted when you remove one.
Reading a local file
The local provider has a local_file data source. Here a team keeps its allowed CIDR ranges in a plain text file, and the configuration turns it into a list:
mkdir d && cd d
printf '10.0.0.0/16\n192.168.10.0/24\n' > allowed-cidrs.txt
cat > main.tf <<'HCL'
data "local_file" "cidrs" {
filename = "${path.module}/allowed-cidrs.txt"
}
output "cidrs" {
value = compact(split("\n", data.local_file.cidrs.content))
}
HCL
tofu init >/dev/null
tofu apply -auto-approvedata.local_file.cidrs: Reading...
data.local_file.cidrs: Read complete after 0s [id=8aae10ffbd243734f2286bc0dd0b952be7846315]
Changes to Outputs:
+ cidrs = [
+ "10.0.0.0/16",
+ "192.168.10.0/24",
]
You can apply this plan to save these new output values to the OpenTofu
state, without changing any real infrastructure.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
cidrs = tolist([
"10.0.0.0/16",
"192.168.10.0/24",
])
The Reading.../Read complete lines are the data source being read; the apply itself has nothing to create (0 added), yet the output is computed and saved in state. tolist([…]) is how the CLI prints a value of type list(string), as returned by compact; a literal ["a", "b"] would print without it, because its type is a tuple.
Policy documents without a network
Some data sources are pure functions inside the provider. aws_iam_policy_document builds IAM policy JSON from HCL blocks, which is easier to review and compose than a JSON string, and it needs no API call. The provider still has to be configured to start, so this session gives it dummy keys and turns off the account lookups: a teaching setup used throughout this course to plan AWS code offline (it would fail at apply).
mkdir policy && cd policy
cat > offline.tf <<'HCL'
# Teaching setup: dummy keys and no account lookups, so the provider never calls AWS.
provider "aws" {
region = "eu-west-1"
access_key = "offline"
secret_key = "offline"
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
}
HCL
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
data "aws_iam_policy_document" "read_logs" {
statement {
sid = "ReadLogs"
actions = ["s3:GetObject", "s3:ListBucket"]
resources = ["arn:aws:s3:::linkly-logs", "arn:aws:s3:::linkly-logs/*"]
}
statement {
sid = "DenyDelete"
effect = "Deny"
actions = ["s3:DeleteObject"]
resources = ["arn:aws:s3:::linkly-logs/*"]
}
}
output "policy" {
value = data.aws_iam_policy_document.read_logs.json
}
HCL
tofu init >/dev/null
tofu apply -auto-approve >/dev/null
tofu output -raw policy{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadLogs",
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::linkly-logs/*",
"arn:aws:s3:::linkly-logs"
]
},
{
"Sid": "DenyDelete",
"Effect": "Deny",
"Action": "s3:DeleteObject",
"Resource": "arn:aws:s3:::linkly-logs/*"
}
]
}
Notice that actions and resources came out in a different order than written: they are sets in the provider's schema, so their order carries no meaning. Pass .json to an aws_iam_policy's policy argument or a bucket policy. The IAM Policies lesson explains what the statements mean.
Data sources that call the API
Most AWS data sources query the account, so they need real credentials. A plan against a real account looks like this:
$ tofu plan
data.aws_availability_zones.available: Reading...
data.aws_caller_identity.current: Reading...
data.aws_ami.ubuntu: Reading...
data.aws_caller_identity.current: Read complete after 0s [id=123456789012]
data.aws_availability_zones.available: Read complete after 0s [id=eu-west-1]
data.aws_ami.ubuntu: Read complete after 1s [id=ami-0a1b2c3d4e5f60718]
…Common ones:
| Data source | Returns |
|---|---|
aws_caller_identity |
the account id and ARN the CLI runs as |
aws_region, aws_availability_zones |
the region, its zone names |
aws_ami (with most_recent and filter) |
an image id, e.g. the latest Ubuntu LTS |
aws_vpc, aws_subnets (with tags or filter) |
network objects created elsewhere |
aws_secretsmanager_secret_version, aws_ssm_parameter |
a stored value (it ends up in state!) |
terraform_remote_state |
the outputs of another configuration's state |
In tests you replace them with fixed values (override_data in Testing), which is how the AWS lessons stay offline.
Tip: Prefer looking up shared infrastructure by tag with a data source (or reading another stack's outputs) over copying ids into variables. A hard-coded
vpc-0abc…breaks the day the VPC is rebuilt.
Test yourself
What happens to the real object when you delete a data block from the code?
- It is destroyed
- Nothing: data sources only read
- It is imported
- It is moved to another state
Why does aws_iam_policy_document work without contacting AWS?
- It is cached in the lock file
- It only renders JSON from the HCL blocks inside the provider
- It reads from the state
- It uses the registry
A plan shows <= data "aws_ami" "x" under the actions. What does it mean?
- The AMI will be deleted
- The data source will be read during apply, because it depends on a value not known yet
- The AMI is replaced
- The data source failed