Bird
Raised Fist0
Terraformcloud~10 mins

Querying existing resources in Terraform - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Querying existing resources
Start Terraform Config
↓
Define data block
↓
Terraform reads state
↓
Look up existing resource
↓
Extract attributes
↓
Use attributes in config
↓
Apply or plan
↓
Output shows queried data
Terraform uses a data block to look up existing resources in the cloud, then extracts their details to use in your configuration.
Execution Sample
Terraform
data "aws_vpc" "selected" {
  filter {
    name   = "tag:Name"
    values = ["main-vpc"]
  }
}

output "vpc_id" {
  value = data.aws_vpc.selected.id
}
This code queries an existing AWS VPC by its tag name and outputs its ID.
Process Table
StepActionTerraform StateResult
1Start Terraform planState file loadedReady to query data
2Read data block aws_vpc.selectedLook up VPC with tag Name=main-vpcFinds VPC with ID vpc-123abc
3Extract attribute idVPC data loadedid = vpc-123abc
4Prepare output vpc_idOutput references data.aws_vpc.selected.idOutput value set to vpc-123abc
5Show plan or applyOutputs readyvpc_id = vpc-123abc
6EndNo changes to infrastructureExecution complete
💡 Terraform finishes after reading existing resource and preparing output; no infrastructure changes made.
Status Tracker
VariableStartAfter Step 2After Step 3Final
data.aws_vpc.selected.idundefinedvpc-123abcvpc-123abcvpc-123abc
output.vpc_id.valueundefinedundefinedvpc-123abcvpc-123abc
Key Moments - 3 Insights
Why does Terraform not create a new VPC when using a data block?
Because data blocks only read existing resources from the cloud or state; they do not create or modify resources. See execution_table step 2 and 6.
How does Terraform find the correct existing resource?
Terraform uses filters inside the data block to match resource attributes, like tags. In the example, it filters by tag Name=main-vpc (execution_table step 2).
Can you use the data block output in other resources?
Yes, the attributes extracted by the data block can be referenced elsewhere in your config to connect resources. This is shown by output referencing data.aws_vpc.selected.id (execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what does Terraform do?
ACreates a new VPC with tag main-vpc
BLooks up an existing VPC with tag main-vpc
CDeletes the VPC with tag main-vpc
DOutputs the VPC ID without lookup
💡 Hint
Refer to execution_table row 2 under Action and Result columns.
At which step does Terraform set the output value to the VPC ID?
AStep 4
BStep 3
CStep 1
DStep 6
💡 Hint
Check execution_table row 4 under Result column.
If the filter in the data block does not match any VPC, what happens?
ATerraform creates a new VPC automatically
BTerraform skips the data block silently
CTerraform errors out during plan
DTerraform outputs a null value
💡 Hint
Data blocks require existing resources; no match causes an error during plan.
Concept Snapshot
Terraform data blocks let you query existing cloud resources.
Use filters to find the resource you want.
Extract attributes like IDs to use elsewhere.
Data blocks do not create or change resources.
Outputs can show queried data.
Errors occur if no matching resource is found.
Full Transcript
Terraform uses data blocks to query existing resources in your cloud environment. You define a data block with filters to find the resource you want, such as a VPC with a specific tag. Terraform reads the current state and cloud to find this resource and extracts its attributes. These attributes can then be used in outputs or other resources. Data blocks do not create or modify resources; they only read existing ones. If no resource matches the filters, Terraform will error during planning. This process helps you connect new infrastructure to existing components 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