Bird
Raised Fist0
Terraformcloud~5 mins

Querying existing resources in Terraform - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you need to use resources that already exist outside your Terraform setup. Querying existing resources lets you get their details so you can use them in your Terraform configuration without recreating them.
When you want to use an existing cloud network in your Terraform project without creating a new one.
When you need to attach a new server to an existing database managed outside Terraform.
When you want to reference an existing storage bucket for your application files.
When you want to get the ID of an existing virtual machine to add security rules.
When you want to import details of existing infrastructure to avoid duplication.
Config File - main.tf
main.tf
provider "aws" {
  region = "us-east-1"
}

# Data block to query an existing VPC by its ID

data "aws_vpc" "existing_vpc" {
  id = "vpc-0a1b2c3d4e5f6g7h"
}

# Use the queried VPC ID in a new subnet
resource "aws_subnet" "example_subnet" {
  vpc_id            = data.aws_vpc.existing_vpc.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
}

The provider block sets the AWS region.

The data "aws_vpc" "existing_vpc" block queries an existing VPC by its ID.

The aws_subnet resource creates a new subnet inside the existing VPC using the queried VPC ID.

Commands
Initializes the Terraform working directory and downloads the AWS provider plugin.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
Shows the execution plan. It will display the new subnet resource to be created using the existing VPC data.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_subnet.example_subnet will be created + resource "aws_subnet" "example_subnet" { + arn = (known after apply) + availability_zone = "us-east-1a" + cidr_block = "10.0.1.0/24" + id = (known after apply) + vpc_id = "vpc-0a1b2c3d4e5f6g7h" } Plan: 1 to add, 0 to change, 0 to destroy.
Applies the plan and creates the new subnet inside the existing VPC without manual approval.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_subnet.example_subnet: Creating... aws_subnet.example_subnet: Creation complete after 3s [id=subnet-1234abcd] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
→
-auto-approve - Skips manual approval prompt to apply changes immediately
Displays the current state of the infrastructure managed by Terraform, including the new subnet and the referenced existing VPC ID.
Terminal
terraform show
Expected OutputExpected
... # aws_subnet.example_subnet: resource "aws_subnet" "example_subnet" { availability_zone = "us-east-1a" cidr_block = "10.0.1.0/24" id = "subnet-1234abcd" vpc_id = "vpc-0a1b2c3d4e5f6g7h" } ...
Key Concept

If you remember nothing else from this pattern, remember: data blocks let you safely use existing resources without recreating them.

Common Mistakes
Trying to create a resource with the same name or ID as an existing resource without querying it first.
Terraform will try to create a duplicate resource, causing conflicts or errors.
Use a data block to query the existing resource and reference its ID instead of creating a new one.
Using incorrect or non-existent IDs in the data block.
Terraform will fail to find the resource and return an error during planning or applying.
Verify the exact resource ID from your cloud provider before using it in the data block.
Summary
Use data blocks in Terraform to query existing resources by their IDs or attributes.
Run 'terraform init' to prepare your environment and 'terraform plan' to see changes before applying.
Apply changes with 'terraform apply' to create new resources that use existing ones safely.

Practice

(1/5)
1. What is the main purpose of a data block in Terraform?
easy
A. To create new cloud resources from scratch
B. To delete resources that are no longer needed
C. To query and use existing resources created outside the current configuration
D. To define variables for user input

Solution

  1. Step 1: Understand the role of data blocks

    data blocks in Terraform are used to look up or query existing resources that were created outside the current Terraform configuration or by other means.
  2. Step 2: Differentiate from resource creation

    Unlike resource blocks that create new infrastructure, data blocks only read information without making changes.
  3. Final Answer:

    To query and use existing resources created outside the current configuration -> Option C
  4. Quick Check:

    Data blocks read existing resources = B [OK]
Hint: Data blocks read existing resources, not create them [OK]
Common Mistakes:
  • Confusing data blocks with resource creation
  • Thinking data blocks delete resources
  • Using data blocks to define variables
2. Which of the following is the correct syntax to query an existing AWS VPC by its ID using a data block?
easy
A. data "aws_vpc" "example" { id = "vpc-123456" }
B. resource "aws_vpc" "example" { id = "vpc-123456" }
C. data "aws_vpc" "example" { vpc_id = "vpc-123456" }
D. data "aws_vpc" "example" { name = "vpc-123456" }

