Terraform is a powerful tool for creating and managing infrastructure as code. One of the key features of Terraform is the ability to use modules to encapsulate and reuse infrastructure configuration. In this blog post, we'll explore how to work with Terraform modules, including how to create and publish your own modules.
First, let's define what a Terraform module is. A module is a collection of Terraform files that define a set of resources. A module can be thought of as a reusable piece of infrastructure configuration that can be easily shared and reused across different projects.
Creating a Terraform module is relatively straightforward. You'll need to create a directory that contains all of the Terraform files that make up the module and then use the module
block in your Terraform configuration to reference that directory. For example, let's say you have a module that creates an S3 bucket. Your directory structure might look something like this:
modules/
├─ s3/
│ ├─ s3.tf
│ ├─ vars.tf
│ ├─ output.tf
In your Terraform configuration, you would then reference the modules/s3-bucket
directory to use the module:
Table of Contents
Let's create a Terraform Module for a sample demo app in which we will deploy the same applications in different environments.
Our terraform module will be related to Three tier Application which consists of a React js Frontend, a Nodejs backend and a database where the database will be in a private subnet and React and Nodejs app in a public subnet
Here in the above diagram, we are using S3, VPC, EC2 and RDS.
And now we will start creating terraform modules for the above infra.
Assuming you have already gone through the earlier blog i.e Getting started with terraform
Let us start with S3 terraform module.
- Create S3 bucket to host a static website
- Set index.html as the entry point whenever the website is loaded and 404.html page if something goes wrong
- Create variables for terraform stack, here
name
andenvironment
is used to identify the stack bucket_name
is used to create bucket names in the s3
- Terraform outputs are a means of exporting resource information in a structured format. This data can then be utilized to automate the configuration of other components within your infrastructure or as a source of information.
As shown earlier how to import a module created, let's use the same code and create a dev environment.
Let's plan and apply terraform s3 module for the DEV environment. once everything runs successfully. you will able to see the output.