简体   繁体   中英

Accessing siblings during a for_each in Terraform

In terraform, if I'm iterating over a map using for_each , is there any way while within any of the iterations to access values from the resources created during prior iterations?

module "my_module" {

  for_each = var.regions

This obviously means that order matters, but provided I've ensured that my map is defined in such a way that the dependency came before the dependant, can I reference it?

For cases like this, I think it makes sense to use Terraform's count feature:

module "my_module" {
  # assuming var.regions is a list:
  count = len(var.regions)
  # region is var.regions[count.index]
  # previous region is var.regions[count.index - 1]

You'll need to work around what to do with the first item; either you iterate only len(var.regions)-1 times or you do something special for the first item.

The for_each syntax is used to iterate over maps or sets. This implies that order should not matter, as maps and sets are not ordered data structures. This also means that you can't actually "define your map in such a way that dependencies come before dependents". You'll likely want to define a list with keys to your map, with the keys in some acceptable order.

Terraform's repetition constructs are not iteration: the instances conceptually all have their actions applied simultaneously. In practice that isn't always true if you have more instances than the -parallelism option allows, but even in that case the order Terraform will process them is undefined.

Dependencies in Terraform are between blocks, not between multiple instances of the same block, because the handling of the repetition happens as part of processing the block, long after the dependencies were already resolved.

For that reason, if you want to have one module instance that depends on another you must declare them as two separate blocks, one of which refers to the other one. There is no way to create a dependency between multiple instances of the same object.

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