How to Build a Terraform Module Example

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

This blog post will show you how to build a terraform module example using Terraform. How to read modules, the structure of modules, and what is required for implementing them in your own software.

The “terraform local module example” is a simple tutorial on how to build a Terraform Module. The article will cover the basics of what Terraform is, and how to use it.

How to Build a Terraform Module Example

Terraform modules are a terrific method to encapsulate and reuse similar pieces of code across many Terraform projects and settings. How do you create a Terraform module example, though? You’re in for a real treat!

You’ll learn how to design a Terraform module that can be used to generate a simple AWS EC2 instance in this post.

Ready? Continue reading and begin constructing!

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • AWS account — If you don’t already have an AWS account, you may sign up for a free tier account.
  • Terraform installed on an EC2 instance – Terraform v0.14.4 is used in this lesson.
  • AWS CLI that has been installed and setup.

Getting Started with the Terraform AWS Provider is a related article.

Organizing a Directory Structure

Why do you need to create a terraform project directory structure to begin with? To begin, Terraform, like other programming languages, requires a directory structure to organize your scripts and files. Terraform also utilizes a.tf file to explain core Terraform settings and various terraform files (.tf states) to describe Terraform resources.

Terraform begins by reading configurations from the root directory, therefore terraform configurations must be located there.

1. Run the following commands in your terminal to create a new directory called terraform project and switch to it. You may rename the directory to anything you like. This directory will house all of the project’s files and subdirectories.

mkdir terraform project mkdir terraform project mkdir terraform cd terraform project terraform project terraform project terraform project

2. Create two folders using the mkdir command. The first is modules, which is a parent directory, and vpc, which is a subfolder of modules.

3. Finally, use an absolute path to shift your current directory to the vpc directory inside the modules directory by running the following command. Make sure cloud user is replaced with your login.

Because each user on your system has their own home directory, you give the absolute path to the vpc directory.

cd /home/cloud user/terraform project/modules/vpc/ /home/cloud user/terraform project/modules/vpc/

Codes for Terraform VPC Modules

It’s time to develop a Terraform module to establish an AWS Virtual Private Cloud now that your project directory structure is complete (VPC). Prepare your preferred code/text editor since you’ll be creating many Terraform configuration files.

Building an AWS VPC with Terraform: A Step-by-Step Guide

Throughout this part, you’ll generate configuration files in the /terraform project/modules/vpc/ directory.

1. With your text editor, create a new file named main.tf (Terraform VPC module) and fill it with the following code. The code below will set variables, define the AWS provider block, and use the cidr block property to determine the subnet range. The AWS VPC and AWS SUBNET resources will be defined by the resource block relating to this VPC module.

# The provider block is where this module’s parameters are declared. It specifies a single parameter called region, which is the AWS Region where the VPC would be installed in this scenario. region = var.region provider “aws” # This is a resource block where VPC resources are defined. “this” resource “aws vpc” # This cidr block specifies a 10.0.0.0/16 network for the VPC. # It’s a 256-class C (CIDR) IP address range, in other words. cidr block = “10.0.0.0/16” cidr block = “10.0.0.0/16” cidr block = “10.0.0.0 # This is a resource block where VPC resources are defined. “this” resource “aws subnet” # The vpc id will be bound to the vpc declared in the “aws vpc” module with this line. aws vpc.this.id = vpc id cidr block = “10.0.1.0/24” cidr block = “10.0.1.0/24” cidr block = “10.0.1.0 # For this module, this block specifies a single parameter. # named /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86 64-gp2 /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86 64-gp2 name = “/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86 64-gp2” data “aws ssm parameter” “this”

2. After that, create a new file named variables.tf and fill it with the following code. All variables that the configuration file refers to are stored in the variables.tf file.

# A variable block is a container for one or more variables. variable “region” # Defines this variable’s data type as a string. # Sets the region variable’s default value to type = string. “us-east-1” is the default value.

3. Finally, create an outputs.tf file and paste the code below into it.

Exporting values from a module to the calling environment necessitates the use of the code below. Terraform produces a single resource when a module is invoked. That resource contains the module’s name as well as the output type.

The values for this resource are defined by the contents of outputs.tf.

# Returns the id of the subnet you defined in the “subnet id” module output. value = aws subnet.this.id aws subnet.this.id aws subnet.this.id aws_ # Returns the value of the ami-amazon-linux-latest/amzn2-ami-hvm-x86 64-gp2 parameter in /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86 64-gp2 parameter. output “ami id” data.aws ssm parameter.this.value value = data.aws ssm parameter.this.value

Writing Terraform Codes (Main Terraform Codes)

