Module 7, Data Sources
What are Data Sources
Data sources read existing infrastructure that Terraform did not create. They are read-only, they never create, update, or delete anything.
# Read an existing VPC
data "aws_vpc" "existing" {
id = "vpc-12345678"
}
# Use it in a new resource
resource "aws_subnet" "new_subnet" {
vpc_id = data.aws_vpc.existing.id
cidr_block = "10.0.50.0/24"
}
Common Data Sources
# Current AWS account and region
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
# Available Availability Zones in current region
data "aws_availability_zones" "available" {
state = "available"
}
# Latest Amazon Linux 2023 AMI, never hardcode AMI IDs
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
# IAM policy document (generates JSON inline)
data "aws_iam_policy_document" "s3_read" {
statement {
effect = "Allow"
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.main.arn}/*"]
}
}
Lab 5, Dynamic AMI Lookup
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux.id
instance_type = "t3.micro"
}
This always uses the latest AMI, no hardcoded IDs that become outdated.
Knowledge Check
- What is the difference between a resource and a data source?
- Can a data source create or modify infrastructure?
- Why use a data source to look up an AMI instead of hardcoding the AMI ID?
- What does
data.aws_caller_identity.current.account_idreturn? - When would you use
data "aws_iam_policy_document"instead of a plain JSON string?