Terraform Module

Table of contents
  1. What is a Terraform module
  2. Typical file structure
  3. Module structure
  4. Module input variables
  5. How to call a module
  6. Itty Bitties

What is a Terraform module

It is sort of like a class in programming. Given input variables, it can be reused to create multiple instances of the infra described in the module.

For example, when you’re creating an AWS lambda resource, there are typically some other resources associated with it, such as the REST API, IAM role, etc.

If you think you’re going to be using this pattern often, you can create a module containing all the common resources and only expose some input variables that need to be configured at the top level.


Typical file structure

The main Terraform execution point is called the root module. This is often the main.tf file in the top level driectory.

Modules are often placed in a folder called modules.

.
├── README.md
├── main.tf
├── modules
├── outputs.tf
└── variables.tf

Module structure

Inside modules directory, create a child directory with a name of your module: e.g. mymodule.

.
├── main.tf
├── modules
│   └── mymodule
│       ├── main.tf
│       ├── outputs.tf
│       └── variables.tf
├── outputs.tf
└── variables.tf

The structure inside mymodule is optional. They can be separated as above or smashed into a single file.


Module input variables

Unless you plan to reuse your module as-is every single time, you typically provide input variables to modules.

Any variables defined with variable must be provided by the calling module or an error will be raised.


How to call a module

All you need to do is feed the necessary input variables.

In main.tf,

# main.tf

module "module_a" {
  source = "./modules/mymodule"

  my_input_var = "Here you go"
}

Notice that the source attribute points the the directory of the module, not any specific files

If you defined any output variables in the module with output, you can access them by:

module.module_a.my_output_var

Itty Bitties

  • Although you can nest your modules in multiple levels, it is recommended to keep the entire Terraform module as flat as possible.
  • Even if you don’t access them, module output variables is always output after terraform apply.
  • Think about whether a module is absolutely necessary. Sometimes you may end up feeding in as many input variablesas the original resource.