You’ve finished configuring your modules and auxiliary files, so you can go on to the main code.

1. Navigate to your main project directory (/terraform project) using the command below.

2. Create a main.tf file with the contents shown below.

The code below will construct a VPC with the ID vpc-xxxxxxx in the AWS region supplied by var.main region and a single subnet with the ID subnet-yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

# Sets the value of var.main region to the variable. variable “main region” type = string default = “us-east-1” # Assigns the variable’s value to the AWS region. region = var.main region provider “aws” # Executes the code in the vpc module you just constructed. source = “./modules/vpc” region = var.main region module “vpc” “aws instance” “my-instance” resource { # This module’s AMI id is bound to the value of the ami variable. module.vpc.ami id = ami # Assigns the value of the subnet id to the module’s subnet id. instance type = “t2.micro” instance id = module.vpc.subnet id # Binds the value of instance type to t2.micro.

3. Finally, create a new file named outputs.tf and fill it with the code below.

When this module is invoked, the values of the outputs are defined by the code below.

aws instance.my-instance.private ip value = aws instance.my-instance.private ip description = “Private IP of EC2 instance” value = aws instance.my-instance.private ip aws instance.my-instance.private ip value = aws instance.my-instance.private ip value = aws instance

Terraform Code Deployment

Your module and configuration files are now ready. However, until you deploy your code, they aren’t doing anything at the moment.

1. Use the terraform fmt command to confirm that your code is properly formatted. Terraform will run through all of the files in your directory if you use the -recursive option.

Terraform employs a set of guidelines called Terraform Style Conventions to decide how it should style your code. If you have any files that don’t follow these guidelines, this command will fix them for you.

Checking the format of the code Checking the format of the code

2. Next, execute the terraform init command to get your Terraform project up and running.

This is a helper command that creates a new Terraform project. This program looks through all of the files in your project and discovers modules automatically, as well as downloading any module dependencies.

Make sure to execute the terraform init command from the root of your project. You should also only start a Terraform project once, else you’ll wind up with a lot of unnecessary files.

Getting your Terraform project started.

Getting your Terraform project started.

To check for flaws in your code, use the terraform validate command.

This command verifies that the code you’ve written is syntactically accurate and won’t cause any problems. This command will inform you which files have problems and how to correct them.

If you continue without checking for issues, Terraform will not be able to deploy your code when the time comes.

Checking your code for errors Checking your code for errors

4. To establish an execution plan, use the terraform plan command.

This tool examines all of the files in your project and then shows you what steps to take without making any changes. strategy for terraforming

The output below displays three resources set in this module, with no resources being updated or removed in this sample.

Creating a strategy for execution Creating a strategy for execution

5. Run terraform apply to apply your execution plan (from step four) while automatically accepting prompts (—auto-approve). Terraform will now begin building the resources specified in the execution plan.

It may take some time for your resources to be deployed, so be patient and wait.

—auto-approve terraform apply

Terraform will offer you with a summary of what happened when the creation step is completed, as seen below.

Terraform built the EC2 instance and outputted the private IP address as specified in the outputs.tf file in your main project directory, as you can see.

Getting a sneak peek at the execution plan's deployment progress Getting a sneak peek at the execution plan’s deployment progress

6. Finally, execute the terraform state command from the command prompt. This command displays a list of resources that have been added to the state file and are currently being tracked.

The state file is a tiny file that keeps track of your resources’ current condition. You may also use the state file to perform commands without stating whether they have been created or removed. As a consequence, this file helps Terraform operate quicker and saves you time.

As seen below, you’ll obtain a resources list that contains your EC2 instance, which was setup and generated by the main code.

Three resources (with module.vpc as their prefix) have also been setup and generated using the VPC module code.

This result verifies that all of your modules are operational.

Verifying that the modules are in good functioning order Verifying that the modules are in good functioning order

Conclusion

You’ve gone through a Terraform module example and learnt how to make your own by writing your own code in this lesson. You’ve also discussed passing variables across modules, verifying code functionality before deployment, and deploying code using the module.

You should now understand the fundamental structure of a Terraform module and how to develop your own. Now is a good time to become more involved with Terraform. Maybe learn how to use Terraform to deploy an EC2 instance to run Docker?

Terraform is a tool that allows you to create, change, and destroy virtual servers. Terraform modules are files that contain the configuration for the server, which can be shared with other people. This article will go over some best practices for building terraform modules. Reference: terraform modules best practices.

Related Tags

  • terraform module example github
  • terraform module tutorial
  • create terraform module
  • terraform module structure best practices
  • terraform-aws-modules