Overview
The following is a simple overview of the main features in Terragrunt.
It includes configurations that are a bit more complex than the ones found in the Quick Start, but don’t panic!
We’ll walk you through each one, and you don’t need to understand everything right away. Knowing that these features are available as you start to use Terragrunt can give you a tool to reach for when you encounter common problems that typically require one or more of these solutions.
This guide is for readers who have completed the Quick Start or joined a team already using Terragrunt. It covers advanced configuration with cloud examples.
If you are unfamiliar with OpenTofu/Terraform, you may want to also read OpenTofu or Terraform documentation after reading this guide.
Following Along
Section titled “Following Along”What follows isn’t a tutorial in the same sense as the Quick Start, but more of a guided tour of some of the more commonly used features of Terragrunt. You don’t need to follow along to understand the concepts, but if you want to, you can.
Browse the steps for your provider:
If you would prefer it, you can clone the Terragrunt repository, and follow along with the examples in your own environment without any copy + paste.
Replace values prefixed __FILL_IN_ with values for your account.
If you need a cloud account, check whether your chosen provider offers a free tier. You can also adapt the examples to another provider.
Example
Section titled “Example”Here is a typical terragrunt.hcl file you might find in a Terragrunt project*:
# Configure the remote backendremote_state { backend = "s3"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { bucket = "my-tofu-state"
key = "tofu.tfstate" region = "us-east-1" encrypt = true dynamodb_table = "my-lock-table" }}
# Configure the AWS providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "aws" { region = "us-east-1"}EOF}
# Configure the module## The URL used here is a shorthand for# "tfr://registry.terraform.io/terraform-aws-modules/vpc/aws?version=5.16.0".## You can find the module at:# https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/latest## Note the extra `/` after the `tfr` protocol is required for the shorthand# notation.terraform { source = "tfr:///terraform-aws-modules/vpc/aws?version=5.16.0"}
# Configure the inputs for the moduleinputs = { name = "my-vpc" cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"] private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"] public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
enable_nat_gateway = false enable_vpn_gateway = false
tags = { IaC = "true" Environment = "dev" }}# Configure the remote backendremote_state { backend = "azurerm"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" container_name = "tfstate"
key = "tofu.tfstate" location = "eastus" use_azuread_auth = true assign_blob_data_role = true }}
# Configure the Azure providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "azapi" { default_location = "eastus"}EOF}
# Configure the module## The `tfr:///` shorthand uses the default registry host for OpenTofu or Terraform.# Set `TG_TF_DEFAULT_REGISTRY_HOST` to use a different host.## The module lives at:# https://search.opentofu.org/module/azure/avm-res-resources-resourcegroup/azurerm/latest## The shorthand needs three slashes after `tfr:`, as in `tfr:///`.terraform { source = "tfr:///Azure/avm-res-resources-resourcegroup/azurerm?version=0.4.0"}
# Configure the inputs for the moduleinputs = { name = "my-rg-eastus" location = "eastus"
tags = { IaC = "true" Environment = "dev" }}# Configure the remote backendremote_state { backend = "gcs"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { project = "my-project" location = "us-central1" bucket = "my-tofu-state"
prefix = "tofu" }}
# Configure the Google providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "google" { project = "my-project" region = "us-central1"}EOF}
# Configure the module## The `tfr:///` shorthand uses the default registry host for OpenTofu or Terraform.# Set `TG_TF_DEFAULT_REGISTRY_HOST` to use a different host.## The module lives at:# https://search.opentofu.org/module/terraform-google-modules/network/google/latest## The shorthand needs three slashes after `tfr:`, as in `tfr:///`.terraform { source = "tfr:///terraform-google-modules/network/google?version=18.3.1"}
# Configure the inputs for the moduleinputs = { project_id = "my-project" network_name = "my-vpc-us-central1"
subnets = [ { subnet_name = "private" subnet_ip = "10.0.1.0/24" subnet_region = "us-central1" }, { subnet_name = "public" subnet_ip = "10.0.101.0/24" subnet_region = "us-central1" }, ]}Try it out
Section titled “Try it out”If you want to try this configuration locally:
-
Copy the contents above into a
terragrunt.hclfile in an empty directory. -
Change the value of
bucketin theremote_stateblock to a unique name.This has to be globally unique, so you might want to include today’s date in the name.
-
Ensure that you are authenticated with AWS and have the necessary permissions to create resources.
Running
aws sts get-caller-identityin the AWS CLI is a good way to confirm this. -
Run
terragrunt run --backend-bootstrap -- apply -auto-approvein the directory where you created theterragrunt.hclfile.
-
Copy the contents above into a
terragrunt.hclfile in an empty directory. -
Change the value of
storage_account_namein theremote_stateblock to a unique name.Storage account names have to be globally unique, between 3 and 24 characters long, and can only contain lowercase letters and numbers.
-
Ensure that you are authenticated with Azure, and tell Terragrunt and OpenTofu/Terraform which subscription to use:
Terminal window az loginexport ARM_SUBSCRIPTION_ID="$(az account show --query id --output tsv)"The example sets
assign_blob_data_role = true. To use it, your identity needs permission to create role assignments, such as subscription Owner.If you cannot assign roles, remove the option. Ask an Owner or User Access Administrator to grant you Storage Blob Data Contributor before you apply. They can grant it on the subscription or on a resource group they create first and name in
resource_group_name. The storage account does not exist until bootstrap runs. A Contributor cannot assign roles to itself. See Required Azure permissions.The Azure Verified Modules used in this guide require OpenTofu/Terraform 1.9 or newer.
-
Run
terragrunt run --backend-bootstrap -- apply -auto-approvein the directory where you created theterragrunt.hclfile.If Terragrunt just granted the blob role and this first run fails with a 403 while checking the container, wait a few minutes and rerun. Azure may not have applied the role yet.
-
Copy the contents above into a
terragrunt.hclfile in an empty directory. -
Change the value of
bucketin theremote_stateblock to a unique name.Cloud Storage bucket names have to be globally unique, so you might want to include today’s date in the name.
-
Replace every
my-projectwith the ID of the Google Cloud project you want to use. -
Ensure that you are authenticated with Google Cloud, and that the Compute Engine API is enabled in your project:
Terminal window gcloud auth application-default logingcloud services enable compute.googleapis.com --project my-projectTerragrunt and the Google provider both read these Application Default Credentials, so one login covers creating the state bucket and the network. Your account needs permission to create Cloud Storage buckets and VPC networks in the project (e.g. the Storage Admin and Compute Network Admin roles). See the GCS backend documentation for other ways to authenticate.
-
Run
terragrunt run --backend-bootstrap -- apply -auto-approvein the directory where you created theterragrunt.hclfile.
The --backend-bootstrap flag lets this apply run create the remote state resources described in the remote_state block if they don’t exist yet. You can also create them beforehand with terragrunt backend bootstrap.
If you’re familiar with OpenTofu/Terraform, this should be a pretty familiar experience.
For the most part, when you use Terragrunt, you are simply setting up configurations in terragrunt.hcl files that have analogues to what you would define with .tf files, then running terragrunt instead of tofu/terraform on the command line.
terragrunt.hcl
Section titled “terragrunt.hcl”The terragrunt.hcl file above does the following:
Remote state backend configuration
Section titled “Remote state backend configuration”The remote_state configuration block controls how Terragrunt should store backend OpenTofu/Terraform state.
In this example, Terragrunt is being configured to store state in an S3 bucket named my-tofu-state in the us-east-1 region. The state file will be named tofu.tfstate, and Terragrunt will use a DynamoDB table named my-lock-table for locking.
If you run the following, you can see how Terragrunt generates a backend.tf file to tell OpenTofu/Terraform to do this:
$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "s3" { bucket = "my-tofu-state" dynamodb_table = "my-lock-table" encrypt = true key = "tofu.tfstate" region = "us-east-1" }}This configuration stores tofu.tfstate in the tfstate container of the mytofustate storage account, within the my-tofu-state resource group. Azure Blob Storage uses blob leases for locking, so no separate lock table is needed.
If you run the following, you can see how Terragrunt generates a backend.tf file to tell OpenTofu/Terraform to do this:
$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "azurerm" { container_name = "tfstate" key = "tofu.tfstate" resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" use_azuread_auth = true }}Notice that location and assign_blob_data_role aren’t in the generated file. Those settings are only used by Terragrunt when it bootstraps the backend, and are never passed on to OpenTofu/Terraform.
In this example, Terragrunt is being configured to store state in a Cloud Storage bucket named my-tofu-state, in the us-central1 location of the my-project project. The gcs backend writes state to <prefix>/default.tfstate, so this unit’s state lands at tofu/default.tfstate. The gcs backend locks state natively, so no separate lock table is needed.
If you run the following, you can see how Terragrunt generates a backend.tf file to tell OpenTofu/Terraform to do this:
$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "gcs" { bucket = "my-tofu-state" prefix = "tofu" }}Notice that project and location aren’t in the generated file. Terragrunt only uses them to create the bucket, and never passes them on to OpenTofu/Terraform.
Right before running any OpenTofu/Terraform command that might store state, Terragrunt will ensure that the appropriate backend.tf file is present in the working directory where OpenTofu/Terraform will run, so that state is persisted appropriately when tofu/terraform is invoked.
Terragrunt created the remote state resources when you passed --backend-bootstrap. You did not need to create them or run tofu/terraform init yourself.
These are just a few of the things that Terragrunt does automatically when orchestrating OpenTofu/Terraform commands because it knows how OpenTofu/Terraform work, and it can take care of some busy work for you to make your life easier.
Provider configuration
Section titled “Provider configuration”The generate block is used to inject arbitrary files into the OpenTofu/Terraform module before running any OpenTofu/Terraform commands.
In this example, Terragrunt is being configured to inject a provider.tf file into the module that configures the AWS provider to use the us-east-1 region.
If you run the following, you can see the provider.tf file that Terragrunt generates:
$ find .terragrunt-cache -name provider.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaprovider "aws" { region = "us-east-1"}The generate block writes provider.tf to configure the azapi provider used by the Azure Verified Modules in this guide. Authentication comes from your Azure CLI session, and the target subscription comes from the ARM_SUBSCRIPTION_ID environment variable you exported earlier. Resources without their own location use default_location.
If you run the following, you can see the provider.tf file that Terragrunt generates:
$ find .terragrunt-cache -name provider.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaprovider "azapi" { default_location = "eastus"}In this example, Terragrunt is being configured to inject a provider.tf file into the module that configures the Google provider to use the my-project project and the us-central1 region. Authentication comes from the Application Default Credentials you set up earlier.
If you run the following, you can see the provider.tf file that Terragrunt generates:
$ find .terragrunt-cache -name provider.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaprovider "google" { project = "my-project" region = "us-central1"}In this example, the generate block writes provider.tf before OpenTofu/Terraform runs. You can also use it to add other files to a module, such as provider settings that vary by region.
You want to be mindful not to do too much with this configuration block, as it can make your OpenTofu/Terraform code harder to reproduce, understand and maintain. But it can be a powerful tool when used judiciously.
Module configuration
Section titled “Module configuration”The terraform block is used to indicate where to source the OpenTofu/Terraform module from (it’s called terraform for historical reasons, but it controls behavior pertinent to both OpenTofu and Terraform).
In this example, all it is doing is controlling where Terragrunt should fetch the OpenTofu/Terraform module from. The configuration block can do a lot more, but the source attribute is the most common attribute you’ll set on the terraform block.
You’ll notice that in the examples above, we were using find to locate the .tf files being generated and placed within the OpenTofu/Terraform module being downloaded here within the .terragrunt-cache directory. This is because Terragrunt aims to operate as an orchestrator, at a level of abstraction higher than OpenTofu/Terraform.
Over the years supporting customers managing IaC at scale, the patterns that we’ve seen emerge for really successful organizations is to treat OpenTofu/Terraform modules as versioned, generic, well tested patterns of infrastructure, and to deploy them in as close to the exact same way as possible across all uses of them.
Terragrunt supports this pattern by treating each unit of Terragrunt configuration (a directory with a terragrunt.hcl file in it) as a hermetic container of infrastructure that can be reasoned about in isolation, and then composed together to form a larger system of one or more stacks (each stack being a collection of units).
To that end, the way that Terragrunt loads OpenTofu/Terraform configurations is to download them into a subdirectory of the .terragrunt-cache directory, and then to orchestrate OpenTofu/Terraform commands from that directory. This ensures that the OpenTofu/Terraform modules are treated as immutable, versioned, and hermetic, and that the OpenTofu/Terraform runs are reliably reproducible.
Directory.terragrunt-cache/
DirectorytnIp4Am20T3Q8-6FuPqfof-kRGU
DirectoryThyYwttwki6d6AS3aD5OwoyqIWA
- CHANGELOG.md
- LICENSE
- README.md
- UPGRADE-3.0.md
- UPGRADE-4.0.md
- backend.tf
- examples
- main.tf
- modules
- outputs.tf
- provider.tf
- terragrunt.hcl
- variables.tf
- versions.tf
- vpc-flow-logs.tf
Directory.terragrunt-cache/
DirectorytnIp4Am20T3Q8-6FuPqfof-kRGU
DirectoryThyYwttwki6d6AS3aD5OwoyqIWA
- AGENTS.md
- CODE_OF_CONDUCT.md
- CONTRIBUTING.md
- LICENSE
- Makefile
- README.md
- SECURITY.md
- SUPPORT.md
- _footer.md
- _header.md
- avm
- avm.bat
- avm.ps1
- avm.tflint.override.hcl
- backend.tf
- data.tf
- examples
- main.telemetry.tf
- main.tf
- modules
- outputs.tf
- provider.tf
- terraform.tf
- terragrunt.hcl
- tests
- variables.tf
Directory.terragrunt-cache/
DirectorytnIp4Am20T3Q8-6FuPqfof-kRGU
DirectoryThyYwttwki6d6AS3aD5OwoyqIWA
- CHANGELOG.md
- CONTRIBUTING.md
- LICENSE
- Makefile
- README.md
- backend.tf
- build
- codelabs
- docs
- examples
- helpers
- main.tf
- metadata.display.yaml
- metadata.yaml
- modules
- outputs.tf
- provider.tf
- terragrunt.hcl
- test
- variables.tf
- versions.tf
Any file that isn’t part of the OpenTofu/Terraform module (like the backend.tf and provider.tf files Terragrunt generated) get a special little Generated by Terragrunt comment at the top of their files by default to make sure it’s clear that Terragrunt generated them (and that they might not be there for other users of the same module).
Inputs configuration
Section titled “Inputs configuration”The inputs block is used to indicate what variable values should be passed to OpenTofu/Terraform when running tofu/terraform commands.
These variables configure the VPC module: the name of the VPC, the CIDR block, the availability zones, the subnets, and so on.
These variables configure the resource group module: its name, location and tags.
These variables configure the network module: the project, the name of the VPC network, and its subnets with their IP ranges and regions.
Under the hood, what happens here is that Terragrunt sets relevant TF_VAR_ prefixed environment variables, which are automatically detected by OpenTofu/Terraform as values for variables defined in .tf files.
Further Reading
Section titled “Further Reading”You can learn more about all the configuration blocks and attributes available in Terragrunt in the docs.
Core Patterns
Section titled “Core Patterns”This statement above is kind of a lie:
* Here is a typical terragrunt.hcl file you might find in a Terragrunt project.
Most projects share provider and backend settings across units. Repeating them in every terragrunt.hcl creates duplication. The state path is the part that varies for each unit.
Aware of this pattern, Terragrunt is designed to leverage a hierarchy of reusable configurations so that your code can be DRY (Don’t Repeat Yourself).
The include block
Section titled “The include block”In almost every terragrunt.hcl file you see, there will be a section that looks like this:
include "root" { path = find_in_parent_folders("root.hcl")}This block configures Terragrunt to include configuration found in a parent folder named root.hcl into it. This is a way to share configuration across all units of infrastructure in your project.
The root label being applied here is the idiomatic way to reference the root.hcl file that is common to all other configurations in the project. This is a convention, not a requirement, but it’s a good one to follow to make your code more readable and maintainable.
Rewriting the example above to use the include block so that it looks more like the kind of thing you’d see in a real project would look like this:
remote_state { backend = "s3"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { bucket = "my-tofu-state"
key = "tofu.tfstate" region = "us-east-1" encrypt = true dynamodb_table = "my-lock-table" }}
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "aws" { region = "us-east-1"}EOF}include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "tfr:///terraform-aws-modules/vpc/aws?version=5.16.0"}
inputs = { name = "my-vpc" cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"] private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"] public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
enable_nat_gateway = false enable_vpn_gateway = false
tags = { IaC = "true" Environment = "dev" }}remote_state { backend = "azurerm"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" container_name = "tfstate"
key = "tofu.tfstate" location = "eastus" use_azuread_auth = true assign_blob_data_role = true }}
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "azapi" { default_location = "eastus"}EOF}include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "tfr:///Azure/avm-res-resources-resourcegroup/azurerm?version=0.4.0"}
inputs = { name = "my-rg-eastus" location = "eastus"
tags = { IaC = "true" Environment = "dev" }}remote_state { backend = "gcs"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { project = "my-project" location = "us-central1" bucket = "my-tofu-state"
prefix = "tofu" }}
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "google" { project = "my-project" region = "us-central1"}EOF}
inputs = { project_id = "my-project"}include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "tfr:///terraform-google-modules/network/google?version=18.3.1"}
inputs = { network_name = "my-vpc-us-central1"
subnets = [ { subnet_name = "private" subnet_ip = "10.0.1.0/24" subnet_region = "us-central1" }, { subnet_name = "public" subnet_ip = "10.0.101.0/24" subnet_region = "us-central1" }, ]}Every Google module in this guide takes a project_id input, so root.hcl sets it once in its own inputs block. Terragrunt merges the included inputs into the unit’s inputs key by key, so each unit gets project_id without repeating it.
By doing this, you can see that it’s become easier to introduce new units of infrastructure, as you only need to define the unique parts of the configuration for that unit in the new terragrunt.hcl file. The shared configuration is inherited from the root.hcl file.
Run terragrunt plan in the unit’s directory before moving on. It should report no changes, because the unit still uses the same state. Running it also initializes the unit against that state, which the Migrating state section needs later.
When you see include blocks in Terragrunt, remember that they result in the configuration being inlined into the configuration file that includes them. For the most part, you can simply replace the relevant include block with the configuration it is including to see the full configuration that Terragrunt will use.
The exception to this is when you are using directives that explicitly leverage the fact that configurations are being included.
Building out the stack
Section titled “Building out the stack”To add another unit to this stack, create a directory with a terragrunt.hcl file:
include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "tfr:///terraform-aws-modules/ec2-instance/aws?version=5.7.1"}
dependency "vpc" { config_path = "../vpc"}
inputs = { name = "single-instance"
instance_type = "t2.micro" monitoring = true subnet_id = dependency.vpc.outputs.private_subnets[0]
tags = { IaC = "true" Environment = "dev" }}include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "tfr:///Azure/avm-res-network-virtualnetwork/azurerm?version=0.22.3"}
dependency "rg" { config_path = "../rg"}
inputs = { name = "my-vnet" location = "eastus" parent_id = dependency.rg.outputs.resource_id
address_space = ["10.0.0.0/16"]
subnets = { private = { name = "private" address_prefixes = ["10.0.1.0/24"] } public = { name = "public" address_prefixes = ["10.0.101.0/24"] } }
tags = { IaC = "true" Environment = "dev" }}include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "tfr:///terraform-google-modules/cloud-router/google?version=9.1.0"}
dependency "vpc" { config_path = "../vpc"}
inputs = { name = "my-router" region = "us-central1" network = dependency.vpc.outputs.network_name}Key Collisions
Section titled “Key Collisions”If you tried to run terragrunt plan in that new directory, you’d see something alarming:
$ terragrunt plan...16:31:14.176 STDOUT tofu: # aws_instance.this[0] will be created...16:31:14.178 STDOUT tofu: # aws_subnet.private[0] will be destroyed...16:31:14.179 STDOUT tofu: # aws_vpc.this[0] will be destroyed...16:31:14.179 STDOUT tofu: Plan: 1 to add, 0 to change, 22 to destroy.$ terragrunt plan...16:21:56.723 STDOUT tofu: # azapi_resource.this will be destroyed...16:21:56.723 STDOUT tofu: # azapi_resource.vnet will be created...16:21:56.723 STDOUT tofu: # module.subnet["private"].azapi_resource.subnet[0] will be created...16:21:56.723 STDOUT tofu: # module.subnet["public"].azapi_resource.subnet[0] will be created...16:21:56.724 STDOUT tofu: Plan: 3 to add, 0 to change, 1 to destroy.$ terragrunt plan...17:45:48.682 STDOUT tofu: # google_compute_router.router will be created...17:45:48.682 STDOUT tofu: # module.subnets.google_compute_subnetwork.subnetwork["us-central1/private"] will be destroyed...17:45:48.682 STDOUT tofu: # module.vpc.google_compute_network.network will be destroyed...17:45:48.683 STDOUT tofu: Plan: 1 to add, 0 to change, 3 to destroy.OpenTofu/Terraform wants to create the resources for the new unit, but it also wants to destroy everything the first unit created. Don’t apply this!
What’s happening here is that when Terragrunt invoked OpenTofu/Terraform, it generated exactly the same backend.tf file for the new unit of infrastructure as it did for the first unit, so both units are using the same state file.
You can see that in the newly generated backend.tf file in the .terragrunt-cache directory under the new unit:
$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "s3" { bucket = "my-tofu-state" dynamodb_table = "my-lock-table" encrypt = true key = "tofu.tfstate" region = "us-east-1" }}$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "azurerm" { container_name = "tfstate" key = "tofu.tfstate" resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" use_azuread_auth = true }}$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "gcs" { bucket = "my-tofu-state" prefix = "tofu" }}Dynamic keys
Section titled “Dynamic keys”Use each unit’s path relative to root.hcl in its backend state path. This keeps state paths distinct and predictable.
So this filesystem layout:
Directoryroot.hcl
Directoryvpc
- terragrunt.hcl
Directoryec2
- terragrunt.hcl
Would result in this state layout in S3:
Directorys3://my-tofu-state
Directoryvpc
- tofu.tfstate
Directoryec2
- tofu.tfstate
Directoryroot.hcl
Directoryrg
- terragrunt.hcl
Directoryvnet
- terragrunt.hcl
The mytofustate storage account then has this state layout:
Directorymytofustate
Directorytfstate
Directoryrg
- tofu.tfstate
Directoryvnet
- tofu.tfstate
Directoryroot.hcl
Directoryvpc
- terragrunt.hcl
Directoryrouter
- terragrunt.hcl
Would result in this state layout in the my-tofu-state bucket:
Directorygs://my-tofu-state
Directoryvpc
- default.tfstate
Directoryrouter
- default.tfstate
Use path_relative_to_include() to build each unit’s state path from its directory relative to root.hcl.
remote_state { backend = "s3"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { bucket = "my-tofu-state"
key = "${path_relative_to_include()}/tofu.tfstate" # <-- region = "us-east-1" encrypt = true dynamodb_table = "my-lock-table" }}
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "aws" { region = "us-east-1"}EOF}remote_state { backend = "azurerm"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" container_name = "tfstate"
key = "${path_relative_to_include()}/tofu.tfstate" # <-- location = "eastus" use_azuread_auth = true assign_blob_data_role = true }}
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "azapi" { default_location = "eastus"}EOF}remote_state { backend = "gcs"
generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" }
config = { project = "my-project" location = "us-central1" bucket = "my-tofu-state"
prefix = path_relative_to_include() # <-- }}
generate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "google" { project = "my-project" region = "us-central1"}EOF}
inputs = { project_id = "my-project"}The gcs backend has no key attribute. prefix sets the directory that state goes in, and the backend names the file default.tfstate itself.
What this does is set the state path in the generated backend.tf file to the relative path from the root.hcl file to the terragrunt.hcl file that is being processed.
Migrating state
Section titled “Migrating state”Changing a unit’s state path makes the backend look for state at a new location. Moving a unit can have this effect when its state path uses path_relative_to_include(). If you want to keep managing the existing resources, migrate the state before applying.
There’s native tooling in OpenTofu/Terraform to support these procedures, but you want to be confident you know what you’re doing when you run them. By default, Terragrunt will provision a remote backend that uses versioning, so you can always roll back to a previous state if you need to.
# Within the vpc directory# First, we'll migrate state to the new location# Answer "yes" when OpenTofu asks whether to copy existing state to the new backend$ terragrunt init -migrate-state# Then, let's take a look at the generated backend.tf file$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "s3" { bucket = "my-tofu-state" dynamodb_table = "my-lock-table" encrypt = true key = "vpc/tofu.tfstate" region = "us-east-1" }}The ec2 unit was initialized against the shared key, so it has to be re-initialized against its own key before it can be planned. There is nothing to migrate for it, as it has never been applied:
# Within the ec2 directory$ terragrunt init -reconfigureNow, we can run the plan in the ec2 directory without any issues:
# Within the ec2 directory$ terragrunt plan...$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "s3" { bucket = "my-tofu-state" dynamodb_table = "my-lock-table" encrypt = true key = "ec2/tofu.tfstate" region = "us-east-1" }}# Within the rg directory# First, we'll migrate state to the new location# Answer "yes" when OpenTofu asks whether to copy existing state to the new backend$ terragrunt init -migrate-state# Then, let's take a look at the generated backend.tf file$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "azurerm" { container_name = "tfstate" key = "rg/tofu.tfstate" resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" use_azuread_auth = true }}The vnet unit was initialized against the shared key, so it has to be re-initialized against its own key before it can be planned. There is nothing to migrate for it, as it has never been applied:
# Within the vnet directory$ terragrunt init -reconfigureNow, we can run the plan in the vnet directory without any issues:
# Within the vnet directory$ terragrunt plan...$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "azurerm" { container_name = "tfstate" key = "vnet/tofu.tfstate" resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" use_azuread_auth = true }}# Within the vpc directory# First, we'll migrate state to the new location# Answer "yes" when OpenTofu asks whether to copy existing state to the new backend$ terragrunt init -migrate-state# Then, let's take a look at the generated backend.tf file$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "gcs" { bucket = "my-tofu-state" prefix = "vpc" }}The router unit was initialized against the shared prefix, so it has to be re-initialized against its own prefix before it can be planned. There is nothing to migrate for it, as it has never been applied:
# Within the router directory$ terragrunt init -reconfigureNow, we can run the plan in the router directory without any issues:
# Within the router directory$ terragrunt plan...$ find .terragrunt-cache -name backend.tf -exec cat {} \;# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEaterraform { backend "gcs" { bucket = "my-tofu-state" prefix = "router" }}Go ahead and apply that plan with terragrunt apply, so both units exist for the next section.
init -migrate-state copies the state to its new location and leaves the original at the old one. After verifying the new state and retiring configurations that use the old location, remove or archive the old copy.
Following this pattern, you can create as many units of infrastructure in your project as you like without worrying about collisions in remote state keys.
You can choose another state path or generate one with a Terragrunt HCL function, provided each unit gets a unique one.
Another completely valid approach, for example, is to utilize get_repo_root, which returns a path relative to the root of the git repository. This, of course, has the drawback that it will not work if you are not using git.
Just make sure to test your configuration carefully, and document your approach so that others can understand what you’re doing.
The dependency block
Section titled “The dependency block”You might have noticed that the second unit of infrastructure has a dependency block in its configuration:
# ...dependency "vpc" { config_path = "../vpc"}
inputs = { name = "single-instance"
instance_type = "t2.micro" monitoring = true subnet_id = dependency.vpc.outputs.private_subnets[0]
tags = { IaC = "true" Environment = "dev" }}This block tells Terragrunt that the ec2 unit depends on the output of the vpc unit. You can also see that it references that dependency within the inputs block as dependency.vpc.outputs.private_subnets[0].
# ...dependency "rg" { config_path = "../rg"}
inputs = { name = "my-vnet" location = "eastus" parent_id = dependency.rg.outputs.resource_id
# ...}This block tells Terragrunt that the vnet unit depends on the output of the rg unit. You can also see that it references that dependency within the inputs block as dependency.rg.outputs.resource_id.
# ...dependency "vpc" { config_path = "../vpc"}
inputs = { name = "my-router" region = "us-central1" network = dependency.vpc.outputs.network_name}This block tells Terragrunt that the router unit depends on the output of the vpc unit. You can also see that it references that dependency within the inputs block as dependency.vpc.outputs.network_name.
When Terragrunt is performing a run for a dependency, it will first run terragrunt output in the dependency, then expose the values from that output as values that can be used in the dependent unit.
This is a very useful mechanism, as it keeps each unit isolated, while allowing for message passing between units when they need to interact.
The Directed Acyclic Graph (DAG)
Section titled “The Directed Acyclic Graph (DAG)”Dependencies also give Terragrunt a way to reason about the order in which units of infrastructure should be run. It uses what’s called a Directed Acyclic Graph (DAG) to determine the order in which units should be run, and then runs them in that order.
For example, let’s go ahead and destroy all the infrastructure that we’ve created so far:
# From the root directory$ terragrunt run --all destroy16:32:08.944 INFO The following units will be run, starting with dependents and then their dependencies:.╰── ec2 ╰── vpcWARNING: Are you sure you want to run `terragrunt destroy` in each unit of the run queue displayed above? There is no undo! (y/n)# From the root directory$ terragrunt run --all destroy16:32:08.944 INFO The following units will be run, starting with dependents and then their dependencies:.╰── vnet ╰── rgWARNING: Are you sure you want to run `terragrunt destroy` in each unit of the run queue displayed above? There is no undo! (y/n)# From the root directory$ terragrunt run --all destroy16:32:08.944 INFO The following units will be run, starting with dependents and then their dependencies:.╰── router ╰── vpcWARNING: Are you sure you want to run `terragrunt destroy` in each unit of the run queue displayed above? There is no undo! (y/n)First, notice that we’re using a special run --all command for Terragrunt. This command tells Terragrunt that we’re operating on a stack of units, and that we want to run a given OpenTofu/Terraform command on all of them.
Second, notice that the dependent unit is listed first, and is run before the unit it depends on. Terragrunt knows about the dependency, so it plans to run the dependent unit first, followed by its dependency.
This is a simple example, but as you build out more complex stacks of infrastructure, you’ll find that Terragrunt’s dependency resolution is a powerful tool for getting infrastructure provisioned correctly.
Go ahead and answer y to the prompt to allow destruction to proceed, and notice that the logging has also changed slightly:
16:33:28.820 STDOUT [ec2] tofu: aws_instance.this[0]: Destruction complete after 1m11s16:33:28.936 STDOUT [ec2] tofu:16:33:28.936 STDOUT [ec2] tofu: Destroy complete! Resources: 1 destroyed.16:33:28.936 STDOUT [ec2] tofu:16:33:30.713 STDOUT [vpc] tofu: aws_vpc.this[0]: Refreshing state... [id=vpc-063d11b72a2c9f8b3]16:33:31.510 STDOUT [vpc] tofu: aws_default_security_group.this[0]: Refreshing state... [id=sg-060d402b95a2cd935]16:33:31.511 STDOUT [vpc] tofu: aws_default_route_table.default[0]: Refreshing state... [id=rtb-05adb3ee7f48640f0]16:29:09.531 STDOUT [vnet] tofu: azapi_resource.vnet: Destruction complete after 12s16:29:10.149 STDOUT [vnet] tofu: Destroy complete! Resources: 7 destroyed.16:29:14.379 STDOUT [rg] tofu: azapi_resource.this: Refreshing state... [id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg-eastus]16:29:15.504 STDOUT [rg] tofu: azapi_resource.this: Destroying... [id=/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg-eastus]16:29:33.808 STDOUT [rg] tofu: azapi_resource.this: Destruction complete after 18s16:29:34.421 STDOUT [rg] tofu: Destroy complete! Resources: 5 destroyed.16:33:14.620 STDOUT [router] tofu: google_compute_router.router: Destruction complete after 11s16:33:14.847 STDOUT [router] tofu: Destroy complete! Resources: 1 destroyed.16:33:16.747 STDOUT [vpc] tofu: module.vpc.google_compute_network.network: Refreshing state... [id=projects/my-project/global/networks/my-vpc-us-central1]16:33:29.388 STDOUT [vpc] tofu: module.vpc.google_compute_network.network: Destroying... [id=projects/my-project/global/networks/my-vpc-us-central1]16:33:51.486 STDOUT [vpc] tofu: module.vpc.google_compute_network.network: Destruction complete after 22s16:33:51.890 STDOUT [vpc] tofu: Destroy complete! Resources: 3 destroyed.Prefixes such as [vpc] and [rg] identify which unit produced an output line.
Mock outputs
Section titled “Mock outputs”Now that the stack has been destroyed, take a look at the error you get when you try to run terragrunt run --all plan again:
$ terragrunt run --all plan...16:50:22.677 ERROR [ec2] Error: Unknown variable16:50:22.677 ERROR [ec2] on /path/to/project/ec2/terragrunt.hcl line 19:16:50:22.677 ERROR [ec2] 19: subnet_id = dependency.vpc.outputs.private_subnets[0]16:50:22.677 ERROR [ec2] There is no variable named "dependency".16:50:22.678 ERROR Run failed: 2 errors occurred:
* resolving dependency "vpc" outputs: /path/to/project/vpc/terragrunt.hcl is a dependency of /path/to/project/ec2/terragrunt.hcl but detected no outputs. Either the target module has not been applied yet, or the module has no outputs.
If this dependency is accessed before the outputs are ready (which can happen during the planning phase of an unapplied stack), consider using mock_outputs:
dependency "vpc" { config_path = "../vpc"
mock_outputs = { vpc_output = "mock-vpc-output" } }...$ terragrunt run --all plan...16:50:22.677 ERROR [vnet] Error: Unknown variable16:50:22.677 ERROR [vnet] on /path/to/project/vnet/terragrunt.hcl line 17:16:50:22.677 ERROR [vnet] 17: parent_id = dependency.rg.outputs.resource_id16:50:22.677 ERROR [vnet] There is no variable named "dependency".16:50:22.678 ERROR Run failed: 2 errors occurred:
* resolving dependency "rg" outputs: /path/to/project/rg/terragrunt.hcl is a dependency of /path/to/project/vnet/terragrunt.hcl but detected no outputs. Either the target module has not been applied yet, or the module has no outputs.
If this dependency is accessed before the outputs are ready (which can happen during the planning phase of an unapplied stack), consider using mock_outputs:
dependency "rg" { config_path = "../rg"
mock_outputs = { rg_output = "mock-rg-output" } }...$ terragrunt run --all plan...16:50:22.677 ERROR [router] Error: Unknown variable16:50:22.677 ERROR [router] on /path/to/project/router/terragrunt.hcl line 17:16:50:22.677 ERROR [router] 17: network = dependency.vpc.outputs.network_name16:50:22.677 ERROR [router] There is no variable named "dependency".16:50:22.678 ERROR Run failed: 2 errors occurred:
* resolving dependency "vpc" outputs: /path/to/project/vpc/terragrunt.hcl is a dependency of /path/to/project/router/terragrunt.hcl but detected no outputs. Either the target module has not been applied yet, or the module has no outputs.
If this dependency is accessed before the outputs are ready (which can happen during the planning phase of an unapplied stack), consider using mock_outputs:
dependency "vpc" { config_path = "../vpc"
mock_outputs = { vpc_output = "mock-vpc-output" } }...The error emitted here tells us that the dependency doesn’t have any outputs available yet for the dependent unit to consume, so the dependency.*.outputs reference can’t be resolved.
The pattern most commonly used to address this is to simply mock the unavailable output during plans.
Update the dependent unit’s dependency block:
# ...dependency "vpc" { config_path = "../vpc"
mock_outputs = { private_subnets = ["mock-subnet"] }
mock_outputs_allowed_terraform_commands = ["plan"]}# ...# ...dependency "rg" { config_path = "../rg"
mock_outputs = { resource_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mock-rg" }
mock_outputs_allowed_terraform_commands = ["plan"]}# ...# ...dependency "vpc" { config_path = "../vpc"
mock_outputs = { network_name = "mock-network" }
mock_outputs_allowed_terraform_commands = ["plan"]}# ...Then run the plan again:
$ terragrunt run --all plan...16:53:04.037 STDOUT [ec2] tofu: + source_dest_check = true16:53:04.037 STDOUT [ec2] tofu: + spot_instance_request_id = (known after apply)16:53:04.037 STDOUT [ec2] tofu: + subnet_id = "mock-subnet"16:53:04.037 STDOUT [ec2] tofu: + tags = {16:53:04.038 STDOUT [ec2] tofu: + "Environment" = "dev"...$ terragrunt run --all plan...16:30:34.850 WARN [vnet] Config /path/to/project/rg/terragrunt.hcl is a dependency of /path/to/project/vnet/terragrunt.hcl that has no outputs, but mock outputs provided and returning those in dependency output....16:30:39.449 STDOUT [vnet] tofu: # azapi_resource.vnet will be created16:30:39.449 STDOUT [vnet] tofu: + resource "azapi_resource" "vnet" {16:30:39.449 STDOUT [vnet] tofu: + id = (known after apply)16:30:39.450 STDOUT [vnet] tofu: + location = "eastus"16:30:39.450 STDOUT [vnet] tofu: + name = "my-vnet"16:30:39.450 STDOUT [vnet] tofu: + parent_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mock-rg"...$ terragrunt run --all plan...16:53:02.298 WARN [router] Config /path/to/project/vpc/terragrunt.hcl is a dependency of /path/to/project/router/terragrunt.hcl that has no outputs, but mock outputs provided and returning those in dependency output....16:53:04.037 STDOUT [router] tofu: # google_compute_router.router will be created16:53:04.037 STDOUT [router] tofu: + resource "google_compute_router" "router" {16:53:04.037 STDOUT [router] tofu: + creation_timestamp = (known after apply)16:53:04.037 STDOUT [router] tofu: + encrypted_interconnect_router = false16:53:04.037 STDOUT [router] tofu: + id = (known after apply)16:53:04.037 STDOUT [router] tofu: + name = "my-router"16:53:04.037 STDOUT [router] tofu: + network = "mock-network"16:53:04.038 STDOUT [router] tofu: + project = "my-project"16:53:04.038 STDOUT [router] tofu: + region = "us-central1"...The dependent unit’s plan now uses the value from mock_outputs.
Terragrunt only uses these mock values when the output is unavailable, so a terragrunt run --all apply would succeed, but it’s best practice to explicitly tell Terragrunt that it should only use these mock values during a plan (or any other command where you are okay with the output being mocked).
Also note that when you run terragrunt run --all apply:
$ terragrunt run --all apply16:57:32.297 INFO The following units will be run, starting with dependencies and then their dependents:.╰── vpc ╰── ec2Are you sure you want to run 'terragrunt apply' in each unit of the run queue displayed above? (y/n)$ terragrunt run --all apply16:57:32.297 INFO The following units will be run, starting with dependencies and then their dependents:.╰── rg ╰── vnetAre you sure you want to run 'terragrunt apply' in each unit of the run queue displayed above? (y/n)$ terragrunt run --all apply16:57:32.297 INFO The following units will be run, starting with dependencies and then their dependents:.╰── vpc ╰── routerAre you sure you want to run 'terragrunt apply' in each unit of the run queue displayed above? (y/n)That the order of units has flipped. Terragrunt knows that during applies, dependencies actually need to be run before the dependent unit, so it’s flipped the order of the units in the stack, relative to destroys.
You can answer y to allow the apply to proceed and see that the dependent unit is given the real output of its dependency (not the mock value) as expected.
Configuration hierarchy
Section titled “Configuration hierarchy”Terragrunt also provides tooling for constructing a hierarchy of configurations that can be used to manage multiple environments, regions, or accounts.
To provision the same resources in multiple regions, use a layout like this:
- root.hcl
Directoryus-east-1
Directoryvpc
- terragrunt.hcl
Directoryec2
- terragrunt.hcl
Directoryus-west-2
Directoryvpc
- terragrunt.hcl
Directoryec2
- terragrunt.hcl
- root.hcl
Directoryeastus
Directoryrg
- terragrunt.hcl
Directoryvnet
- terragrunt.hcl
Directorywestus2
Directoryrg
- terragrunt.hcl
Directoryvnet
- terragrunt.hcl
- root.hcl
Directoryus-central1
Directoryvpc
- terragrunt.hcl
Directoryrouter
- terragrunt.hcl
Directoryus-east1
Directoryvpc
- terragrunt.hcl
Directoryrouter
- terragrunt.hcl
Create a directory for the region you have used so far, then copy the existing units into it:
mkdir us-east-1cp -R vpc ec2 us-east-1/mkdir eastuscp -R rg vnet eastus/mkdir us-central1cp -R vpc router us-central1/Moving a unit changes the value of path_relative_to_include(), and with it the key where its state is stored, so the state has to move too. The backend migrate command does that for you. Migrate dependencies before their dependents, then remove the old copies:
terragrunt backend migrate vpc us-east-1/vpcterragrunt backend migrate ec2 us-east-1/ec2rm -rf vpc ec2terragrunt backend migrate rg eastus/rgterragrunt backend migrate vnet eastus/vnetrm -rf rg vnetterragrunt backend migrate vpc us-central1/vpcterragrunt backend migrate router us-central1/routerrm -rf vpc routerWe want the region used by our units to be determined dynamically, so we can add a configuration file to the new region directory that looks like this:
locals { region = "us-east-1"}locals { region = "eastus"}locals { region = "us-central1"}Then update the root.hcl like so:
locals { region_hcl = find_in_parent_folders("region.hcl") region = read_terragrunt_config(local.region_hcl).locals.region}
# Configure the remote backendremote_state { backend = "s3" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { bucket = "my-tofu-state"
key = "${path_relative_to_include()}/tofu.tfstate" region = "us-east-1" encrypt = true dynamodb_table = "my-lock-table" }}
# Configure the AWS providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "aws" { region = "${local.region}"}EOF}Now, when the configurations in the us-east-1 directory include the root.hcl, they’ll automatically parse the first region.hcl file they find while traversing up the filesystem, and use the region value defined in that file to set the AWS region for the provider.
locals { region_hcl = find_in_parent_folders("region.hcl") region = read_terragrunt_config(local.region_hcl).locals.region}
# Configure the remote backendremote_state { backend = "azurerm" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" container_name = "tfstate"
key = "${path_relative_to_include()}/tofu.tfstate" location = "eastus" use_azuread_auth = true assign_blob_data_role = true }}
# Configure the Azure providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "azapi" { default_location = "${local.region}"}EOF}Now, when the configurations in the eastus directory include the root.hcl, they’ll automatically parse the first region.hcl file they find while traversing up the filesystem, and use the region value defined in that file to set the default location for the provider.
The provider’s default_location only applies to resources that don’t set a location of their own. The modules used in this guide always set it explicitly, so the next section shows how to make the units pick up the region as well.
locals { region_hcl = find_in_parent_folders("region.hcl") region = read_terragrunt_config(local.region_hcl).locals.region}
# Configure the remote backendremote_state { backend = "gcs" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { project = "my-project" location = "us-central1" bucket = "my-tofu-state"
prefix = path_relative_to_include() }}
# Configure the Google providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "google" { project = "my-project" region = "${local.region}"}EOF}
inputs = { project_id = "my-project"}Now, when the configurations in the us-central1 directory include the root.hcl, they’ll automatically parse the first region.hcl file they find while traversing up the filesystem, and use the region value defined in that file to set the default region for the provider.
The provider’s region only applies to resources that don’t set a region of their own. The units in this guide set it explicitly, so the next section shows how to make them pick up the region as well.
NOTE In the generate block, we’re using "${local.region}", rather than local.region. This is because the generate block is going to generate a file directly into the OpenTofu/Terraform module. We need to ensure that when the value is interpolated, it’s done so in a way that OpenTofu/Terraform can understand, so we wrap it in quotes.
This example keeps state in one region. You can use a different region for the backend by changing the remote_state configuration.
Exposed includes
Section titled “Exposed includes”Before moving on, take note of one thing: some values in the units are still tied to the first region.
The azs attribute in the vpc unit of the us-east-1 stack is hardcoded to ["us-east-1a", "us-east-1b", "us-east-1c"].
This would cause issues if we were to try to deploy the vpc unit in the us-west-2 stack, as those availability zones don’t exist in the us-west-2 region. What we need to do is make the azs attribute dynamic and use the resolved region to determine the correct availability zones.
The location input in both the rg and vnet units of the eastus stack is hardcoded to "eastus", and the resource group is named my-rg-eastus.
Copying those units into westus2 as-is would still create resources in eastus. It would also reuse the resource group name, which Azure forbids within a subscription. Use the resolved region for both location and the resource group name.
The subnet_region of each subnet in the vpc unit and the region input of the router unit in the us-central1 stack are hardcoded to "us-central1", and so is the network name, my-vpc-us-central1.
If we copied those units into a us-east1 stack as-is, they would still create the subnets and router in us-central1, and the second network would collide with the first (network names are unique within a project). What we need to do is make those region inputs and the network name dynamic, using the resolved region.
To do this, we can expose the attributes on the included root configuration by setting the expose attribute to true:
include "root" { path = find_in_parent_folders("root.hcl") expose = true}
locals { region = include.root.locals.region}
# Configure the module# The URL used here is a shorthand for# "tfr://registry.terraform.io/terraform-aws-modules/vpc/aws?version=5.16.0".# Note the extra `/` after the protocol is required for the shorthand# notation.terraform { source = "tfr:///terraform-aws-modules/vpc/aws?version=5.16.0"}
# Configure the inputs for the moduleinputs = { name = "my-vpc" cidr = "10.0.0.0/16"
azs = ["${local.region}a", "${local.region}b", "${local.region}c"] # <-- private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"] public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
enable_nat_gateway = false enable_vpn_gateway = false
tags = { IaC = "true" Environment = "dev" }}include "root" { path = find_in_parent_folders("root.hcl") expose = true}
locals { region = include.root.locals.region}
terraform { source = "tfr:///Azure/avm-res-resources-resourcegroup/azurerm?version=0.4.0"}
inputs = { name = "my-rg-${local.region}" # <-- location = local.region # <--
tags = { IaC = "true" Environment = "dev" }}include "root" { path = find_in_parent_folders("root.hcl") expose = true}
locals { region = include.root.locals.region}
terraform { source = "tfr:///Azure/avm-res-network-virtualnetwork/azurerm?version=0.22.3"}
dependency "rg" { config_path = "../rg"
mock_outputs = { resource_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mock-rg-${local.region}" }
mock_outputs_allowed_terraform_commands = ["plan"]}
inputs = { name = "my-vnet" location = local.region # <-- parent_id = dependency.rg.outputs.resource_id
address_space = ["10.0.0.0/16"]
subnets = { private = { name = "private" address_prefixes = ["10.0.1.0/24"] } public = { name = "public" address_prefixes = ["10.0.101.0/24"] } }
tags = { IaC = "true" Environment = "dev" }}include "root" { path = find_in_parent_folders("root.hcl") expose = true}
locals { region = include.root.locals.region}
terraform { source = "tfr:///terraform-google-modules/network/google?version=18.3.1"}
inputs = { network_name = "my-vpc-${local.region}" # <--
subnets = [ { subnet_name = "private" subnet_ip = "10.0.1.0/24" subnet_region = local.region # <-- }, { subnet_name = "public" subnet_ip = "10.0.101.0/24" subnet_region = local.region # <-- }, ]}include "root" { path = find_in_parent_folders("root.hcl") expose = true}
locals { region = include.root.locals.region}
terraform { source = "tfr:///terraform-google-modules/cloud-router/google?version=9.1.0"}
dependency "vpc" { config_path = "../vpc"
mock_outputs = { network_name = "mock-network-${local.region}" }
mock_outputs_allowed_terraform_commands = ["plan"]}
inputs = { name = "my-router" region = local.region # <-- network = dependency.vpc.outputs.network_name}These inputs now derive their region-specific values from region.hcl.
Run terragrunt run --all plan from the region directory to confirm it. Both units should report no changes, as the dynamic values resolve to exactly what was hardcoded before.
Now that you’ve set up the first region, you can repeat the process for a second one:
cp -R us-east-1/ us-west-2/Then update the region.hcl file in the us-west-2 directory to set the region to us-west-2:
locals { region = "us-west-2"}cp -R eastus/ westus2/Then update the region.hcl file in the westus2 directory to set the region to westus2:
locals { region = "westus2"}cp -R us-central1/ us-east1/Then update the region.hcl file in the us-east1 directory to set the region to us-east1:
locals { region = "us-east1"}Tightening the blast radius
Section titled “Tightening the blast radius”Run the terragrunt run --all apply command after changing your current working directory to the second region’s directory:
cd us-west-2terragrunt run --all applyYou should see the VPC and EC2 instances being provisioned in the us-west-2 region.
cd westus2terragrunt run --all applyYou should see the resource group and virtual network being provisioned in the westus2 region.
cd us-east1terragrunt run --all applyYou should see the VPC network, its subnets and the Cloud Router being provisioned in the us-east1 region.
This showcases three superpowers you gain when you leverage Terragrunt:
- Automatic DAG Resolution: Terragrunt runs dependencies before the units that use them.
- Dynamic Configuration: Change
region.hclto deploy the same unit files in another region. - Reduced Blast Radius: Running
terragrunt run --allfrom a region directory limits the run to units in that directory. Your working directory sets the blast radius.
Cleanup
Section titled “Cleanup”If you still have all the resources that were provisioned as part of this tutorial active, this is a reminder that you might want to clean them up.
To destroy all the resources you’ve provisioned thus far, run the following:
# From the root directory$ terragrunt run --all destroyIn real-world scenarios, it’s generally advised that you plan your destroys first before cleaning them up:
# From the root directory$ terragrunt run --all -- plan -destroyYou won’t need to run any more Terragrunt commands for the rest of this guide.
Recommended Repository Patterns
Section titled “Recommended Repository Patterns”Outside of the patterns used for setting up Terragrunt configurations within a project, there are also some patterns that we recommend for managing one or more repositories used to manage infrastructure. At Gruntwork, we refer to this as your “Infrastructure Estate”.
These recommendations are merely guidelines, and you should adapt them to suit your team’s needs and constraints.
infrastructure-live
Section titled “infrastructure-live”The core of the infrastructure you manage with a Terragrunt is typically stored in a repository named infrastructure-live (or some variant of it). This repository is where you store the Terragrunt configurations used for infrastructure that is intended to be “live” (i.e. provisioned and active).
Most successful teams stick to Trunk Based Development, perform plans on any change being proposed via a pull request / merge request, and only apply changes to live infrastructure after a successful plan and review.
This repository is generally concerned with the configuration of reliably reproducible, immutable and versioned infrastructure. You generally don’t author OpenTofu/Terraform code directly into it, and you apply appropriate branch protection rules to ensure that changes are merged only if they get the appropriate sign-off from responsible parties.
What’s on the default branch for this repository is generally considered the source of truth for the infrastructure you have provisioned. That default branch is generally the only version that matters when considering the state of your infrastructure.
Gruntwork maintains example infrastructure-live repositories for each cloud:
infrastructure-modules
Section titled “infrastructure-modules”The patterns for your infrastructure you want to reliably reproduce. This repository is where you store the OpenTofu/Terraform modules that you use in your infrastructure-live repository.
This repository is generally concerned with maintaining versioned, well tested and vetted patterns of infrastructure, ready to be consumed by the infrastructure-live repository.
You typically integrate this repository with tools like Terratest to ensure that every change to a module is well tested and reliable.
Semantic Versioning is widely used to manage communicating the impact of updates to this repository, and you typically pin the version of a consumed module in the infrastructure-live repository to a specific tag.
You can see an example of this in the terragrunt-infrastructure-catalog-example repository maintained by Gruntwork. It keeps Azure and GCP modules under modules/azure and modules/gcp, next to the AWS modules.
Atomic Deployments
Section titled “Atomic Deployments”Following the repository patterns outlined above, you typically see Terragrunt repositories that have configurations which look like this:
include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "github.com:foo/infrastructure-modules.git//app?ref=v0.0.1"}
inputs = { instance_count = 3 instance_type = "t2.micro"}Where app is an opinionated module in the infrastructure-modules repository, maintained by the team managing infrastructure for the foo organization.
The code in that module might be hand-rolled, it may wrap a community maintained module, or it might wrap a module like one found in the Gruntwork IaC Library.
Regardless, the module is something that the team managing infrastructure for an organization has vetted for deployment.
When deploying a change to live infrastructure, the team would typically make a change like the following:
include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "github.com:foo/infrastructure-modules.git//app?ref=v0.0.2" # <--}
inputs = { instance_count = 1 instance_type = "t3.micro"}Given that all the changes here are part of one atomic deployment, it’s fairly easy to determine the impact of the change, and to roll back if necessary.
After that, they would propagate the change up however many intermediary environments they have, and finally to production.
include "root" { path = find_in_parent_folders("root.hcl")}
terraform { source = "github.com:foo/infrastructure-modules.git//app?ref=v0.0.2" # <--}
inputs = { instance_count = 3 instance_type = "t3.large"}Note that the two terragrunt.hcl files here have different inputs values, as those values are specific to the environment they are being deployed to.
The end result of this process is that infrastructure changes are atomic and reproduceable, and that the infrastructure being deployed is versioned and immutable.

If at any point during this process a change is found to be problematic, the team can simply roll back to the previous version of the module for a single unit in a given environment.
That’s the power of reducing your blast radius with Terragrunt!
Keep It Simple, Silly
Section titled “Keep It Simple, Silly”One last pattern to internalize is the general tendency to prefer simple configurations over complex ones when possible.
Terragrunt provides a lot of power and flexibility, but it’s generally best to use that power to make your configurations more readable and maintainable. Keep in mind that you’re writing code that will be read by other humans, and that you might not be around to explain any complexity you introduce.
As an example, consider one potential solution to a step outlined in the Exposed includes section, the requirement to update the region local in the region.hcl file:
locals { region = "us-west-2"}locals { region = "westus2"}locals { region = "us-east1"}You might think to yourself “Hey, I know a lot about Terragrunt functionality, I can make this more dynamic, such that I don’t even need to create a region.hcl file!” and come up with a solution like this:
locals { region = split("/", path_relative_to_include())[0]}
# Configure the remote backendremote_state { backend = "s3" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { bucket = "my-tofu-state"
key = "${path_relative_to_include()}/tofu.tfstate" region = "us-east-1" encrypt = true dynamodb_table = "my-lock-table" }}
# Configure the AWS providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "aws" { region = "${local.region}"}EOF}locals { region = split("/", path_relative_to_include())[0]}
# Configure the remote backendremote_state { backend = "azurerm" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { resource_group_name = "my-tofu-state" storage_account_name = "mytofustate" container_name = "tfstate"
key = "${path_relative_to_include()}/tofu.tfstate" location = "eastus" use_azuread_auth = true assign_blob_data_role = true }}
# Configure the Azure providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "azapi" { default_location = "${local.region}"}EOF}locals { region = split("/", path_relative_to_include())[0]}
# Configure the remote backendremote_state { backend = "gcs" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { project = "my-project" location = "us-central1" bucket = "my-tofu-state"
prefix = path_relative_to_include() }}
# Configure the Google providergenerate "provider" { path = "provider.tf" if_exists = "overwrite_terragrunt" contents = <<EOFprovider "google" { project = "my-project" region = "${local.region}"}EOF}
inputs = { project_id = "my-project"}With this expression, region is the first directory in the path relative to root.hcl. You could then remove the region.hcl files.
Consider, though, that this might make the configuration harder to understand for someone who is not as familiar with Terragrunt as you are. You’ve now tightly coupled the name of the directory to the region that the infrastructure is being deployed to, and you’ve made it harder for someone to understand if they run into issues.
Say a user tries to deploy infrastructure while on a Windows machine, where the path separator is \ instead of /. Using this configuration would result in the region local being set to the region and unit directory names joined by a backslash, which is confusing and not what you want.
In this case, you might prefer to have kept the region.hcl file, as it makes the configuration more explicit and easier to understand.
On the other hand, maybe you work with a team that’s very comfortable with Terragrunt, exclusively using Unix-based systems, and you’ve all agreed and documented this as a good pattern to follow. In that case, this might be a perfectly acceptable solution.
You have to exercise your best judgment when deciding how much complexity to introduce into your Terragrunt configurations. As a general rule, the best patterns to follow are the ones that are easiest to reproduce, understand, and maintain.
Next steps
Section titled “Next steps”Now that you’ve learned the basics of Terragrunt, here is some further reading to learn more:
-
Features: Learn about the core features Terragrunt supports.
-
Documentation: Check out the detailed Terragrunt reference documentation.
-
Fundamentals of DevOps and Software Delivery: Learn the fundamentals of DevOps and Software Delivery from one of the founders of Gruntwork!
-
Terraform: Up & Running: Terragrunt is a direct implementation of many of the ideas from this book.