Bird
Raised Fist0
Terraformcloud~15 mins

Resource dependencies (implicit) in Terraform - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Resource dependencies (implicit)
What is it?
Resource dependencies in Terraform are the relationships that tell Terraform which resources must be created or updated before others. Implicit dependencies happen automatically when one resource uses the output or attribute of another resource. This helps Terraform know the correct order to build or change infrastructure without extra instructions.
Why it matters
Without resource dependencies, Terraform wouldn't know the right order to create or update resources. This could cause errors, like trying to use a network before it exists. Implicit dependencies make infrastructure automation safer and smoother, saving time and avoiding costly mistakes.
Where it fits
Before learning implicit dependencies, you should understand basic Terraform resources and how to write configurations. After this, you can learn explicit dependencies and advanced dependency management to control complex infrastructure builds.
Mental Model
Core Idea
Terraform automatically figures out which resources depend on others by seeing when one resource uses another's data or attributes.
Think of it like...
It's like baking a cake where you automatically know you must mix the batter before putting it in the oven because the recipe calls for the batter first.
┌─────────────┐       ┌─────────────┐
│ Resource A  │──────▶│ Resource B  │
│ (network)   │       │ (server)    │
└─────────────┘       └─────────────┘

Terraform sees Resource B uses Resource A's info, so it builds A first.
Build-Up - 7 Steps
1
FoundationWhat are Terraform resources
🤔
Concept: Terraform resources are the building blocks of infrastructure, representing things like servers or networks.
In Terraform, you write blocks called resources to tell it what to create. For example, a resource can be a virtual machine or a storage bucket. Each resource has a type and a name, and you set its properties.
Result
You can define infrastructure pieces in code that Terraform understands.
Knowing what resources are is essential because dependencies connect these pieces to build working infrastructure.
2
FoundationHow Terraform plans changes
🤔
Concept: Terraform creates a plan by comparing current infrastructure with desired state and figuring out what to add, change, or remove.
When you run 'terraform plan', Terraform checks what exists and what you want. It then decides the order to create or update resources based on dependencies it knows.
Result
Terraform shows a safe plan to change infrastructure without breaking things.
Understanding planning helps see why dependencies matter to avoid errors during changes.
3
IntermediateImplicit dependencies explained
🤔Before reading on: do you think Terraform needs you to always tell it which resources depend on others? Commit to your answer.
Concept: Terraform automatically detects dependencies when one resource uses another's attributes or outputs.
If a resource uses a value from another resource, like a server needing a network ID, Terraform knows the server depends on the network. This is implicit dependency because you didn't tell Terraform explicitly; it figured it out from your code.
Result
Terraform builds resources in the correct order without extra instructions.
Understanding implicit dependencies shows how Terraform reduces manual work and errors by reading your resource connections.
4
IntermediateExamples of implicit dependencies
🤔Before reading on: do you think referencing a resource's attribute always creates a dependency? Commit to your answer.
Concept: Using attributes from one resource inside another creates an implicit dependency.
Example: a virtual machine resource uses the subnet ID from a network resource. Terraform sees this and knows to create the network first. Even if you don't write 'depends_on', Terraform orders them correctly.
Result
Resources build in the right sequence automatically.
Knowing how references create dependencies helps you write clearer, safer Terraform code.
5
IntermediateWhen implicit dependencies are not enough
🤔Before reading on: do you think all dependencies can be detected automatically by Terraform? Commit to your answer.
Concept: Some dependencies are not visible through resource attributes and need explicit declaration.
If a resource depends on another without using its outputs, Terraform won't know. For example, a script that must run after a server is ready but doesn't use its attributes. Here, you must use 'depends_on' to tell Terraform the order.
Result
You learn when to add explicit dependencies to avoid errors.
Recognizing implicit dependency limits prevents subtle bugs in complex infrastructure.
6
AdvancedHow Terraform builds the dependency graph
🤔Before reading on: do you think Terraform builds a map of all resource connections before applying changes? Commit to your answer.
Concept: Terraform creates a graph of resources and their dependencies to plan the correct order of operations.
Terraform scans your configuration and builds a graph where nodes are resources and edges are dependencies. It then uses this graph to decide which resources to create, update, or delete first, ensuring no resource is used before it exists.
Result
Terraform applies changes safely and efficiently.
Understanding the dependency graph explains why Terraform can handle complex infrastructure reliably.
7
ExpertSurprises in implicit dependency detection
🤔Before reading on: do you think Terraform always detects dependencies inside all expressions and functions? Commit to your answer.
Concept: Terraform detects dependencies only when resource attributes are directly referenced; some indirect uses may not create dependencies.
If you use resource data inside complex expressions, or pass resource IDs through variables or locals without direct reference, Terraform might miss the dependency. This can cause resources to build in the wrong order. Experts carefully check references and sometimes add explicit dependencies to fix this.
Result
You avoid subtle bugs caused by hidden or indirect dependencies.
Knowing Terraform's detection limits helps prevent hard-to-debug infrastructure errors.
Under the Hood
Terraform parses all resource blocks and expressions to find references to other resources' attributes. It builds a directed graph where each node is a resource and edges represent dependencies. This graph guides the order of creation, update, or deletion. During apply, Terraform walks this graph to ensure no resource is used before it exists.
Why designed this way?
Terraform was designed to automate infrastructure safely and efficiently. Implicit dependencies reduce manual work and errors by letting Terraform infer order from natural references. Explicit dependencies exist for cases where references are not visible. This balance keeps configurations simple yet powerful.
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│ Resource A  │──────▶│ Resource B  │──────▶│ Resource C  │
│ (network)   │       │ (server)    │       │ (database)  │
└─────────────┘       └─────────────┘       └─────────────┘

