DevOps | Scripts | Automation

Terraform

How to use terraform modules?

Why terraform module is required?

If you are new to terraform, I will advise you to first check the terraform basics.

Alright, you might have worked with multiple programming languages where you want to reuse your code and you write functions.

Similarly in Terraform, we create modules so that the same resource block can be called and used multiple times by just passing values.

For example, consider this scenario where you have to create a storage account for two environments (QA and Prod). In a typical environment what you have done without a module is create two resources and pass variables separately.

For example, Prod Storage Account main.tf file. (To reduce the article length, variable values are directly passed to the main.tf file).

QA main.tf file

From the above example, instead of creating a resource block 2 times for a storage account, we can create a reusable block using the terraform module and call it as many times for the different environments.

The diagram for the Module is shown below.

The syntax for the Module:

  • You need to specify the module keyword with the module name.
  • Source – Path (local, relative, or remote) where the module is defined.
  • param – Values to be passed to variables.

Let’s create a storage account module as per the above diagram and call them in both environments main.tf file.

Storage Account module main.tf.

Module: variables.tf

Once the base resource block is ready, we are ready to call it in the module as shown below.

Prod Environment: main.tf

QA Environment: main.tf

If you want to spin up any new environment, you just have to call the module and provide the source path of the module and parameters.

This is how the module hierarchy will look like,

If you want to create a new module for another resource then create a resource folder name the same as the storage account. For example,

The below example shows, how you can accommodate multiple modules in the main.tf file.

Prod: main.tf

QA: main.tf

Once you run the terraform init command, terraform will initialize the specified module.

You can get the above example code from the GitHub repo.

https://github.com/chiragce17/MyPublicRepo/tree/main/Terraform/Module-Intro

Loading