0
0
Terraformcloud~30 mins

AMI lookup data source example in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
AMI lookup data source example
📖 Scenario: You are setting up a cloud server and need to find the latest Amazon Machine Image (AMI) for Ubuntu 22.04 in the AWS region you are working in.
🎯 Goal: Create a Terraform configuration that uses the aws_ami data source to look up the latest Ubuntu 22.04 AMI and then launch an EC2 instance using that AMI.
📋 What You'll Learn
Use the aws_ami data source to find the latest Ubuntu 22.04 AMI
Filter the AMI by owner 099720109477 (official Ubuntu owner)
Launch an EC2 instance using the found AMI
Use the aws_instance resource with a simple instance type
💡 Why This Matters
🌍 Real World
Finding the latest AMI ensures your cloud servers use up-to-date and secure operating system images.
💼 Career
Cloud engineers often use data sources in Terraform to dynamically find resources like AMIs, making infrastructure code reusable and reliable.
Progress0 / 4 steps
1
Set up AWS provider
Write a Terraform block to configure the AWS provider with the region us-east-1. Create a variable called region and set it to "us-east-1". Then configure the provider to use this variable.
Terraform
Need a hint?

Use a variable block to define region and then use it inside the provider block.

2
Add AMI lookup data source
Add a Terraform data block named ubuntu using the aws_ami data source. Filter for the latest Ubuntu 22.04 AMI by setting most_recent = true, owners = ["099720109477"], and a filter with name = "name" and values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"].
Terraform
Need a hint?

Use the aws_ami data source with filters to find the latest Ubuntu 22.04 AMI.

3
Create EC2 instance resource
Add an aws_instance resource named web. Use the AMI ID from the data source data.aws_ami.ubuntu.id. Set the instance type to t2.micro.
Terraform
Need a hint?

Use the AMI ID from the data source to launch the EC2 instance.

4
Add tags to EC2 instance
Add a tags block inside the aws_instance.web resource. Set the tag Name to "UbuntuServer".
Terraform
Need a hint?

Add a tags block with the Name key inside the EC2 instance resource.