Terraform builds this graph to know the order: A before B before C.
Myth Busters - 4 Common Misconceptions
Quick: Do you think Terraform always needs 'depends_on' to order resources? Commit yes or no.
Common Belief:Terraform requires explicit 'depends_on' for all resource dependencies.
Tap to reveal reality
Reality:Terraform automatically detects dependencies when one resource uses another's attributes, so 'depends_on' is often unnecessary.
Why it matters:Adding unnecessary 'depends_on' makes configurations verbose and harder to maintain.
Quick: Do you think referencing a resource inside a variable or local always creates a dependency? Commit yes or no.
Common Belief:Any use of a resource's output inside variables or locals creates implicit dependencies.
Tap to reveal reality
Reality:Terraform only detects dependencies if the resource attribute is directly referenced in resource arguments; indirect use in variables or locals may not create dependencies.
Why it matters:Missing dependencies can cause resources to build in the wrong order, leading to errors.
Quick: Do you think Terraform's dependency graph includes data sources the same way as resources? Commit yes or no.
Common Belief:Data sources always create dependencies like resources do.
Tap to reveal reality
Reality:Data sources are read-only and do not create dependencies that affect resource creation order unless explicitly referenced.
Why it matters:Misunderstanding this can cause confusion about why some resources build before data sources.
Quick: Do you think Terraform can detect dependencies inside all expressions and functions? Commit yes or no.
Common Belief:Terraform detects dependencies inside any expression or function that uses resource attributes.
Tap to reveal reality
Reality:Terraform only detects dependencies when resource attributes are directly referenced; complex expressions or functions may hide dependencies.
Why it matters:This can cause subtle bugs where resources build in the wrong order.
Expert Zone
1
Terraform's dependency graph is recalculated on every plan, so changes in references immediately affect resource order.
2
Implicit dependencies do not cover lifecycle hooks or provisioners, which may require explicit ordering.
3
Modules can hide dependencies inside, so understanding how outputs connect modules is key for complex setups.
When NOT to use
Implicit dependencies are not enough when resources depend on side effects, external scripts, or lifecycle events. In these cases, use explicit 'depends_on' or external orchestration tools.
Production Patterns
In production, teams rely on implicit dependencies for most resources to keep code clean, adding explicit dependencies only for edge cases like ordering scripts or manual steps. They also use modules to encapsulate dependencies and outputs clearly.
Connections
Directed Acyclic Graphs (DAGs)
Terraform's dependency graph is a DAG representing resource order.
Understanding DAGs from computer science helps grasp how Terraform ensures no cycles and correct build order.
Build systems (e.g., Makefiles)
Both use dependency graphs to decide build order automatically.
Knowing how build tools manage dependencies clarifies Terraform's approach to infrastructure orchestration.
Project management task dependencies
Like tasks that must finish before others start, Terraform resources depend on each other.
Seeing resource dependencies as task dependencies helps plan and avoid bottlenecks in infrastructure projects.
Common Pitfalls
#1Assuming all dependencies are detected automatically.
Wrong approach:resource "null_resource" "example" { provisioner "local-exec" { command = "echo done" } } resource "null_resource" "dependent" { provisioner "local-exec" { command = "echo depends" } } # No depends_on used
Correct approach:resource "null_resource" "example" { provisioner "local-exec" { command = "echo done" } } resource "null_resource" "dependent" { depends_on = [null_resource.example] provisioner "local-exec" { command = "echo depends" } }
Root cause:Implicit dependencies only detect references in resource arguments, not side effects or provisioners.
#2Using variables or locals to pass resource IDs without direct reference.
Wrong approach:variable "subnet_id" {} resource "aws_instance" "web" { subnet_id = var.subnet_id } # subnet_id variable set outside referencing resource
Correct approach:resource "aws_subnet" "main" { # subnet config } resource "aws_instance" "web" { subnet_id = aws_subnet.main.id }
Root cause:Terraform cannot detect dependency if resource attributes are passed indirectly through variables.
#3Expecting data sources to create build order dependencies.
Wrong approach:data "aws_vpc" "main" { filter { name = "tag:Name" value = "main-vpc" } } resource "aws_subnet" "subnet" { vpc_id = data.aws_vpc.main.id } # Assuming data source delays subnet creation
Correct approach:data "aws_vpc" "main" { filter { name = "tag:Name" value = "main-vpc" } } resource "aws_subnet" "subnet" { vpc_id = data.aws_vpc.main.id } # Data source reads existing VPC, no creation order needed
Root cause:Data sources read existing infrastructure and do not create dependencies for resource creation order.
Key Takeaways
Terraform automatically detects resource dependencies when one resource uses another's attributes, creating implicit dependencies.
Implicit dependencies help Terraform build infrastructure in the correct order without extra instructions, reducing errors and manual work.
Not all dependencies are detected implicitly; some require explicit 'depends_on' declarations to ensure correct ordering.
Terraform builds a dependency graph internally to plan and apply changes safely and efficiently.
Understanding implicit dependencies and their limits is essential to write reliable and maintainable Terraform configurations.

Practice

(1/5)
1. What does Terraform use to determine the order of resource creation when no explicit depends_on is set?
easy
A. The alphabetical order of resource names
B. The order resources are written in the file
C. References between resources inside the configuration
D. Manual user input during apply

Solution

  1. Step 1: Understand Terraform's dependency mechanism

    Terraform automatically detects dependencies by checking if one resource references another inside its configuration.
  2. Step 2: Compare with other options

    The order in the file, alphabetical order, or manual input do not affect resource creation order unless explicitly coded.
  3. Final Answer:

    References between resources inside the configuration -> Option C
  4. Quick Check:

    Implicit dependencies = references [OK]
Hint: Look for resource references to find dependencies [OK]
Common Mistakes:
  • Thinking order in file matters
  • Assuming alphabetical order controls creation
  • Believing manual input sets dependencies
2. Which of the following Terraform resource blocks correctly creates an implicit dependency on aws_vpc.main?
easy
A. resource "aws_subnet" "subnet1" { vpc_id = "vpc-123456", cidr_block = "10.0.1.0/24" }
B. resource "aws_subnet" "subnet1" { cidr_block = "10.0.1.0/24" }
C. resource "aws_subnet" "subnet1" { depends_on = [aws_vpc.main], cidr_block = "10.0.1.0/24" }
D. resource "aws_subnet" "subnet1" { vpc_id = aws_vpc.main.id, cidr_block = "10.0.1.0/24" }

Solution

  1. Step 1: Identify implicit dependency via reference

    resource "aws_subnet" "subnet1" { vpc_id = aws_vpc.main.id, cidr_block = "10.0.1.0/24" } references aws_vpc.main.id inside vpc_id, creating an implicit dependency.
  2. Step 2: Check other options

    resource "aws_subnet" "subnet1" { cidr_block = "10.0.1.0/24" } lacks any reference, so no implicit dependency. resource "aws_subnet" "subnet1" { depends_on = [aws_vpc.main], cidr_block = "10.0.1.0/24" } uses explicit depends_on, not implicit. resource "aws_subnet" "subnet1" { vpc_id = "vpc-123456", cidr_block = "10.0.1.0/24" } uses a hardcoded string, no reference.
  3. Final Answer:

    resource "aws_subnet" "subnet1" { vpc_id = aws_vpc.main.id, cidr_block = "10.0.1.0/24" } -> Option D
  4. Quick Check:

    Reference attribute = implicit dependency [OK]
Hint: Implicit dependency needs resource attribute reference, not hardcoded values [OK]
Common Mistakes:
  • Confusing explicit depends_on with implicit
  • Using hardcoded IDs instead of references
  • Missing the reference attribute in resource
3. Given the following Terraform snippet, what is the correct order of resource creation?
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "subnet1" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"
}

