πΉ What Is a Terraform Data Source?
A data source allows Terraform to:
Query existing resources
Fetch live information from AWS
Use that data inside resource definitions
Unlike resources:
β Data sources do not create anything
β
They only read existing infrastructure
1οΈβ£ Why You Should Never Hardcode AMI IDs
Problem
AMI IDs:
Are region-specific
Change frequently
Become outdated and insecure
Hardcoding them breaks automation.
Solution
Use an AMI data source.
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
β Always fetches the latest AMI
β No manual updates required
2οΈβ£ Using Data Source for Existing VPC
In shared environments, you should not recreate VPCs.
Instead, query them.
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["shared-vpc"]
}
}
This selects the VPC based on tags.
3οΈβ£ Using Data Source for Existing Subnet
Subnets are often tied to a VPC and environment.
data "aws_subnet" "public" {
filter {
name = "tag:Name"
values = ["public-subnet-1"]
}
filter {
name = "vpc-id"
values = [data.aws_vpc.main.id]
}
}
β Ensures correct subnet
β Avoids ambiguity in large AWS accounts
4οΈβ£ Using Data Sources Inside a Resource
Once data is fetched, it can be referenced like variables.
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux.id
instance_type = "t2.micro"
subnet_id = data.aws_subnet.public.id
}
Terraform now:
Reads existing infrastructure
Creates only what is needed
Avoids duplication and mistakes
π Conclusion
Day 13 is a major milestone in Terraform learning.
Youβve now learned how to:
Integrate Terraform with existing AWS infrastructure
Build dynamic, reusable, automation-ready configurations
Avoid fragile, hardcoded values
Follow enterprise-grade Terraform practices
Terraform data sources are mandatory knowledge for:
Real-world projects
Shared AWS accounts
Scalable DevOps workflows
_
π Next Steps
Explore more AWS data sources (SGs, IAM, Route53)
Combine data sources with modules
Use data sources in CI/CD pipelines
Practice filtering strategies using tags
_
Next:
π Day 14 β Terraform State & Remote State Deep Dive π
Happy Terraforming! π
Top comments (0)