We are at part 4 and I would expect that we know well about all tf scripts in the folder will be executed as we can't include nor exclude any files. But when it comes to tens or twenties or more resources to handle, it could be many tf scripts to manage. How should we partition them not to confuse ourselves?

Modular scheme is one of all answers. In Terraform, we can partition resources in to separated folders and include any or all of them into our main script.


Benefits of modules

We can imagine of external libraries we could import in Python. Modules can be included anytime in Terraform in the same way. This comfort us to manage to partition sets of resources into each as we desire.

When we split the resource files into modules. Those module files can be outside the main tf scripts folders. After that, we need to include each module into the main script, however updating modules inclusion always requires init every time.


Syntax

Writing a module is so easy. We just write a keyword, a source file and variables that the module needs.

module "<module_name>" {
  source     = "<module_script_path>"
  attribute1 = value1
  attribute2 = value2 
}

The path of the module can be relative path e.g. "../module/folder1/folder2". This is so useful to maintain the file structures at ease.


Sample structure

I put the main script in a neighbor folder ( src ) to the module folder ( modules ) and execute the main script in the main folder ( src ). So the module folder won't be included when run.

in the module folder

There are 2 files as follows.

First is a script for GCS buckets.

Another is its variables.

in the main folder

There are backend and main script here.

and variable declaration file.

and variable assignment file.

relationship diagram

So, we can see the relationship of those variables like this.

The value assignments are cascading from right to left in the diagram.


Let's run

Once we included the module into the main script, we should find the module is imported when init.

And, of course, we can validate and plan before apply like this.


References