When Should You Explicitly Use depends_on in Terraform?

Terraform automatically builds a dependency graph by analyzing resource references in your code. In most cases, you never need to declare dependencies manually. But there are specific scenarios where depends_on is necessary.

How Implicit Dependencies Work

When one resource references another, Terraform infers the dependency automatically:

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "public" {
  vpc_id     = aws_vpc.main.id   # Implicit dependency — Terraform knows VPC must exist first
  cidr_block = "10.0.1.0/24"
}

When Implicit Dependencies Are NOT Enough

Use depends_on when a resource relies on another that it does not directly reference in code. The most common example: an application server that needs a database to be fully initialized, but shares no configuration values with it.

resource "aws_db_instance" "postgres" {
  identifier        = "my-app-db"
  engine            = "postgres"
  instance_class    = "db.t3.micro"
  allocated_storage = 20
  username          = "admin"
  password          = var.db_password
}

resource "aws_instance" "app_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  # No direct reference to the DB, but the app needs it running first
  depends_on = [aws_db_instance.postgres]
}

depends_on with Modules

depends_on can also be applied to entire modules:

module "database" {
  source = "./modules/database"
}

module "application" {
  source     = "./modules/application"
  depends_on = [module.database]
}

depends_on with IAM Policies

A classic use case — an EC2 instance needing an IAM policy to be attached before it starts:

resource "aws_iam_role_policy_attachment" "s3_access" {
  role       = aws_iam_role.ec2_role.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}

resource "aws_instance" "worker" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  iam_instance_profile = aws_iam_instance_profile.ec2_profile.name

  depends_on = [aws_iam_role_policy_attachment.s3_access]
}

Key Takeaway

Use depends_on only when a hidden dependency exists that Terraform cannot detect through resource attribute references. Overusing it adds unnecessary coupling — rely on implicit dependencies wherever possible.

(Visited 1 times, 1 visits today)