John
John

Reputation: 11921

Terraform: can module's name be resolved dynmically?

Given a series of modules whose names follow a pattern:

module "mod-a" {
  // ...
}

module "mod-b" {
  // ...
}

module "mod-b" {
  // ...
}

and assuming each module defines an output called my_output, can I refer to a particular module on the basis of a dynamically resolved name?

e.g.

...
// some_module = "mod-a"
some_value = module[some_module].my_output
...

The syntax above gives the error:

The "module" object cannot be accessed directly. Instead, access one of its
attributes.

Is there another way to access a module whose name is only known at runtime?

Upvotes: 2

Views: 3113

Answers (1)

Martin Atkins
Martin Atkins

Reputation: 74694

To achieve this in Terraform today (Terraform 0.12.13), you'll need to construct a suitable map explicitly as a local value, and then index that map:

locals {
  modules = {
    mod_a = module.mod_a
    mod_b = module.mod_b
    mod_c = module.mod_c
  }
}

Elsewhere in the configuration you can then use an expression like local.modules[local.dynamic_module_key], selecting the desired object from the map.

Terraform requires static references to objects like this so that it can properly construct a dependency graph. In this case, Terraform infers that local.modules depends on all of the outputs from all three of these modules, and thus anything that refers to local.modules must wait until all of the outputs from all of these modules are ready to ensure that the final index operation has a complete value to work with.

Upvotes: 7

Related Questions