Terraform Made Simple: Day 4: Data Sources & Locals
In Day 3 of this Terraform series, we learned how variables make configurations flexible.
But Terraform configs often need two more things:
- Fetching existing infrastructure data
- Computing reusable internal values
That’s exactly where Data Sources and Locals are used.
1. Data Sources:
A Data Source lets Terraform read information from your cloud provider without creating anything.
Instead of manually looking up values (like an AMI ID or VPC ID), Terraform can query the provider and fetch it automatically.
Common use cases:
- Get the latest AMI ID
- Fetch an existing VPC or subnet
- Read information about already created resources
Example:
data "aws_ami" "example"
- This tells Terraform to query AWS and return the latest AMI that matches the filter.
- That value can then be used directly in your resources.
- So instead of hardcoding an AMI ID, Terraform dynamically retrieves it for you.
2. Locals:
Locals are used to compute internal values inside your configuration. Think of them as helper variables.
They help you:
- Avoid repeating values
- Simplify complex expressions
- Keep configurations cleaner
Example:
- local.instance_type = "t3.micro"
- Now you can reuse it anywhere.
This keeps your configuration more readable and less repetitive.
3. How Terraform uses them:
Terraform follows a simple flow:
1️⃣ Declare data sources & locals
2️⃣ Fetch external data from providers
3️⃣ Compute internal values
4️⃣ Consume them in resources
To summarize:
- Data Sources → fetch external information
- Locals → compute internal values
That’s Day 4 of the Terraform series: Data Sources & Locals.
In Day 5, we’ll dive into Terraform resources by creating a VPC from scratch using Terraform.
Stay tuned!
Comments
Post a Comment