resource "aws_instance" "web" {
  subnet_id = aws_subnet.subnet1.id
  ami       = "ami-123456"
  instance_type = "t2.micro"
}
medium
A. aws_vpc.main -> aws_subnet.subnet1 -> aws_instance.web
B. aws_instance.web -> aws_subnet.subnet1 -> aws_vpc.main
C. aws_subnet.subnet1 -> aws_vpc.main -> aws_instance.web
D. aws_vpc.main -> aws_instance.web -> aws_subnet.subnet1

Solution

  1. Step 1: Identify dependencies from references

    aws_subnet.subnet1 depends on aws_vpc.main via vpc_id. aws_instance.web depends on aws_subnet.subnet1 via subnet_id.
  2. Step 2: Determine creation order

    Terraform creates resources in order of dependencies: first aws_vpc.main, then aws_subnet.subnet1, then aws_instance.web.
  3. Final Answer:

    aws_vpc.main -> aws_subnet.subnet1 -> aws_instance.web -> Option A
  4. Quick Check:

    Dependency chain order = B [OK]
Hint: Follow references to find creation order [OK]
Common Mistakes:
  • Ignoring dependency direction
  • Assuming alphabetical or file order
  • Mixing up resource references
4. You have two resources: aws_security_group.sg and aws_instance.web. The instance should be created after the security group. The code is:
resource "aws_security_group" "sg" {
  name = "web-sg"
}

resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
Why might Terraform create the instance before the security group, and how to fix it?
medium
A. Because no reference exists; add vpc_security_group_ids = [aws_security_group.sg.id] to instance
B. Because depends_on is missing; add depends_on = [aws_security_group.sg] to instance
C. Because resource names are unordered; rename aws_security_group.sg to sg1
D. Because Terraform always creates instances first; no fix possible

Solution

  1. Step 1: Identify missing implicit dependency

    The instance resource does not reference the security group, so Terraform sees no dependency and may create in any order.
  2. Step 2: Fix by adding reference

    Adding vpc_security_group_ids = [aws_security_group.sg.id] creates an implicit dependency, ensuring the security group is created first.
  3. Final Answer:

    Add vpc_security_group_ids referencing security group to instance -> Option A
  4. Quick Check:

    Reference creates implicit dependency [OK]
Hint: Add resource attribute reference to create implicit dependency [OK]
Common Mistakes:
  • Relying only on depends_on when reference is better
  • Changing resource names expecting order change
  • Assuming Terraform creates instances first always
5. You have a Terraform configuration with three resources: aws_lb.lb, aws_lb_target_group.tg, and aws_lb_listener.listener. The listener must be created after the load balancer and target group. The target group references the load balancer's ARN. The listener references the target group's ARN. However, you want to ensure the listener is created only after both are fully ready. Which is the best way to enforce this implicit dependency correctly?
hard
A. Use explicit depends_on everywhere and avoid references
B. Reference aws_lb.lb.arn in aws_lb_target_group.tg and aws_lb_target_group.tg.arn in aws_lb_listener.listener without using depends_on
C. Create the listener first, then the target group and load balancer
D. Add depends_on = [aws_lb.lb, aws_lb_target_group.tg] in aws_lb_listener.listener and no references

Solution

  1. Step 1: Understand implicit dependency chaining

    Referencing aws_lb.lb.arn in the target group creates an implicit dependency on the load balancer. Referencing aws_lb_target_group.tg.arn in the listener creates an implicit dependency on the target group.
  2. Step 2: Avoid unnecessary explicit depends_on

    Using references allows Terraform to build the dependency graph automatically and safely without manual depends_on, which should be reserved for special cases.
  3. Final Answer:

    Use references to create implicit dependencies without depends_on -> Option B
  4. Quick Check:

    Implicit references chain dependencies best [OK]
Hint: Chain resource references to build implicit dependencies [OK]
Common Mistakes:
  • Overusing depends_on instead of references
  • Creating resources in wrong order manually
  • Avoiding references and relying only on depends_on