Terraform: Reusing code using module

UNDERSTANDING THE REQUIREMENT

Imagine a situation where every new or current writing the same code (let’s for example of creating an EC2). Obviously there will be lot of code repetition and duplication of code files if not managed properly.

Even if one is not from an IT background it will not take a ride to Atlas mountain to understand that for writing anything, not every time you start from scratch and start revising A-Z. Instead you use the knowledge acquired previously and start referencing it for current work.

If the above construct is still hard to relate, understand that every time you do not setup a soft drink plant for having a bottle of your favorite drink 🙂

THE SOLUTION

For having a standard oriented and a cleaner code, terraform provides us with option to either download a module from terraform registry OR create reusable module where we can describe our infrastructure in terms of its architecture, rather than directly in terms of physical objects.

For ease of your testing we put the code which we are going to test at https://github.com/HemantGangwar/terraformModuleTest

CODE IN ACTION

Let’s first create the root/main module source code and test if it is able to deploy a machine.

Note: Your code may fail if your key_name doesn’t match ours so use that wisely.

resource "aws_instance" "myec2" {
        ami             = var.custom_ami_id
        instance_type   = var.instance_hw
        tags = {
                Name    = var.aws_ec2_name
                }
        key_name        = var.aws_key_name
        }


#### DEFINING VARIABLE DECLARATION #######

variable "instance_hw" {
        default = "t2.micro"
        }

variable "aws_ec2_name" {}

variable "custom_ami_id" {
        default = "ami-06a0b4e3b7eb7a300"
        }

variable "aws_key_name" {
        default = "aws-exam-testing"
        }

output "awsip" { value = aws_instance.myec2.public_ip }
#### END - DEFINING VARIABLE DECLARATION ##########

Test the code by issuing “terraform apply”

Now create a basic child module referencing the values you require and test if it is working fine for you. Remember to provide correct source path, else child module will not be able to find the location of parent module.

module "ec2module" {
        source = "../../tmp/puppet/"
        custom_ami_id = "ami-06a0b4e3b7eb7a300"
        aws_ec2_name = var.aws_ec2_name
                }

variable "aws_ec2_name" {}

output "awsip" { value = module.ec2module.awsip }

Well congratulation! If you are able to successfully test and used module. Now for ease of testing we are sharing below video link which you can reference to test things in action. Do practice at your end and share your feedbacks.

Leave a comment