Terraform Custom Module for EC2

Christopher Miles
3 min readOct 24, 2022

--

What are Terraform modules?

Modules are containers for multiple resources that are used together. A module consists of a collection of .tf and/or .tf.json files kept together in a directory. Modules are the main way to package and reuse resource configurations with Terraform.

Every Terraform configuration has at least one module, known as its root module, which consists of the resources defined in the .tf files in the main working directory.

A Terraform module (usually the root module of a configuration) can call other modules to include their resources into the configuration. A module that has been called by another module is often referred to as a child module.

Child modules can be called multiple times within the same configuration, and multiple configurations can use the same child module.

OVERVIEW: Your team needs you to create a custom module for ec2 instance with a amazon linux 2 ami ID

  1. Fork and clone this repo locally with the ec2.tf template as a starting point to create the ec2 : https://github.com/LevelUpInTech/terraformec2.git
  2. Create a custom module for ec2 out of the resource block that you can use as repeatable infrastructure
  3. Push the new created module and the ec2.tf file to your repo!

Prerequisites: AWS Cloud9, Terraform CLI

Step 1. Fork the repo and git clone it in Cloud9 which will provide the template to get started.

Step 2. Switch into the directory cd terraformec2 (root module). Make a new directory for your (child) module and change into it.

mkdir <new_directory>
cd <new_directory>
In this directory, make the files: main.tf, providers.tf, variables.tf.

Step 3. Using the ec2.tf template, customize your code and input into the appropriate files.

main.tf
variables.tf
providers.tf

Step 4. Now the Terraform commands can be run.

terraform init
terraform validate
terraform plan
terraform apply

Navigate to AWS management console to see that the instance has been created.

Now push the new module and ec2 file to your repo and destroy the resources...

THANKS FOR READING!

--

--