Module 5: Terraform Modules

Lesson 5.2: Variable Scope Within Modules

Plain language

Each module has its own namespace. A module behaves like a function:

  • Input variables are its parameters.
  • Outputs are its return values.
  • Resources are internal, private to the module.
Direction Mechanism Example
Parent → child Set the child's input variables as arguments in the module block environment = var.environment
Child → parent Child declares output blocks. The parent reads module.<name>.<output>. module.site.site_id
Child → child Pass one module's output into another module's input, in the parent vpc_id = module.network.vpc_id

Under the hood

  • A child module can't see the parent's var.*, local.*, or resources. It sees only its own declarations.
  • A parent can't reference a child's resources in expressions, as in module.site.local_file.page. Only outputs cross the boundary.
  • State addresses do include the module path, for example module.site.random_pet.suffix. You use these in CLI commands and moved blocks, but not in expressions.
  • A required child variable (no default) must be set in the module block, or plan errors.
  • Root module variables come from the CLI, tfvars, and the environment. Child module variables come only from the calling module block. TF_VAR_ and .tfvars don't reach child modules directly.