Terraform Basics 101: Part 5

Terraform Module

By now , we have seen so many tf files

Managing so many tf files make it difficult for us to manage. Rather than this, we can create directory where we can create some configuration files (tf files). This directory is then called a module.

Here, you can see that aws-instance directory has 2 configuration file (main.tf and variables.tf)

Now, this aws-instance is called the root module

Now, assume that we have created another folder called development under terraform-projects.

Here we have created main.tf file.

But we have nothing on this main.tf (configuration file) right now. Rather than writing from scratch , we can import content from aws-instance on this maint.tf file like this

Now, development folder become the root module and aws-instance becomes child module

Let’s create and use a module. Assume this is our aws architecture for an example

Now, in our local file within the folder payroll-app we have kept some tf files (configuration files). So, this payroll-app is a module now

Here, we can see that we used var.ami, var.app_region etc meaning we have kept a variable.tf file to store the value

Now, let’s create another folder under terraform-projects called us-payroll-app. Then we have kept main.tf and provider.tf file here

But these are empty and we want to use the payroll-ap to use the default architecture.

You can notice that the region and ami was not set there. we specified those using variable (var.ami, var.app_region)

So, we need to specify those once we import the module. Then we initialize, plan and apply changes for the main.tf file

Let’s create another folder within the terraform-projects called uk-payroll-app

which has main.tf file and provider.tf file. Then we set the main.tf file and provider.tf file

In this way, we have set an ami instance to be launched on us-west-2

Once we intialize, plan and apply changes, we can see this

Great! So, this is how we can use the module feature.

But by now, we used local modules. What about modules kept in registry?

Modules are based on verified one and community one.

Here in the verified one, we can also see the provision instructions

To make use of this on our local one, we need to specify like this. Then use terraform init or use terraform get (if the provider was downloaded earlier)