Terragrunt with modules of terraform using local state instead of s3 remote state

4k Views Asked by At

I am using terragrunt to create an environment using the approach of storing the remote state into my local path.

remote_state {
  backend = "local"
  config = {
        path= "../..//mypath/terraform.tfstate"
  }
}

but because terragrunt downloads the terraform modules in a temporary folder by default .terragrunt-cache, it does not set them in the original path but in the temporary path. I am using the following command in the path where my root file is located:

terragrunt run-all apply --terragrunt-download-dir C:\Tempfile Using --terragrunt-download-dir but this will only downloads the temporal folder in a specific path and i want to set my terraform.tfstate in the original path not the temporary folder.

2

There are 2 best solutions below

0
On

You can specify where the terraform.state will be save by using TerraGrunt to write the backend.tf so that is also sets the path for the state file, like so:

remote_state {
  backend = "local"
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite"
  }
  config = {
    path = "${get_terragrunt_dir()}/terraform.tfstate"
  }
}

backend.tf should look something like:

# Generated by Terragrunt. Sig: nIlQXj57tbuaRZEa
terraform {
  backend "local" {
    path = "C:/Users/Imposter/src/github.com/sample/technology-iac/test/iac-backend/terraform.tfstate"
  }
}

  1. The generate block will generate a "backend.tf" file in the Terraform module that it downloads into the .terragrunt-cache directory.
  2. The get_terragrunt_dir() function will be replace with the path to the directory that holds the terragrunt.hcl. See the TerraGrunt build-in function get_terragrunt_dir() for details.
  3. That will cause Terraform to place the state file in the same directory as the terragrunt.hcl file.

Note this means that you would need to remove backend config from any other *.tf files.

Also, if you have terragrunt.hcl files that are only meant to be included in other terragrunt.hcl modules or do not produce any infrastructure, then you'll want to make use of TerraGrunt's skip attribute so the run-all apply command does not try to process them.

Tested with terragrunt version v0.42.5 and Terraform v1.3.6 on Windows.

0
On

You need to combine both the absolute and relative paths:

remote_state {
  backend = "local"
  config = {
    path = "${get_parent_terragrunt_dir()}/${path_relative_to_include()}/terraform.tfstate"
  }

  generate = {
    path = "backend.tf"
    if_exists = "overwrite"
  }
}

You'll know it's working when you see terraform.tfstate files in each folder containing a terragrunt.hcl.

More context: terragrunt/issues/2179