Define multiple Terragrunt dependencies in an array

Viewed 25

I have the following setup

terraform {
  source = "${get_path_to_repo_root()}//modules/shared-infra"
}

dependency "project_1" {
  config_path = "../../../project_1"
}

dependency "project_2" {
  config_path = "../../../project_2"
}


inputs {
   shared_vpc_service_project_ids = [
      dependency.project_1.outputs.project_id,
      dependency.project_2.outputs.project_id
   ]

   shared_vpc_host_subnet_users = [
      "serviceAccount:${dependency.project_1.outputs.sa_email}",
      "serviceAccount:${dependency.project_2.outputs.sa_email}",
   ]
   
   < ... more variables ... >
}

is there a way to define those dependencies in some array and define inputs using list comprehension?

something similar to:

locals {
   projects = [dependency.project_1, dependency.project_2]
}

inputs {
   shared_vpc_service_project_ids = [ for p in projects : p.outputs.project_id ]

   shared_vpc_host_subnet_users = [ for p in projects : "serviceAccount:${p.outputs.sa_email}" ]
   
   < ... more variables ... >
}

Basically, I don't want to go through and update each and every input when a new project is created.

1 Answers

It is not possible to include dependency directly into the locals as in the initial example described in the question.
After some investigation, I arrived at the following solution:

Create separate config file projects.hcl and add project dependencies there

project.hcl

dependency "project_1" {
  config_path = "../../../project_1"
}

dependency "project_2" {
  config_path = "../../../project_2"
}

update terragrunt.hcl to read the config and include that config as a local variable

locals {
  project_deps  = read_terragrunt_config("projects.hcl")
  projects = [
    local.project_deps.dependency.project_1,
    local.project_deps.dependency.project_2,
  ]
}

inputs {
   shared_vpc_service_project_ids = [ for p in local.projects : p.outputs.project_id ]

   shared_vpc_host_subnet_users = [ for p in local.projects : "serviceAccount:${p.outputs.sa_email}" ]
   
   < ... more variables ... >
}

So only two changes are needed once a new project is created - add a new dependency in projects.hcl and update the local variable with a new dependency name.

Related