Cloud / IaC · Freelance

Terragrunt Multi-Environment Layout for AWS with Remote State and Terratest

A DRY multi-environment Terraform setup: Terragrunt root config, S3 remote state, per-environment inputs, reusable modules for EventBridge, CodePipeline and Lambda, and Terratest checks.

  • Terraform
  • Terragrunt
  • S3 backend
  • DynamoDB locking
  • Terratest
  • EventBridge
  • CodePipeline
  • AWS Lambda
  • Go

// Why this matters

A terragrunt multi environment aws layout answers a question every Terraform team hits within a few months: how do we run the same infrastructure in dev, staging and production without maintaining three diverging copies. Copying folders works on day one and fails by month three, when a fix lands in prod and never reaches dev.

Terraform workspaces look like the answer but hide the environment in a runtime variable, share one backend configuration and make it easy to apply to the wrong target. Explicit folders make the target visible in the path of the command you run.

I have used this layout for client estates built from small modules (an EventBridge rule, a CodePipeline, a Lambda function) and for larger EKS stacks. The same skeleton scales from a handful of resources to many units.

// The problem

Plain Terraform requires the backend block to use literal values; it cannot interpolate variables. So every stack repeats a bucket name, a key and a region, and every environment edits the key by hand. A copy-paste mistake points two stacks at the same state file, and the next apply tries to delete the other stack's resources.

Dependencies are the second problem. A network stack produces subnet IDs that an application stack needs. Without tooling, people copy IDs between tfvars files or use data lookups that break when names change. Ordering applies by hand is error-prone.

Finally, modules without tests regress. A refactor of a shared module compiles and plans cleanly but changes behaviour, and the first sign is a failed production apply. You need a way to exercise a module for real before environments pick it up.

// The solution

The repository has two top-level areas: modules/ (or separate module repositories) and live/. Under live/ there is a folder per environment and, inside it, a folder per unit such as network, eventbridge or pipeline. Each unit contains only a terragrunt.hcl.

A root terragrunt.hcl at the top of live/ holds everything common. Its remote_state block uses the S3 backend and sets the key with path_relative_to_include(), so live/prod/network/ gets its own key automatically. It also enables locking with a DynamoDB table and generates the backend and provider files, so units contain no boilerplate.

Each unit includes the root file, sets terraform.source to a module address pinned to a tag, and provides inputs. Environment-wide values (account alias, region, sizing) come from an env.hcl file that units read with read_terragrunt_config. Promotion then means changing the tag in the staging unit, applying, and later making the same one-line change in prod.

Cross-unit data uses dependency blocks. The application unit declares a dependency on the network unit and reads its outputs as inputs. Terragrunt builds the graph, so run-all plan and run-all apply honour order. Mock outputs let plans work before the dependency exists.

Terratest closes the loop. A Go test copies a module to a temp dir, applies it with a unique name prefix in a sandbox, asserts on outputs and real API state, and destroys it with defer. I rejected Terraform workspaces (hidden target) and a single giant root module (blast radius), and kept Terragrunt thin on purpose: logic belongs in modules. See One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling and Adding a Region Without Destroying Anything for related patterns.

How it flows flow1. Root config → 2. Env folder → 3. Module source → 4. Plan → 5. Review gate → 6. Apply → 7. Test → 8. Promote01Root config02Env folder03Module source04Plan05 · GATEReview gate06Apply07Test08Promote
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Root configone terragrunt.hcl defines remote state and provider generation
  2. Env folderdev, staging and prod each hold only inputs
  3. Module sourceTerragrunt points each unit at a versioned module
  4. Planrun-all plan shows changes per unit in dependency order
  5. Review gate gateplan output is reviewed before apply
  6. Applyunits apply in order with outputs passed through dependencies
  7. TestTerratest provisions modules in a sandbox and asserts outcomes
  8. Promotebump the module tag in the next environment
Rootterragrunt.hclbackend + providercommon tagsEnvironmentslive/devlive/staginglive/prodUnitsnetworkeventbridgepipelinelambdaModulesversioned git tagsno env logicTerratest suite
Repository layout. Modules are shared; environments are folders of inputs.
Promotion path for a module change flow1. Change module → 2. Test → 3. Tag → 4. Dev → 5. Soak → 6. Staging → 7. Prod01Change module02Test03Tag04Dev05 · GATESoak06Staging07Prod
Promotion path for a module change. A change moves through environments by bumping a tag.
  1. Change moduleedit code and add Terratest cases
  2. TestTerratest applies and destroys in a sandbox
  3. Tagpublish a new module version
  4. Devbump the tag in live/dev and apply
  5. Soak gateobserve dev before promoting
  6. Stagingrepeat in live/staging
  7. Prodbump the tag after approval

