Objective
By the end of this lab, you will have:
- Used data sources to read AWS metadata.
- Referenced the data sources in resources.
- Verified the resources are created with the data source attributes.
Requirements
- A Linux or macOS workstation with shell access.
- The Terraform CLI 1.9.x or later installed.
- An AWS account (or modify the examples for a local provider).
Scenario
You have a configuration that needs to read AWS metadata (the current account, the current region, the available AZs) and use that metadata in resources. The data sources are the way to read this metadata without hard-coding it.
Tasks
Task 1: Create the working directory
mkdir -p ~/rb-data-sources-lab
cd ~/rb-data-sources-lab
Task 2: Write the configuration
Create main.tf:
terraform {
required_version = ">= 1.9.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
data "aws_availability_zones" "available" {
state = "available"
}
resource "aws_subnet" "main" {
vpc_id = "vpc-12345"
cidr_block = "10.0.1.0/24"
availability_zone = data.aws_availability_zones.available.names[0]
tags = {
Name = "subnet-from-data-source"
Account = data.aws_caller_identity.current.account_id
Region = data.aws_region.current.name
CreatedBy = "terraform"
}
}
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
output "region" {
value = data.aws_region.current.name
}
output "availability_zones" {
value = data.aws_availability_zones.available.names
}
Task 3: Apply the configuration
terraform init
terraform apply
The apply creates the subnet using the data source attributes.
Task 4: Verify the outputs
terraform output
The output shows the account ID, region, and availability zones.
Task 5: Verify the resource
aws ec2 describe-subnets --filters "Name=tag:Name,Values=subnet-from-data-source"
The subnet has the correct tags.
Validation
The lab is successful if:
- The data sources read the AWS metadata.
- The subnet uses the data source attributes.
- The tags are set correctly.
Expected Outcome
The subnet is created with the correct tags. The outputs show the AWS metadata.
Cleanup
cd ~/rb-data-sources-lab
terraform destroy
rm -rf .terraform .terraform.lock.hcl terraform.tfstate*
The main.tf is the only artefact worth keeping.
What You Learned
You learned the data source pattern:
- Data sources read infrastructure. The provider returns the attributes.
- Data sources are referenced in resources and outputs. The attributes are available to the configuration.
- Data sources are not in the state. The state has the resource attributes, not the data source attributes.
- Data sources must be safe to read. The provider may make API calls.