0
0
Terraformcloud~30 mins

Querying existing resources in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Querying Existing Resources with Terraform
📖 Scenario: You are managing cloud infrastructure using Terraform. You want to reuse an existing virtual network instead of creating a new one. This helps avoid duplication and keeps your setup clean.
🎯 Goal: Learn how to query an existing resource in Terraform and use its attributes in your configuration.
📋 What You'll Learn
Use Terraform to query an existing virtual network by its name
Use the data source attributes like name and ID in your configuration
Use the queried virtual network name to create a new subnet inside the existing virtual network
Ensure the Terraform configuration is valid and deployable
💡 Why This Matters
🌍 Real World
In real cloud projects, reusing existing resources avoids duplication and reduces costs. Querying existing resources helps integrate new infrastructure with what is already deployed.
💼 Career
Cloud engineers and DevOps professionals often need to reference existing infrastructure in Terraform to maintain and extend cloud environments safely and efficiently.
Progress0 / 4 steps
1
Create a data block to query the existing virtual network
Write a Terraform data block named existing_vnet to query the Azure virtual network resource with the name my-vnet in the resource group my-resource-group.
Terraform
Need a hint?

Use the data block to look up existing resources by specifying their exact name and resource group.

2
Create a variable to hold the subnet name
Create a Terraform variable named subnet_name with the default value my-subnet.
Terraform
Need a hint?

Define a variable block with the name subnet_name and set its default value.

3
Create a subnet resource using the queried virtual network ID
Create a Terraform resource block named azurerm_subnet with the name my_subnet. Use the variable subnet_name for the subnet name, the virtual network name from data.azurerm_virtual_network.existing_vnet.name, and set the address prefix to 10.0.1.0/24.
Terraform
Need a hint?

Use the data.azurerm_virtual_network.existing_vnet.name to link the subnet to the existing virtual network.

4
Add the provider block for AzureRM
Add the Terraform provider block for azurerm with features {} to enable the Azure provider.
Terraform
Need a hint?

The provider block is required to tell Terraform which cloud to work with.