// Before you start

  • Terraform 1.6 or later and Terragrunt 0.55 or later installed
  • An S3 bucket and DynamoDB table for state, created once out of band, referred to as <state-bucket> and <lock-table>
  • AWS credentials for each target account via profiles or role assumption
  • Go 1.21 or later for Terratest
  • A git host for module tags (any repository works)

// Step-by-step implementation

  1. 01 Lay out the repository

    Keep the structure boring and predictable. Each environment has an env.hcl for shared values, and each unit is a folder with one file. Predictability is what lets a new engineer find anything in seconds.

    Create the folders first and add content afterwards.

  2. 02 Write the root terragrunt.hcl with remote state

    The remote_state block is the piece that eliminates repetition. path_relative_to_include() returns the unit path relative to the root file, so each unit gets a unique key. generate writes backend.tf, so Terraform sees a normal backend block.

    Enable encryption and a lock table. Locking is what stops two engineers from applying at once.

  3. 03 Define environment values once

    An env.hcl per environment keeps sizing and naming in one place. Units load it with read_terragrunt_config and read the values they need. This is how dev gets small instances and prod gets larger ones without touching module code.

    Keep these files tiny and free of logic.

  4. 04 Create a versioned module: EventBridge rule to Lambda

    A module should do one job and take everything environmental as variables. This one creates a scheduled EventBridge rule, a target and the permission that lets EventBridge invoke the function.

    The permission resource is the one people forget; without it the rule fires and nothing happens.

  5. 05 Compose units with dependencies and inputs

    The EventBridge unit depends on the Lambda unit. The dependency block reads outputs from that unit; mock_outputs let plan succeed before the Lambda exists. The source line pins the module to a tag, which is how promotion is controlled.

    Because the unit includes the root file, it inherits the backend and provider automatically.

  6. 06 Plan and apply the whole environment

    run-all walks the dependency graph. Always plan first and read the output; Terragrunt runs units in parallel where it can, so errors can scroll past quickly. Use a plan file or the non-interactive flag only in CI where a human has already approved the plan.

    Scope with a path to apply a single unit while debugging.

  7. 07 Test the module with Terratest

    Terratest runs the real module. Use a random suffix so parallel runs never collide, defer destroy so a failing assertion still cleans up, and assert against outputs and, where cheap, the real API.

    Run these against a sandbox account or a dedicated prefix in CI on every module change, before cutting a tag.

// How to verify it works

  • terragrunt run-all plan in live/dev succeeds and lists the units in dependency order.
  • The state bucket contains one object per unit under a path that mirrors the folder layout.
  • Running two applies at once makes the second wait on the lock rather than corrupt state.
  • go test ./test -run TestEventBridgeRule creates and then removes the rule, leaving no resources behind.
  • Changing the module tag in dev only produces a plan in dev; staging and prod remain unchanged.

// Design decisions and trade-offs

  • One root terragrunt.hcl generates the backend so no environment repeats it
  • State keys derive from the folder path, so state can never collide between stacks
  • Modules stay environment-agnostic; environments only supply inputs
  • Pin module versions with git tags so promotion is a deliberate change
  • Terratest applies modules to a throwaway account or prefix before release

// Pitfalls and lessons learned

  • Forgetting mock_outputs makes the first plan fail because the dependency has no state yet.
  • Stale .terragrunt-cache folders produce confusing provider-version errors; delete them after changing sources.
  • Never put environment conditionals inside modules. If a module needs "if prod", expose a variable instead.
  • A module source without a pinned ref silently moves every environment when someone pushes to main.
  • run-all destroy is dangerous at the wrong directory level; check pwd before running it.
  • Locking tables created with the wrong key name cause lock errors that look like permission problems.

// Frequently asked questions

What does terragrunt add over plain Terraform?

It removes duplicated backend and provider blocks, derives state keys from paths, and orders units through dependency blocks.

Terragrunt or Terraform workspaces?

Folders make the target environment explicit and give each its own backend config. Workspaces hide the target in a variable and are easier to misapply.

How do I share outputs between units?

Declare a dependency block and read dependency.name.outputs; Terragrunt applies in the right order.

How do I do terragrunt multi environment aws promotion?

Pin each environment to a module tag and promote by changing the tag one environment at a time.

Can Terratest run in CI?

Yes. Give the pipeline a sandbox role, use unique name prefixes, and always defer destroy.

// The outcome

A new environment is a folder with a small inputs file instead of a copy of the codebase. Backends, locking and provider settings are defined once, and module changes are tested before any environment consumes them.

// Where to take it next

  • Run plan on pull requests and apply from a protected branch, as in One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling.
  • Add policy checks (OPA or Sentinel-style) on the plan JSON.
  • Split state further as units grow, keeping blast radius small.
  • Add a drift-detection job that runs plan nightly and alerts on differences.

// Keep reading