Day-13: Data sources in Terraform

Published: (December 7, 2025 at 01:43 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

What are Data Sources?

You can use data sources to fetch information about existing VPCs, subnets, AMIs, security groups, etc.

data "data_source_type" "data_source_name" {
  # Configuration arguments
}

Filters

filter {
  name   = "filter_name"
  values = ["value1", "value2"]
}

Creating an EC2 instance by fetching the AMI ID using Data Source and Subnet ID using Data Source

// main.tf

# Fetch the latest Ubuntu AMI
data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  owners = ["amazon"] # Canonical
}

# Fetch existing VPC by Name tag
data "aws_vpc" "selected" {
  filter {
    name   = "tag:Name"
    values = ["shared-primary-vpc"]
  }
}

# Fetch existing Subnet by Name tag within the selected VPC
data "aws_subnet" "selected" {
  filter {
    name   = "tag:Name"
    values = ["shared-primary-subnet"]
  }
  vpc_id = data.aws_vpc.selected.id
}

# Create an EC2 instance using the fetched AMI and Subnet
resource "aws_instance" "example" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  subnet_id     = data.aws_subnet.selected.id

  tags = {
    Name = "day-13-instance"
  }
}

Output

// outputs.tf
output "instance_id" {
  value = aws_instance.example.id
}

output "instance_public_ip" {
  value = aws_instance.example.public_ip
}

The Terraform configuration uses data sources to fetch the latest Ubuntu AMI and existing subnet information to create an EC2 instance.

Back to Blog

Related posts

Read more »

Terraform Data Source (AWS)

What Are Terraform Data Sources? A data source in Terraform is a read‑only lookup to an existing resource. Instead of creating something new, Terraform queries...

Day 13: Terraform Data Sources

Data Source Think of a data source like a phone directory with a username and phone number as key‑value pairs accessed via an API. Instead of hard‑coding value...

Day 8 - Terraform Meta-Arguments

Whenever we create any resource using Terraform—whether it is an S3 bucket, an EC2 instance, or a security group—we have to pass certain arguments that are spec...