Variable Scope within Modules and Child Modules

Learn the scope of local values, variables, and outputs within modules and child modules.

Configuring inputs and outputs for modules

We can configure inputs and outputs for modules with an API interface. This allows us to customize them for specific requirements while our code remains as DRY and reusable as possible.

Every directory containing configuration is automatically a module in Terraform. Using modules just means explicitly referencing that configuration. References to modules are created with the module block, and resources created by the child module are exposed through outputs defined in the child module.

Scope of a local value

A local value defined in a module is only available in the context of that module. The calling module and any other child modules invoked by that calling module don’t have access to those local values unless they’re exposed as output values. For instance, let’s say we have a root module that invokes two child modules, A and B. Any local values created in module A won’t be available to the root module or module B.

Scope of variables within a module

Variables are contained within a module. If we’re calling a module, however, we also need to pass values for any variables that don’t have a default value as part of that module call. Those are the inputs for the module.

Scope of variables within a child module

The child module doesn’t have access to variables defined in the calling module unless they’re explicitly passed as inputs. For instance, let’s say we have a root module with a variable callednaming_prefix.

Get hands-on with 1200+ tech skills courses.