0

I have a Terraform/Terragrunt project to automate the creation of and ECR repository and several Fargate instances (test, uat, production) to host images from that repository (depending on how far they've progressed through the testing cycle).

Each environment/fargate instance is in its own module, whilst the ECR repo (shared by all environments) is in another. The environments' modules need to reference the ECR module in order to get the ARN for this resource. I've seen I can get this info using a terraform_remote_state data block, but that requires hardcoding the ECR module's bucket & key details in the environments' modules; which goes against the approach I'm using to create these state files (i.e. using a Terragrunt root file to specify a dynamically generated backend file per module).

Is there a way to reference a remote state file from another module without relying on hardcoding, whilst still benefiting from a dynamically created backend file?

Additional Info

The project is structured like this; i.e. following the example given in this terragrunt repo:

└ terragrunt.hcl
└ project.json
└ myAwsAccount
   └ account.json
   └ eu-west-1
      └ region.json
      └ _global
         └ environment.json
         └ ecr
            └ terragrunt.hcl
      └ test
         └ environment.json
         └ ecs
            └ terragrunt.hcl

In the root terragrunt.hcl file I configure remote state for the subfolders using the following:

locals {
    project_vars = jsondecode(file(find_in_parent_folders("project.json")))
    account_vars = jsondecode(file(find_in_parent_folders("account.json")))
    region_vars = jsondecode(file(find_in_parent_folders("region.json")))
    environment_vars = jsondecode(file(find_in_parent_folders("environment.json")))
}

# Generate an AWS provider block
generate "provider" {
    path      = "provider.tf"
    if_exists = "overwrite_terragrunt"
    contents  = <<EOF
provider "aws" {
  region = "${local.region_vars.aws_region}"
  # Only these AWS Account IDs may be operated on by this template
  allowed_account_ids = ["${local.account_vars.aws_account_id}"]
}
EOF
}

# Configure Terragrunt to automatically store tfstate files in an S3 bucket
remote_state {
  backend = "s3"
  config = {
    encrypt        = true
    bucket         = "${get_env("TG_BUCKET_PREFIX", "tfstate")}-${local.project_vars.project_name}-${local.account_vars.account_name}-${local.region_vars.aws_region}"
    key            = "${path_relative_to_include()}/terraform.tfstate"
    region         = local.region_vars.aws_region
    dynamodb_table = "terraform-locks"
  }
  generate = {
    path      = "backend.tf"
    if_exists = "overwrite_terragrunt"
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.