Misunderstanding explicit dependencies in Terraform can create noisy, redundant and potentially confusing code. In this article you will learn when and how to use Terraform's depends_on
meta-argument
As a reminder, dependencies help Terraform know in which order the resources must be created and deleted.
What is an implicit dependency?
Implicit dependencies are automatically inferred by Terraform when a resource or module accesses the data of another resource or module.
In this example employee
implicitly depends on employer
because it accesses its name
.
resource "employer" "monsters_inc" {
name = "Monsters, Inc."
}
resource "employee" "mike" {
name = "Mike"
employer_name = employer.monsters_inc.name
}
What is an explicit dependency?
Since driver
doesn't access any of team
's data, there is no implicit dependency.
resource "team" "ferrari" {
name = "Ferrari"
}
resource "driver" "carlos" {
name = "Carlos"
}
If we want to enforce an explicit dependency between team
and driver
we can use the depends_on
meta-argument.
resource "team" "ferrari" {
name = "Ferrari"
}
resource "driver" "carlos" {
depends_on = [team.ferrari]
name = "Carlos"
}
This guarantees that team
will be created before driver
.
When should I use an explicit dependency?
Explicitly specifying a dependency using the depends_on
meta-argument is only necessary when a resource relies on some other resource without accessing any of its data.
Examples
In this example there is no dependency, implicit or explicit.
It is dangerous because the employee
could be created before the employer
.
# 👎 DANGEROUS
local {
employer_name = "Monsters, Inc."
}
module "employer" {
name = locals.employer_name
}
module "employee" {
employer_name = locals.employer_name
}
In this example there is an implied dependency, re-declared explicitly. This is redundant and potentially confusing.
# 👎 BAD
local {
employer_name = "Monsters, Inc."
}
module "employer" {
name = locals.employer_name
}
module "employee" {
depends_on = [module.employer]
employer_name = module.employer.name
}
This last example illustrates the ideal approach.
# 👍 IDEAL
local {
employer_name = "Monsters, Inc."
}
module "employer" {
name = locals.employer_name
}
module "employee" {
employer_name = module.employer.name
}