What Is Terragrunt? Units, dependency Blocks, Remote State, and Two Clouds in One Repo

I ran terragrunt destroy in one unit and the next run --all destroy would not start. Units, dependency blocks, S3 remote state, Docker plus AWS (LocalStack).

By Mirac Can Yılmaz 12 min read
What Is Terragrunt? Units, dependency Blocks, Remote State, and Two Clouds in One Repo - DevOps yazısının kapak görseli

I ran terragrunt destroy inside one unit of a small stack, the network. A web container was still attached to that network, so Docker refused and Terraform timed out. Fair enough. Then I ran run --all destroy to take the whole stack down in the right order, and it did not start at all: the unit that depends on the network could not read the network's outputs, because the failed destroy had already removed them from state. Nothing was deleted, nothing could be deleted, and the DAG that was supposed to protect me was the thing refusing to run. Here I look at that DAG: what Terragrunt adds on top of Terraform, how a dependency block is depends_on between state files, what happens when two units talk to two different clouds, and how to get out when a destroy goes wrong. Everything runs on a laptop: Docker for one cloud, LocalStack for the other.

What is Terragrunt?

Terragrunt is a thin wrapper around Terraform (or OpenTofu). It does not replace HCL or providers. It solves three things Terraform leaves to you once a configuration grows:

  • Units. You split one big root module into small directories, each with its own state file. Terragrunt calls them units and runs them together with run --all.
  • Dependencies between units. A dependency block reads another unit's outputs and feeds them in as inputs. Terragrunt builds a graph from those blocks and applies the units in that order, in parallel where it can.
  • Don't repeat yourself. One root.hcl generates the backend and provider blocks for every unit, so a new environment is a folder with one small env.hcl, not a copy of the whole thing.

The previous post looked at depends_on inside one state file. Terragrunt's dependency is the same idea one level up, with the same limits: it orders, it does not supervise.

The problem, and why it matters

A single Terraform root works until it does not. Plans get slow, one bad change can touch everything, and two people cannot apply at the same time because they share one state. The usual fix is to split: one state for networking, one for the app, one per environment. The moment you do that, Terraform can no longer see that the app needs the network, because that edge now crosses two state files.

A second problem shows up when the stack spans more than one provider. Most real setups do: a cloud account and a DNS provider, or two clouds, or a cloud and a local Docker daemon as in this lab. Each unit needs its own provider block, its own backend configuration, and the same handful of settings repeated in every folder. The copy that drifts is always the one you did not look at.

Terragrunt is one answer to both. It is also one more tool, one more set of conventions, and one more place where "it ordered things" is not the same as "it kept things safe".

What Terragrunt gives you