Solution

  1. Step 1: Identify correct data block syntax

    The correct syntax uses data followed by the provider resource type and a name, then inside the block the attribute id is used to specify the VPC ID.
  2. Step 2: Check attribute correctness

    The attribute to specify the VPC ID is id, not vpc_id or name.
  3. Final Answer:

    data "aws_vpc" "example" { id = "vpc-123456" } -> Option A
  4. Quick Check:

    Use id attribute in data block = A [OK]
Hint: Use 'id' attribute inside data block to query by resource ID [OK]
Common Mistakes:
  • Using resource block instead of data block
  • Using wrong attribute names like vpc_id
  • Confusing resource creation syntax with data query
3. Given this Terraform data block:
data "aws_subnet" "selected" {
  filter {
    name   = "tag:Name"
    values = ["public-subnet"]
  }
}

What will data.aws_subnet.selected.id return?
medium
A. The ID of the subnet tagged with Name=public-subnet
B. A list of all subnet IDs in the AWS account
C. An error because filter is not allowed in data blocks
D. The name of the subnet instead of the ID

Solution

  1. Step 1: Understand the filter block in data source

    The filter block selects resources matching the tag Name=public-subnet.
  2. Step 2: Identify the returned attribute

    data.aws_subnet.selected.id returns the ID of the matched subnet, not a list or name.
  3. Final Answer:

    The ID of the subnet tagged with Name=public-subnet -> Option A
  4. Quick Check:

    Filter selects subnet by tag, id returns its ID = D [OK]
Hint: Filter selects resource; .id returns its ID [OK]
Common Mistakes:
  • Thinking filter returns multiple resources
  • Assuming .id returns name or list
  • Believing filter is invalid in data blocks
4. You wrote this data block to query an existing AWS security group:
data "aws_security_group" "example" {
  name = "my-sg"
}

But Terraform returns an error: "Multiple security groups found with name 'my-sg'". What is the best fix?
medium
A. Remove the name attribute to query all security groups
B. Add a filter block with more specific criteria to narrow the search
C. Change data to resource to create a new security group
D. Rename the security group in AWS to have a unique name

Solution

  1. Step 1: Understand the error cause

    The error means multiple security groups share the same name, so Terraform cannot pick one.
  2. Step 2: Narrow the query with filters

    Adding a filter block with more attributes (like VPC ID) helps select exactly one security group.
  3. Final Answer:

    Add a filter block with more specific criteria to narrow the search -> Option B
  4. Quick Check:

    Use filters to avoid multiple matches = C [OK]
Hint: Use filters to narrow data queries when duplicates exist [OK]
Common Mistakes:
  • Switching to resource block instead of filtering
  • Removing name attribute causing ambiguous query
  • Changing AWS resource names unnecessarily
5. You want to use an existing AWS IAM role in your Terraform configuration, but only know its ARN. Which is the best way to query this role using a data block?
hard
A. Use data "aws_iam_role" "existing" { id = "my-role" }
B. Use data "aws_iam_role" "existing" { name = "my-role" } and ignore ARN
C. Use resource "aws_iam_role" "existing" { arn = "arn:aws:iam::123456789012:role/my-role" }
D. Use data "aws_iam_role" "existing" { arn = "arn:aws:iam::123456789012:role/my-role" }

Solution

  1. Step 1: Identify correct attribute to query by ARN

    The aws_iam_role data source supports querying by arn attribute to find the exact role.
  2. Step 2: Avoid using resource block or wrong attributes

    Using resource block tries to create a new role, which is incorrect. Using name may fail if multiple roles share the name. id is not a valid attribute here.
  3. Final Answer:

    Use data "aws_iam_role" "existing" { arn = "arn:aws:iam::123456789012:role/my-role" } -> Option D
  4. Quick Check:

    Query IAM role by ARN using data block = A [OK]
Hint: Query IAM role by ARN attribute in data block [OK]
Common Mistakes:
  • Using resource block instead of data block
  • Querying by name when ARN is known
  • Using invalid attribute 'id' for IAM role
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard