π― Goal: Stop guessing AMI IDs or subnet IDs β query AWS dynamically and build portable, environment-agnostic configs.
β Youβll master:
- β
data "aws_ami"β Get latest AMIs (no moreami-0c7217cdde317cfec!)- β
data "aws_vpc"+data "aws_subnet"β Reuse shared infrastructure- β Filtering with
tags,name,cidr_block- β Safe, read-only discovery (no
terraform applyside effects)
β Without data sources:
- Hardcoded
ami = "ami-0c721..."β breaks when AMI rotates- Manual
subnet_id = "subnet-abc123"β fails in staging/prod- Copy-paste VPC IDs across teams β configuration drift
β With data sources:
β Infrastructure that self-discovers dependencies
β Truly portable configs (dev β staging β prod)
β Zero manual lookup β fully automated
π‘ Golden Rule:
βIf it already exists in AWS β
datait. If youβre creating it βresourceit.β
| Data Source | Use Case | Key Filter Attributes |
|---|---|---|
aws_ami |
Find OS images | owners, name, virtualization_type, root_device_type |
aws_vpc |
Reuse shared VPCs | tags, cidr_block, default |
aws_subnet |
Target specific subnets | vpc_id, availability_zone, tags, cidr_block |
aws_iam_role |
Attach to existing roles | name |
aws_ssm_parameter |
Read config from SSM | name |
π― Critical:
datablocks are read-only β no side effects onapply- Values resolved during
terraform planβ fully predictable
Name = "shared-prod-vpc" (already exists)Name = "app-subnet-a", "app-subnet-b" (in us-east-1a, us-east-1b)