How to use modules in Terraform?

person writing on the notebook
Reading Time: 3 minutes

In this blog, we will learn about terraform modules with the help of an example.

What are modules?

Modules in terraform, allow using various resources together as a group. Also, these resources are reusable. They are available to use for other configurations as well. A module can be any configuration file with a (.tf) extension in the directory. Every module usually contains 3 files-


For example, we want to set up a network, create an ec2 instance, and connect it with S3 using modules. By doing the following steps we can create this.

Steps for creating this complete setup

Step 1: Create a directory named terraform. Now create a directory in it called the vpc, which is our first module. Create a, that will have the following code. In this code, we are creating a vpc, then a subnet. The subnet is made public by attaching an internet gateway.

In the same directory, vpc, create another file In this file, the two outputs are declared as their values are required in the instance module also.

Step 2: Now create another directory named bucket, which is another module. Create a and file. In, we are creating an S3 bucket and a role for the same and attaching it to an instance profile, so it can further be assigned to the EC2.

Step 3: Now, create the third module named instance. Further, create a file. In this file, we are creating an EC2 in that vpc and attaching it to the instance profile. In order to have the ssh connection to the instance, a security group is created to allow port 22.

Step 4: In terraform directory, create a file named In this file, details of the provider are mentioned. The 3 modules that we created are called. The outputs of vpc and bucket modules are declared as variables in the instance module so that they can be used in it.

Step 5: The setup created above, can be implemented using the following three commands of terraform.

  • terraform init
  • terraform plan
  • terraform apply


So this is an example of how modules are used in terraform. For more detail on modules, refer to this.