What are Terraform Modules and how to use them
Hello. In this tutorial, we will understand Terraform modules.
1. Introduction
Terraform is a tool for building, changing, and versioning the infrastructure safely and efficiently. It is used to manage the infrastructure of the popular cloud service providers and custom in-house solutions. It helps manage both low-level (Compute, Storage, Networking, etc.) and high-level components (such as SaaS, DNS, etc.) Terraform deployment automation is divided into different sections i.e. –
- IaaC – IaaC is popularly known as the Infrastructure as a Code wherein the infrastructure is described using a high-level configuration syntax. This allows a blueprint of the infrastructure which can be deployed, versioned, and shared for re-use
- Execution Plans – Terraform has a planning step where it generates an execution plan. The execution plan tells the administrator what Terraform will do once applied and helps to avoid any surprises when it creates the infrastructure
- Resource Graph – Terraform builds a graph of all the resources and parallelizes the creation and modification of non-dependent resources. This offers insights into learning the dependencies in their infrastructure
- Change Automation – Terraform allows to apply of complex changesets to the infrastructure with minimal human intervention
1.1 Configuration language
Terraform has its configuration language designed to meet the infrastructure automation requirements. The main purpose of this language is to declare resources and a group of resources (gathered into a module) represents a larger unit of configuration. Language syntax consists of a few elements i.e. – Blocks, Arguments, and Expressions.
- Blocks – Containers for other contents and represents the object configuration
- Arguments – Assign a value to the name and appear within the blocks
- Expressions – Represents a single value, referenced value, or combination of other values
1.2 Steps
To create the infrastructure via the Terraform scripts following commands need to be executed.
terraform init
– Initializing the new or existing terraform configurationterraform plan
– Generate the execution plan from the resources specified in the fileterraform apply
– Create the infrastructure from the resources specified in the fileterraform destroy
– Destroy the created infrastructure
1.3 Modules in terraform
A module is a container for multiple resources that are used together. A module can call other modules that allow the developers to include the child module resources into a configuration in an easy way.
2. Practice
Let us dive into some practice stuff from here. You’re free to choose the IDE of your choice. I am using Visual Studio Code as my preferred IDE for the development with the HashiCorp Terraform extension installed. The extension offers syntax highlighting and other editing features for Terraform files using the Terraform language server.
2.1 Pre-requisite
To proceed we will be needing an AWS CLI user having the right set of permissions required for creating the infrastructure. I am using an existing user and attached the EC2 full access policy attached to this user so that the IAM user can successfully create the required infrastructure. The access and secret key generated for the user will be used in the project’s root variables.tf
file.
2.2 Creating EC2 module
Create a module named ec2
and add the files to it required for creating the ec2 via terraform code.
2.2.1 Variables File
The file contains the declarations required to create the EC2 instance. Add the following code to the file containing information related to the machine image id, availability zone id, instance type, etc. You’re free to change the values as per your need.
variables.tf
variable "ami_id" { type = string default = "freetier_linux_ami_id" } variable "az_id" { type = string default = "ap-south-1a" } variable "type" { type = string default = "t2.micro" # creating in the free-tier category } variable "instance_count" { type = number default = 1 } variable "subnet_id" { type = string default = "subnet_id" } variable "key_name" { type = string default = "your_keypair_name" } variable "vpc_id" { type = string default = "virtual_private_cloud_id" } variable "tags" { type = map(string) default = { environment = "development" terraform = "true" } }
2.2.2 EC2 Instance File
The file contains the resources that will be used to create the EC2 instance. The file will get the variable details from the module’s variables.tf
file. Add the following code to it.
ec2.tf
resource "aws_security_group" "ec2-sg" { name = "ec2-sg" description = "security group for ec2" vpc_id = var.vpc_id ingress = [ { # ssh port allowed from any ip description = "ssh" from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = null prefix_list_ids = null security_groups = null self = null } ] egress = [ { description = "all-open" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = null prefix_list_ids = null security_groups = null self = null } ] tags = var.tags } resource "aws_instance" "ec2_instance" { ami = var.ami_id availability_zone = var.az_id instance_type = var.type count = var.instance_count security_groups = ["${aws_security_group.ec2-sg.id}"] subnet_id = var.subnet_id key_name = var.key_name ebs_block_device { device_name = "/dev/xvda" volume_size = 8 volume_type = "gp2" delete_on_termination = true } tags = var.tags }
2.3 Creating the implementation
Add the implementation files in the project root folder so that we can successfully call the EC2 module and create an instance on the AWS EC2 dashboard.
2.3.1 Variables File
The file contains the variables required for the application to connect to the aws environment. Add the following code to the file containing the AWS CLI user-related information.
variables.tf
variable "region" { type = string default = "ap-south-1" }
2.3.2 Implementation File
Add the following code to the file containing the implementation.
main.tf
provider "aws" { access_key = "YOUR_CLI_USER_ACCESS_KEY" secret_key = "YOUR_CLI_USER_SECRET_KEY" region = var.region } module "ec2_module" { source = "./modules/ec2" }
3. Code Run
Navigate to the project directory containing the above scripts and open the terminal. Execute the below commands in the respective order within the directory.
Commands
-- step1: initializing the new or existing terraform configuration -- terraform init -- step2: generating the execution plan -- terraform plan -- step3: building the infrastructure -- -- auto-approve flag skips interactive approval of the plan before applying terraform apply --auto-approve -- step4: destroying the infrastructure -- -- auto-approve flag skips interactive approval of the plan before applying terraform destroy --auto-approve
4. Demo
Once the terraform script is successfully executed head over the AWS console to confirm that the ec2 instance is successfully created on the ec2 dashboard.
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
5. Summary
In this tutorial, we learned an introduction to Terraform and create a simple module to create the ec2 instance in the aws portal. You can download the source code from the Downloads section.
6. Download the Project
This was a tutorial on learning and implementing Terraform module to create the ec2 instance on aws.
You can download the full source code of this example here: What are Terraform Modules and how to use them