Skip to main content

Using Terraform Data Sources to Read Resources

Use Terraform data sources to read existing AWS resources like AMIs, VPCs and secrets without managing them, and learn when each is evaluated.

26 Terms

Overview and What You Will Learn

A Terraform data source is a data block that reads information about something that already exists, such as an AMI, a VPC or a secret, and exposes it to the rest of your configuration. Unlike a resource block, it never creates, changes or destroys anything. In this lab, you will look up the latest Amazon Linux AMI, read a VPC and subnets owned by another team, build names from the current account and region, read secrets and parameters, and learn when Terraform actually evaluates a data source.

  • Choosing between a resource block and a data block
  • Fetching the latest AMI without hardcoding an ID
  • Reading a VPC, subnets and security groups created by another team
  • Using aws_caller_identity, aws_region and aws_availability_zones
  • Reading Secrets Manager and SSM Parameter Store values, and what that does to state
  • Understanding why a data result can show (known after apply)

Why This Matters in Production

At a company like Atlassian, a networking team owns the VPC and subnets, a platform team owns the EC2 and RDS resources, and a security team owns the IAM roles. Nobody creates what another team owns, but everybody needs to reference it. If the platform team hardcodes vpc-0a1b2c3d4e5f6a7b8, the configuration breaks the day the VPC is rebuilt or the code is reused in another region. A data source that finds the VPC by its tags keeps the configuration portable across regions and environments.

Core Principles

A data source performs a read-only API call and returns attributes you can reference as data.<type>.<name>.<attribute>. The data. prefix is what distinguishes a lookup from a managed resource such as aws_instance.web.id.

flowchart TD D[data block
aws_vpc.main] --> API[(Provider API
read-only call)] API --> R[Result attributes
id, cidr_block] R --> U[resource block
aws_subnet.app] classDef cfg fill:#326CE5,color:#FFFFFF classDef api fill:#475569,color:#FFFFFF classDef out fill:#D1FAE5,color:#1E293B class D,U cfg class API api class R out

The two block types differ in ownership:

Question resource block data block
What does it do? Creates and manages an object Reads an existing object
Can Terraform destroy it? Yes No, the object is untouched
Where is it recorded? In state In state, as a refreshed read

Data sources do appear in state and in terraform state list as data.aws_ami.amazon_linux. What they never do is change the real object. Their results are refreshed on every plan.

Detailed Step-by-Step Practical Lab

Part 1 - Look Up the Latest AMI

Hardcoded AMI IDs go stale and differ per region. The aws_ami data source returns the current image that matches your filters:

HCL
data "aws_ami" "amazon_linux_2023" {
most_recent = true # if several match, return the newest
owners = ["amazon"] # only AMIs published by Amazon
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"] # Amazon Linux 2023 naming pattern
}
filter {
name = "state"
values = ["available"] # skip images that are not ready
}
}
resource "aws_instance" "app_server" {
ami = data.aws_ami.amazon_linux_2023.id
instance_type = "t3.medium"
tags = {
Name = "mumbai-prod-app-1"
AMI = data.aws_ami.amazon_linux_2023.name
}
}
output "ami_id_used" {
description = "AMI selected by the data source, kept for auditing"
value = data.aws_ami.amazon_linux_2023.id
}

For Ubuntu, filter on Canonical's AWS account ID, which is 099720109477:

HCL
data "aws_ami" "ubuntu_22_04" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
Remember

most_recent = true makes the AMI change between plans whenever a newer image is published, which can trigger an instance replacement. Pin the AMI for production, or use lifecycle { ignore_changes = [ami] } and roll out new images deliberately.

Part 2 - Read a VPC and Subnets Owned by Another Team

HCL
data "aws_vpc" "main" {
tags = {
Name = "mumbai-prod-vpc"
Environment = "prod"
}
}
data "aws_subnets" "private" {
filter {
name = "vpc-id"
values = [data.aws_vpc.main.id]
}
tags = {
Tier = "private" # the networking team tags its subnets
}
}
resource "aws_db_subnet_group" "app" {
name = "payments-db-subnet-group"
subnet_ids = data.aws_subnets.private.ids
}
resource "aws_security_group" "rds" {
name = "payments-rds-sg"
vpc_id = data.aws_vpc.main.id
}

A singular data source such as aws_vpc or aws_subnet must match exactly one object. The plural forms, aws_subnets and aws_availability_zones, return lists.

Part 3 - Make Configurations Aware of Account and Region

HCL
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
data "aws_availability_zones" "available" {
state = "available"
}
resource "aws_s3_bucket" "artifacts" {
# bucket names are global, so add the account ID to guarantee uniqueness
bucket = "mumbai-prod-artifacts-${data.aws_caller_identity.current.account_id}"
}
resource "aws_cloudwatch_log_group" "app" {
name = "/aws/ec2/${data.aws_region.current.name}/app" # /aws/ec2/ap-south-1/app
}
Tip

