0
0
Terraformcloud~30 mins

Why data sources query existing infrastructure in Terraform - See It in Action

Choose your learning style9 modes available
Using Terraform Data Sources to Query Existing Infrastructure
📖 Scenario: You are managing cloud infrastructure using Terraform. Sometimes, you need to use information about resources that already exist outside your current Terraform configuration. For example, you want to find the ID of an existing virtual network or security group to connect new resources to it.
🎯 Goal: Learn how to use Terraform data sources to query existing infrastructure resources and use their attributes in your Terraform configuration.
📋 What You'll Learn
Create a Terraform data source block to query an existing AWS VPC by its ID
Create a variable to hold the VPC ID
Use the data source's attributes to configure a new subnet resource
Add a tag to the subnet referencing the VPC's name
💡 Why This Matters
🌍 Real World
In real cloud projects, you often need to connect new resources to existing networks or security groups. Terraform data sources let you safely reference these existing resources without recreating them.
💼 Career
Cloud engineers and DevOps professionals use data sources to manage hybrid infrastructure setups and avoid conflicts by querying existing resources before creating new ones.
Progress0 / 4 steps
1
Create a variable for the existing VPC ID
Create a Terraform variable called existing_vpc_id of type string with a default value of "vpc-0abcd1234efgh5678".
Terraform
Need a hint?

Use the variable block with type = string and set the default to the exact VPC ID.

2
Add a data source to query the existing VPC
Add a Terraform data block named existing_vpc of type aws_vpc that uses the variable existing_vpc_id to look up the VPC by its ID.
Terraform
Need a hint?

Use a data block with type aws_vpc and set id = var.existing_vpc_id.

3
Create a subnet using the existing VPC data source
Create a Terraform resource block named example_subnet of type aws_subnet. Use the VPC ID from the data source data.aws_vpc.existing_vpc.id for the vpc_id attribute. Set the cidr_block to "10.0.1.0/24".
Terraform
Need a hint?

Use the resource block for aws_subnet and reference the VPC ID from the data source.

4
Add a tag to the subnet using the VPC's name from the data source
Add a tags block inside the aws_subnet.example_subnet resource. Set the tag Name to the VPC's name using data.aws_vpc.existing_vpc.tags["Name"].
Terraform
Need a hint?

Inside the resource block, add a tags map and set Name to the VPC's name from the data source.