Skip to content
Latchkey

Terragrunt generate block "file already exists" in CI

A generate block writes a file (a backend, provider, or versions file) into the module directory. When that file already exists and if_exists is not set to overwrite, Terragrunt errors instead of clobbering it.

What this error means

terragrunt fails with a generate error stating the target file already exists and if_exists is set to error (the default for some setups), so it refuses to write.

terragrunt
ERRO[0001] Detected generate block for backend.tf that would overwrite an existing
file, but if_exists is set to "error". Set if_exists = "overwrite" or "overwrite_terragrunt"
to allow the generate block to replace the file.

Common causes

A committed file collides with the generated one

The module already contains a hand-written backend.tf (or provider file) with the same name the generate block targets, and if_exists forbids overwriting.

A stale generated file lingered in the working tree

A previous run left a generated file behind (not cleaned) that the current generate block now conflicts with.

How to fix it

Let the generate block overwrite safely

Use overwrite_terragrunt, which replaces only files Terragrunt itself generated and errors on foreign files.

terragrunt.hcl
generate "backend" {
  path      = "backend.tf"
  if_exists = "overwrite_terragrunt"
  contents  = "terraform { backend \"s3\" {} }"
}

Remove the conflicting committed file

  1. Delete the hand-written backend/provider file the generate block owns.
  2. Let Terragrunt generate it instead so there is one source of truth.
  3. Re-run the plan.
Terminal
git rm live/prod/vpc/backend.tf

How to prevent it

  • Use if_exists = "overwrite_terragrunt" for generated backend/provider files.
  • Do not commit files that a generate block also produces.
  • Clean .terragrunt-cache between unrelated runs.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →