Creating lots of instances in any cloud provider is always required for any organization or is a project need. If you are asked to create 10 EC2 machines in a particular AWS account using console UI , I am sure it will take tons of hours to create it and lots of efforts. There are lots of automated ways which can create multiple instance in quick time , Yes that's quite possible and with terraform its very simple and easy.

In this tutorial, we will learn to create multiple ec2 instance in AWS account using terraform code.

Table of content

  1. What is terraform?
  2. Prerequisites
  3. How to Install Terraform on Ubuntu 18.04 LTS
  4. Launch multiple EC2 instances of same type using count on AWS using Terraform
  5. Launch multiple EC2 instances of different type using for_each on AWS using Terraform
  6. Conclusion

What is Terraform?

Terraform is a tool for building , versioning and changing the infrastructure. Terraform is Written in GO Language and the syntax language of configuration files is hcl which stands for HashiCorp configuration language which is much easier than yaml or json.

Terraform has been in use for quite a while now . I would say its an amazing tool to build , change the infrastructure in very effective and simpler way. It's used with variety of cloud provider such as Amazon AWS, Oracle, Microsoft Azure , Google cloud and many more. I hope you would love to learn it and utilize it.

Prerequisites

  • Ubuntu machine preferably 18.04 version + , if you don't have any machine you can create a ec2 instance on AWS account
  • Recommended to have 4GB RAM
  • At least 5GB of drive space
  • Ubuntu machine should have IAM role attached with AWS EC2 instance creation which we will use later in tutorial using terraform

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

How to Install Terraform on Ubuntu 18.04 LTS

  • Update your already existing system packages.
                sudo apt update              
  • Download the latest version of terraform in opt directory
                wget https://releases.hashicorp.com/terraform/0.14.8/terraform_0.14.8_linux_amd64.zip              
  • Install zip package which will be required to unzip
                sudo apt-get install zip -y              
  • unzip the Terraform download zip file
                unzip terraform*.zip              
  • Move the executable to executable directory
                sudo mv terraform /usr/local/bin              
  • Verify the terraform by checking terraform command and version of terraform
                terraform               # To check if terraform is installed   terraform -version      # To check the terraform version                              
  • This confirms that terraform has been successfully installed on ubuntu 18.04 machine.

Terraform Configuration Files and Structure

Let us first understand terraform configuration files before running Terraform commands.

  • main.tf: This file contains code that create or import other AWS resources.
  • vars.tf: This file defines variable types and optionally set the values.
  • output.tf: This file helps in generating of the output of AWS resources .The output is generated after the terraform apply command is executed.
  • terraform.tfvars: This file contains the actual values of variables which we created in vars.tf
  • provider.tf: This file is very important . You need to provide the details of providers such as AWS , Oracle or Google etc. so that terraform can make the communication with the same provider and then work with resources.

Launch multiple EC2 instances of same type using count on AWS using Terraform

Now, In this demonstration we will create multiple ec2 instance using count and for_each parameters in terraform. So Lets create all the configuration files which are required for creation of EC2 instance on AWS account using terraform.

  • Create a folder in opt directory and name it asterraform-demo
                mkdir /opt/terraform-demo cd /opt/terraform-demo              
  • Create main.tf file under terraform-demo folder and paste the content below.
                resource "aws_instance" "my-machine" {   count = 4                                      # Here we are creating identical 4 machines.                                    ami = var.ami   instance_type = var.instance_type   tags = {     Name = "my-machine-${count.index}"          } }              
  • Create vars.tf file under terraform-demo folder and paste the content below
                                                      # Creating a Variable for ami                                    variable "ami" {          type = string }                                      # Creating a Variable for instance_type                                    variable "instance_type" {       type = string }              
  • Create terraform.tfvars file under terraform-demo folder and paste the content below.
                                  ami = "ami-0742a572c2ce45ebf"  instance_type = "t2.micro"                              
  • Create output.tf file under terraform-demo folder and paste the content below.

Note: value depends on resource name and type ( same as that of main.tf)

                output "ec2_machines" {   value = aws_instance.my-machine.*.arn                                      # Here * indicates that there are more than one arn as we used count as 4                                                        }                              

provider.tf:

                provider "aws" {                                      # Defining the Provider Amazon  as we need to run this on AWS                                                        region = "us-east-1" }              
  • Now your files and code are ready for execution . Initialize the terraform
                terraform init              
  • Terraform initialized successfully ,now its time to run the terraform plan command.
  • Terraform plan is a sort of a blueprint before deployment to confirm if correct resources are being provisioned or deleted.
                terraform plan              
  • After verification , now its time to actually deploy the code using apply.
                terraform apply              

Great Job, terraform commands execution was done successfully. Now we should have four EC2 instance launched in AWS.

Launch multiple EC2 instances of different type using for_each on AWS using Terraform

  • In previous example we created more than one resource but all with same attributes such as instance_type
  • Note: We use for_each in the terraform when we need to create more than one resources but with different attributes such as instance_type for keys etc.

main.tf

                resource "aws_instance" "my-machine" {   ami = var.ami   for_each  = {                                                            #                                                                            for_each iterates over each key and values                                    key1 = "t2.micro"                                      # Instance 1 will have key1 with t2.micro instance type                                    key2 = "t2.medium"                                      # Instance 2 will have key2 with t2.medium instance type                                    }         instance_type  = each.value 	key_name       = each.key     tags =  { 	   Name  = each.value 	} }              

vars.tf

                variable "tag_ec2" {   type = list(string)   default = ["ec21a","ec21b"] }                                                      variable "ami" {                                      # Creating a Variable for ami                                    type = string }              

terraform.tfvars

                ami = "ami-0742a572c2ce45ebf" instance_type = "t2.micro"              
  • Now code is ready for execution , initialize the terraform , run the plan and then use apply to deploy the code as described above.
                terraform init  terraform plan terraform apply              

Conclusion

Terraform is a great open source tool which provides easiest code and configuration files to work with. Its a best Infra as a code tool to start with. You should now have an idea to Launch multiple EC2 instances on AWS using Terraform count and for_each on Amazon web service.

Hope this tutorial will help you in understanding the terraform and running multiple instances on cloud. Please share with your friends.