0
0
Terraformcloud~30 mins

Data source block syntax in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Data source block syntax
📖 Scenario: You are setting up a Terraform configuration to retrieve information about an existing AWS AMI (Amazon Machine Image) to use in your infrastructure.
🎯 Goal: Build a Terraform configuration that uses a data source block to fetch the latest Amazon Linux 2 AMI ID in the us-east-1 region.
📋 What You'll Learn
Create a data block named aws_ami with the name amazon_linux
Configure the data source to filter for the latest Amazon Linux 2 AMI
Use the owners attribute to specify Amazon's owner ID
Add an output to display the AMI ID
💡 Why This Matters
🌍 Real World
Terraform data sources let you query existing cloud resources to use their information in your infrastructure setup without recreating them.
💼 Career
Understanding data source blocks is essential for cloud engineers and DevOps professionals to integrate existing resources into Terraform-managed infrastructure.
Progress0 / 4 steps
1
Create the data source block skeleton
Create a Terraform data block named aws_ami with the name amazon_linux.
Terraform
Need a hint?

Start with data "aws_ami" "amazon_linux" { } to define the data source block.

2
Add filter and owners attributes
Inside the data "aws_ami" "amazon_linux" block, add a filter block with name = "name" and values = ["amzn2-ami-hvm-*-x86_64-gp2"]. Also add owners = ["137112412989"] to specify Amazon's owner ID.
Terraform
Need a hint?

Use a filter block with name and values, and add owners outside the filter.

3
Add most_recent attribute
Add the attribute most_recent = true inside the data "aws_ami" "amazon_linux" block to get the latest AMI.
Terraform
Need a hint?

Set most_recent = true to ensure the latest AMI is selected.

4
Add output for the AMI ID
Create an output block named ami_id that outputs the value of data.aws_ami.amazon_linux.id.
Terraform
Need a hint?

Use output "ami_id" with value = data.aws_ami.amazon_linux.id to show the AMI ID.