The name attribute of aws_region is correct for AWS provider 5.x. Newer provider releases introduce a region attribute and deprecate name, so check the provider changelog when you upgrade.

Part 4 - Reuse Existing Security Groups and IAM Objects

HCL
data "aws_security_group" "bastion" {
name = "mumbai-prod-bastion-sg"
vpc_id = data.aws_vpc.main.id
}
data "aws_iam_role" "ec2_instance_role" {
name = "mumbai-prod-ec2-instance-role"
}
data "aws_iam_policy" "ssm_managed" {
arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_role_policy_attachment" "ssm" {
role = data.aws_iam_role.ec2_instance_role.name
policy_arn = data.aws_iam_policy.ssm_managed.arn
}

Part 5 - Read Secrets and Parameters

HCL
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = "payments/prod/rds/master-password"
}
data "aws_ssm_parameter" "db_endpoint" {
name = "/payments/prod/database/endpoint"
}
data "aws_ssm_parameter" "api_key" {
name = "/payments/prod/third-party/api-key"
with_decryption = true
}
resource "aws_db_instance" "payments" {
identifier = "mumbai-prod-payments"
engine = "postgres"
instance_class = "db.r6g.large"
allocated_storage = 100
username = "payments_admin"
password = data.aws_secretsmanager_secret_version.db_password.secret_string
}
Security

A value read through a data source is still written to the state file in plaintext, and it is also copied into any resource attribute that uses it. Encrypt the state backend, restrict access to it, and mark outputs as sensitive. For RDS, manage_master_user_password = true lets AWS manage the password so it never enters your configuration. Newer Terraform versions also offer ephemeral values, which are never stored in state.

Part 6 - When a Data Source Is Evaluated

Terraform reads a data source during plan when all of its arguments are already known. If an argument depends on a resource that does not exist yet, the read is deferred to apply time and its results show as (known after apply).

flowchart TD Q{Are all arguments
known at plan time?} -->|Yes| P[Read during plan
results visible] Q -->|No| A[Deferred to apply
known after apply] classDef dec fill:#F97316,color:#FFFFFF classDef ok fill:#10B981,color:#FFFFFF classDef wait fill:#8B5CF6,color:#FFFFFF class Q dec class P ok class A wait
HCL
resource "aws_vpc" "lab" {
cidr_block = "10.0.0.0/16"
}
data "aws_subnets" "lab" {
filter {
name = "vpc-id"
values = [aws_vpc.lab.id]
}
}

To refresh data sources without changing infrastructure, run terraform plan -refresh-only. If you created a resource in the same configuration, reference it directly as aws_vpc.lab.id instead of looking it up with a data source.

Production Best Practices & Common Pitfalls

Common Mistake

Hardcoding IDs such as vpc-0a1b2c3d4e5f6a7b8 or ami-0f5ee92e2d63afc18 in resource arguments. They differ per region and account, and they silently go stale.

Tip

Agree on a tagging standard with the team that owns the shared resources. A data source that filters on tags only works if the tags are present and consistent.

  • Expect hard failures when the target disappears. If someone renames a tag or deletes the object, the next plan errors. That is useful, because it forces you to update the configuration instead of guessing.
  • Narrow filters until exactly one object matches. A singular data source that matches zero or several objects fails the plan.
  • Do not look up what you create. Reference the resource attribute directly, which also gives Terraform a correct dependency.
  • Treat most_recent AMIs as a moving target. Pin or ignore AMI changes on long-lived servers to avoid surprise replacements.
  • Verify publisher IDs. Owner IDs like Canonical's 099720109477 protect you from look-alike community AMIs.

Quick Reference & Troubleshooting Commands

Command Description
terraform plan Shows data reads and any (known after apply) values
terraform plan -refresh-only Re-reads data sources and resources without proposing changes
terraform console Evaluate expressions such as data.aws_vpc.main.id
terraform state list Lists resources and data sources, shown as data.TYPE.NAME
terraform state show data.aws_ami.amazon_linux_2023 Inspect a data source's stored attributes
Error Cause Fix
no matching AMI found Filters or owner match nothing Broaden the filter and check owners
no matching EC2 VPC found Tags or values do not match Verify tags on the real VPC
multiple VPCs matched Filter too broad Add filters until exactly one matches
(known after apply) in plan Depends on a resource not yet created Normal, or reference the resource directly
AccessDeniedException on a secret Missing permission Grant secretsmanager:GetSecretValue to the role

Resources

Explore More in Terraform Fundamentals and Core Workflow

All 4 Topics

Frequently Asked Questions

Is Using Terraform Data Sources to Read Resources free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Using Terraform Data Sources to Read Resources topic cover?

Use Terraform data sources to read existing AWS resources like AMIs, VPCs and secrets without managing them, and learn when each is evaluated.

Found a mistake, an outdated step or a broken link?