DEV Community

Cover image for πŸš€ Terraform Day 13: Data Sources β€” Stop Hardcoding, Start Automating
Jeeva
Jeeva

Posted on

πŸš€ Terraform Day 13: Data Sources β€” Stop Hardcoding, Start Automating

πŸ”Ή 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)