In practice What changed in the lab
include + root.hcl backend and provider written once, generated into every unit four units, two environments, one place where the S3 backend and both provider blocks live
dependency block outputs of one unit become inputs of another; the DAG follows web waited for network and for aws, in both environments, with no depends_on anywhere
mock_outputs plan before the dependency exists run --all plan on an empty state planned the web unit with name = "mock-network"
run --all apply or destroy a whole folder in DAG order networks and buckets first, in parallel, then the web containers
dag graph print the order before running anything dev/web -> dev/aws, dev/web -> dev/network, same for stage
provider by unit one root decides which provider a unit gets live/*/aws got the AWS provider pointed at LocalStack, everything else got Docker

How it works: the DAG across providers

Diagram: two environments, dev and stage, each with three units. The network unit uses the Docker provider, the aws unit uses the AWS provider pointed at LocalStack, and the web unit uses Docker but reads outputs from both. Arrows from network and aws to web are the dependency blocks; run --all applies network and aws in parallel and web after them. Each unit's state is one object in the same S3 bucket.

Terragrunt does not know or care what a unit talks to. It reads the dependency blocks, runs terraform output on the dependency, hands the values to the dependent unit, and orders the run. The provider is the unit's problem. In this lab the root config decides it by folder name:

# root.hcl
locals {
  unit = basename(get_original_terragrunt_dir())   # "network", "aws" or "web"
}

generate "provider" {
  path      = "provider.tf"
  if_exists = "overwrite_terragrunt"
  contents  = local.unit == "aws" ? local.provider_aws : local.provider_docker
}

remote_state {
  backend = "s3"
  generate = { path = "backend.tf", if_exists = "overwrite_terragrunt" }
  config = {
    bucket       = "tfstate"
    key          = "${path_relative_to_include()}/terraform.tfstate"
    endpoints    = { s3 = "http://localhost:9000" }   # SeaweedFS
    use_lockfile = true
    # ...
  }
}

The AWS provider block points every endpoint at LocalStack on port 4566 and uses the fake test credentials LocalStack accepts. The module does not know; it writes aws_s3_bucket and aws_ssm_parameter exactly as it would against a real account.

The lab

Two environments, live/dev and live/stage, three units each. network creates a Docker network. aws creates an S3 bucket and an SSM parameter in LocalStack. web runs an nginx container on that network with the bucket name and the parameter name in its environment. The remote state is an S3-compatible SeaweedFS in a container, with use_lockfile so there is no DynamoDB table to manage.

1. The dependency block, and what the DAG looks like

# live/dev/web/terragrunt.hcl
dependency "network" {
  config_path  = "../network"
  mock_outputs = { name = "mock-network" }
  mock_outputs_allowed_terraform_commands = ["plan", "validate"]
}

dependency "aws" {
  config_path  = "../aws"
  mock_outputs = { bucket = "mock-bucket", greeting_param = "/mock/greeting" }
  mock_outputs_allowed_terraform_commands = ["plan", "validate"]
}

inputs = {
  network_name   = dependency.network.outputs.name
  assets_bucket  = dependency.aws.outputs.bucket
  greeting_param = dependency.aws.outputs.greeting_param
}

terragrunt dag graph prints the edges before anything runs. With an empty state, run --all plan still works: the web unit plans with the mock values, which is the point of mock_outputs. Then run --all apply creates the two networks and the two bucket-plus-parameter pairs in parallel, and the two web containers after them.

Terminal: terragrunt dag graph listing dev/web -> dev/aws, dev/web -> dev/network and the same for stage; run --all plan on an empty state showing name = "mock-network" in the web plan; run --all apply creating networks and AWS resources first and web containers after; the four state keys listed from the bucket.

2. Two clouds, one container

The web container is a Docker resource. Its environment carries values that were created by the AWS provider against LocalStack, and the only thing connecting them is the Terragrunt dependency:

Terminal: docker exec on the dev web container printing ASSETS_BUCKET=tg-dev-assets and GREETING_PARAM=/tg/dev/web/greeting, values that came out of the aws unit; below, the LocalStack health endpoint reporting s3 and ssm available and the bucket listed.

This is the whole multi-cloud story at the small scale: nothing in the Docker module imports the AWS provider, nothing in the AWS module knows about containers, and the environment file that differs between dev and stage is a few lines. Swap LocalStack's endpoint for a real region and the aws unit is the only thing that changes.

3. Where the state went

After the apply, the bucket holds one object per unit, at the key path_relative_to_include() built for it. The SeaweedFS filer shows the same objects the S3 listing does:

SeaweedFS filer UI: the tfstate bucket after terragrunt run --all apply, browsed to live/dev/web, showing a single terraform.tfstate object with its size and timestamp.

Browser: the dev/web state file opened from the bucket as JSON, showing terraform_version, the url output and the docker_container resource with its attributes.

4. The destroy that locked the stack

I went into live/dev/network and ran terragrunt destroy, with the dev web container still attached to that network. Interactive Terragrunt would have warned me about dependent units. Non-interactive, the way it runs in a pipeline, it did not. Docker refused to remove a network with an endpoint on it, and the provider gave up after its timeout:

Terminal: terraform destroy inside live/dev/network only, "Still destroying" until the provider gives up and then "Error: timeout while waiting for state to become 'removed'"; then terragrunt run --all destroy from live/ failing with "live/dev/network is a dependency of live/dev/web but detected no outputs" and "Unit live/dev/network did not run due to an earlier failure"; then terragrunt apply inside the network unit, "Apply complete! 0 added, 0 changed, 0 destroyed", outputs back; then run --all destroy walking dev/web and dev/network in reverse order.

The destroy failed, which was correct. What was not obvious: a destroy plan removes the root module's outputs from state before it starts deleting resources, and that part had succeeded. So the network unit still had its resource and no outputs. The next run --all destroy had to resolve dependency.network.outputs.name for the web unit, found none, and refused to run the dev chain at all. Stage, which had no broken unit, was destroyed in the same run.

Recovery was one command: terragrunt apply inside the network unit. Nothing changed in Docker, the outputs came back into state, and run --all destroy then walked dev in reverse order. The other way out is to add "destroy" to mock_outputs_allowed_terraform_commands, so the web unit can be destroyed with mock inputs. Either way the lesson is the same as in the previous post: the dependency orders the run. It does not stop you from doing the wrong thing in one folder.

Where it broke

1. Detected generate blocks with the same name: [provider]

My first version put a generate "provider" in the aws units to override the Docker provider the root generated. Terragrunt does not allow a child to redefine a parent's generate block by the same name. The fix was to move the decision into the root: one generate block whose contents depend on the unit's folder name.

2. License activation failed from LocalStack

localstack/localstack:latest is the Pro image now; it exits unless it finds an auth token. The community image is the versioned tag, localstack/localstack:4.9 here. If your LocalStack quits a second after starting, check the tag before anything else.

3. Backend initialization required, please run "terraform init"

I had initialised the aws unit once with -backend=false to pre-download the provider. Terragrunt reused that cache and Terraform refused to run with a half-initialised backend. Deleting the unit's .terragrunt-cache fixed it. The cache is a convenience, not state; when in doubt, remove it.

4. timeout while waiting for state to become 'removed'

The network unit, destroyed alone, with a container still attached. Docker keeps the network in a pending state and the provider waits out its timeout. In non-interactive mode Terragrunt does not warn that other units depend on this one.

5. ... is a dependency of ... but detected no outputs

The follow-up to the previous failure, and the one that actually blocks you: the failed destroy already dropped the outputs, so run --all destroy cannot resolve the dependency and skips the whole chain. terragrunt apply in the dependency unit restores the outputs.

6. No outputs on a second run --all destroy

After a clean full destroy, running run --all destroy again fails the same way for every unit that reads a dependency, because destroyed units have no outputs. It looks alarming and is harmless. Allowing destroy in mock_outputs_allowed_terraform_commands makes it a clean no-op instead.

The trade-off, side by side

One Terraform root Terragrunt units
Plus Terraform sees every edge; one plan, one state, no extra tool small blast radius per state; provider and backend written once; a new environment is a small file
Minus plans slow down, one change can touch everything, one state for the whole team an extra tool and its conventions; cross-unit edges live outside Terraform and can lock you out, as above
Fits one team, one environment, a configuration you can plan in a minute several environments or teams, more than one provider, anything you already wanted to split
Real cloud in the lab LocalStack (or any local emulator)
Plus the real API, real IAM, real quirks free, fast, no account, safe to destroy a hundred times
Minus costs money, needs credentials, slow to reset not every service, not every edge case; IAM is mostly a yes
Fits the last check before production learning the shape of a stack, CI that must not touch an account

Neither column is the right one. I keep a single root until the second environment shows up, and I build the shape of a stack against LocalStack before the first real apply costs anything.

When to use which

  • Stay with one root while one team plans it in a minute and nobody waits on anyone's lock.
  • Move to Terragrunt when the second environment appears, or when two providers need the same backend and settings in every folder.
  • Decide the provider in root.hcl, by folder name or by a small per-unit file; do not redefine generate blocks in children.
  • Give every dependency mock_outputs and think about whether destroy belongs in the allowed commands for your pipeline.
  • Never destroy a unit alone if another unit reads its outputs. If you did, terragrunt apply it back before run --all destroy.
  • Pin the LocalStack tag. latest is the Pro image.

Your call

I split into Terragrunt units when the second environment shows up, not before, and I let the root decide the provider by folder name. That is the right size for my stacks this month; it is not a rule for yours. Two things I would like to hear from real repos:

  • When did you split your Terraform: at the second environment, at the second team, or when a plan got too slow to wait for?
  • Do you test cloud infrastructure against an emulator like LocalStack, or only against a real account?

I am not after who is right. I want the pluses and minuses of both columns above to be visible to everyone who reads this, in words from real infrastructure, and the comments are where that happens. If you would rather vote than write, the same question is a poll on my LinkedIn post for this article: https://www.linkedin.com/in/mirac-can-yilmaz

Summary

  • Terragrunt adds units, dependency blocks and a root config to Terraform. A dependency is depends_on between state files: it orders run --all and passes outputs.
  • One root.hcl can generate the backend and the right provider for every unit, by folder name. The modules do not know which cloud they are in; a Docker container carried values created in LocalStack.
  • Remote state is one object per unit in one bucket; use_lockfile means no lock table.
  • A destroy that fails in one unit can still remove its outputs. run --all destroy then refuses the dependent chain. Fix with terragrunt apply in the dependency, or allow destroy in mock_outputs_allowed_terraform_commands.
  • The DAG orders. It does not supervise. The same lesson as depends_on, one level up.

Next in the series

This is post 7b of Core Skills, the second half of What Is depends_on in Terraform?, which looked at dependencies and the lifecycle block inside one state. Next: What Is a Reusable Workflow in GitHub Actions?, on reusable workflows, matrix builds and caching, and what a shared pipeline changes for a team.

The code for this lab (the Terragrunt root and units, the Docker and AWS modules, the SeaweedFS state backend and the LocalStack setup) is shared with Lab Access members on Buy Me a Coffee; the repo invite comes by email after you join: https://buymeacoffee.com/miraccanyilmaz/membership

About the author

Mirac Can Yılmaz

Mirac Can Yılmaz DevOps & Platform Engineer

I work as a DevOps and platform engineer with Kubernetes, GitOps (Argo CD), CI/CD and Terraform. Every post here was tried and measured in my own lab, on kind and Talos clusters: the commands, the errors and the numbers as they happened. The lab code is shared with Lab Access members on Buy Me a Coffee.

İnsanın en büyük hatalarından biri de doğru zamanı yanlış kişilerle doldurmaktır.
Charles Bukowski