简体   繁体   中英

Accessing the module from within for_each(avoiding cycle)

I am creating modules using for_each loop. I want to access a previous module from within the module block to get a variable but it stops me from doing so because of the cycle.

locals{
  deployment_plan = ["a", "b", "c"]
}
module "tier" {
  source = "./modules/deployment"
  for_each = { for tier,data in local.tier_config : tier => data }
  tier_cfg = each.value
  predecessors = [module.tier[local.deployment_plan[index(local.deployment_plan, each.key) - 1]].last_release_phase] : []
}

I see an error when assigning predecessor for the module as I am accessing module in cycle. Although I want to access the previous module.

You can't access module.tier before it is created. Thus you get the error. In your case you have to create 3 modules, for each of your deployment_plan :

locals{
  deployment_plan = ["a", "b", "c"]
}
module "tier_a" {
  source = "./modules/deployment"
  for_each = { for tier,data in local.tier_config : tier => data }
  tier_cfg = each.value
  predecessors = []
}

module "tier_b" {
  source = "./modules/deployment"
  for_each = { for tier,data in local.tier_config : tier => data }
  tier_cfg = each.value
  predecessors = [module.tier_a.last_release_phase]
}

module "tier_c" {
  source = "./modules/deployment"
  for_each = { for tier,data in local.tier_config : tier => data }
  tier_cfg = each.value
  predecessors = [module.tier_b.last_release_phase]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM