Terraform Tutorial — Data Sources Practice Exercises

1 minute read

Practice using data sources to read existing infrastructure.


Exercise 1: Latest AMI

Task: Write a data source that finds the latest Amazon Linux 2023 AMI owned by Amazon.

Answer
data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

Reference it with data.aws_ami.amazon_linux.id.


Exercise 2: Existing VPC

Task: Write a data source that finds a VPC with the tag Environment = "production". Then create a subnet in that VPC.

Answer
data "aws_vpc" "prod" {
  tags = {
    Environment = "production"
  }
}

resource "aws_subnet" "app" {
  vpc_id     = data.aws_vpc.prod.id
  cidr_block = "10.0.100.0/24"

  tags = {
    Name = "app-subnet"
  }
}

Exercise 3: Dynamic Availability Zones

Task: Write code that creates one subnet per available AZ in the current region, using dynamic AZ names.

Answer
data "aws_availability_zones" "available" {
  state = "available"
}

resource "aws_subnet" "public" {
  count             = length(data.aws_availability_zones.available.names)
  vpc_id            = aws_vpc.main.id
  cidr_block        = cidrsubnet("10.0.0.0/16", 8, count.index)
  availability_zone = data.aws_availability_zones.available.names[count.index]

  tags = {
    Name = "public-${data.aws_availability_zones.available.names[count.index]}"
  }
}

Exercise 4: Data Source vs Resource

Task: Explain when you would use data "aws_vpc" vs resource "aws_vpc".

Answer
  • Use resource "aws_vpc" when you want Terraform to create and manage the VPC. Terraform will create it on apply and destroy it on destroy.

  • Use data "aws_vpc" when the VPC already exists and was created outside your Terraform config (by another team, another Terraform project, or manually). You just want to reference its ID, CIDR, or other attributes.


Chapter Summary

In this chapter, you learned:

  • Data sources read existing infrastructure (read-only)
  • The data block with filter, tags, most_recent, and owners
  • Common AWS data sources: aws_ami, aws_vpc, aws_availability_zones, aws_caller_identity, aws_region
  • Filter logic: AND between filter blocks, OR within values
  • Combining data sources with resources for dynamic, portable configurations

Next up: Modules — organizing configuration into reusable components.


← Combining Data Sources with Resources Modules →