0
0
TerraformConceptBeginner · 4 min read

What is Data Source in Terraform: Explanation and Example

In Terraform, a data source lets you fetch information from existing infrastructure or external systems to use in your configuration. It helps you read data without creating or changing resources, making your setup more dynamic and connected.
⚙️

How It Works

Think of a data source in Terraform like looking up information in a phone book before making a call. Instead of creating a new contact, you just find the existing phone number you need. Similarly, Terraform's data sources let you read details about resources that already exist outside your current setup.

This means you can gather information such as IDs, names, or configurations from cloud providers or other systems and use that data to configure your own resources. It keeps your infrastructure code flexible and avoids duplication.

💻

Example

This example shows how to use a data source to get the latest Amazon Linux 2 AMI ID from AWS, then use it to launch an EC2 instance.

terraform
provider "aws" {
  region = "us-east-1"
}

data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

resource "aws_instance" "example" {
  ami           = data.aws_ami.amazon_linux.id
  instance_type = "t2.micro"
}
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: aws_instance.example.id = "i-0abcd1234efgh5678"
🎯

When to Use

Use data sources when you need to reference existing resources or information that Terraform does not manage directly. For example:

  • Getting the ID of a shared network or security group created outside your Terraform code.
  • Fetching the latest version of an operating system image to launch virtual machines.
  • Reading configuration details from cloud services or external APIs to use in your infrastructure.

This helps keep your infrastructure code up-to-date and consistent with the real environment.

Key Points

  • Data sources read existing information without creating or changing resources.
  • They make Terraform configurations more dynamic and connected to real infrastructure.
  • Commonly used to fetch IDs, names, or settings from cloud providers or external systems.
  • They help avoid hardcoding values and reduce duplication.

Key Takeaways

A data source in Terraform fetches existing information without creating resources.
Use data sources to get dynamic values like IDs or latest images from your cloud provider.
They help keep your infrastructure code flexible and consistent with real-world setups.
Data sources avoid hardcoding and duplication by reading live data.
They are essential when referencing resources managed outside your Terraform code.