Implicit Dependencies
When one resource references another's attributes, Terraform automatically creates them in the right order.
Resources often depend on each other — a server needs a security group, a subnet needs a VPC. Terraform discovers these relationships automatically.
Implicit dependencies
When resource A references an attribute of resource B (like aws_vpc.main.id), Terraform knows B must be created first. This is an implicit dependency, and it is the preferred way to express ordering.
The dependency graph
Terraform builds a graph of all these references and creates resources in parallel where possible, respecting the required order.
Example
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
# This subnet references the VPC, so Terraform
# creates the VPC first, then the subnet.
resource "aws_subnet" "app" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}When to use it
- Terraform automatically creates a VPC before a subnet because the subnet references aws_vpc.main.id, without the engineer specifying any ordering.
- A security group is created before the EC2 instance because the instance block includes aws_security_group.web.id in its vpc_security_group_ids list.
- An IAM role policy attachment waits for both the role and the policy to exist because it references both resources' id attributes implicitly.
More examples
Subnet depends on VPC implicitly
The subnet references aws_vpc.main.id so Terraform automatically creates the VPC first without any explicit ordering.
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id # implicit dependency
cidr_block = "10.0.1.0/24"
}Security group before instance
The instance references the security group's id, so Terraform builds the dependency graph and creates the SG first.
resource "aws_security_group" "web" {
name = "web-sg"
vpc_id = aws_vpc.main.id
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.web.id] # implicit dep
}Chained three-resource dependency
Creates a three-level implicit chain: VPC -> subnet -> instance, all ordered automatically from attribute references.
resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" }
resource "aws_subnet" "app" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.2.0/24"
}
resource "aws_instance" "app" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
subnet_id = aws_subnet.app.id # depends on subnet -> vpc
}
Discussion