HashiCorp Terraform Associate (004) Question 98
Single answer4b Refer to resource attributes and create cross-resource referencesYour team is provisioning AWS networking with Terraform. A VPC and subnet are already defined in the same root module. You now need to create an EC2 instance that must be launched into that subnet and tagged with the VPC's CIDR block for troubleshooting. Which configuration correctly uses Terraform cross-resource references to achieve this without hardcoding values?
- A
resource "aws_instance" "app" { ami = "ami-1234567890abcdef0" instance_type = "t3.micro" subnet_id = aws_subnet.app.id
tags = { Name = "app-server" VPC_CIDR = aws_vpc.main.cidr_block } }
- B
resource "aws_instance" "app" { ami = "ami-1234567890abcdef0" instance_type = "t3.micro" subnet_id = "aws_subnet.app.id"
tags = { Name = "app-server" VPC_CIDR = "aws_vpc.main.cidr_block" } }
- C
resource "aws_instance" "app" { ami = "ami-1234567890abcdef0" instance_type = "t3.micro" subnet_id = var.aws_subnet.app.id
tags = { Name = "app-server" VPC_CIDR = var.aws_vpc.main.cidr_block } }
- D
resource "aws_instance" "app" { ami = "ami-1234567890abcdef0" instance_type = "t3.micro" subnet_id = data.aws_subnet.app.id
tags = { Name = "app-server" VPC_CIDR = data.aws_vpc.main.cidr_block } }
Show answer and explanation
Correct answer: A
Explanation
Terraform creates cross-resource relationships by referencing exported resource attributes with the syntax
- A. Correct.
Correct. This uses direct resource attribute references in the same root module: aws_subnet.app.id and aws_vpc.main.cidr_block. Terraform automatically builds the dependency graph from these references, so the instance depends on the subnet and can use the VPC attribute without hardcoding. This is the standard way to create cross-resource references between managed resources.
- B. Incorrect.
Incorrect. Quoting aws_subnet.app.id and aws_vpc.main.cidr_block turns them into literal strings, not Terraform expressions. Terraform would pass the exact text to the provider rather than the actual subnet ID or VPC CIDR block. A common misconception is that references should be wrapped in quotes like plain text values.
- C. Incorrect.
Incorrect. var.aws_subnet.app.id and var.aws_vpc.main.cidr_block are not valid ways to reference resources. The var object is only for input variables declared with variable blocks. Resource references use the pattern
. . , such as aws_subnet.app.id. This distractor reflects confusion between variables and managed resource attributes. - D. Incorrect.
Incorrect. data.aws_subnet.app.id and data.aws_vpc.main.cidr_block would only be valid if corresponding data sources were explicitly declared. In this scenario, the VPC and subnet are already managed resources in the same root module, so data sources are unnecessary. While data sources can read existing infrastructure, direct resource references are the appropriate cross-resource reference here.