How to create EC2 instance using Terraform

EC2 instance Creation using Terraform on AWS using IAM Role | Terraform With AWS Cloud

How to create EC2 instance using Terraform

What is Terraform?

Terraform is an open-source tool for provisioning and managing cloud infrastructure. Terraform can provision resources on any cloud platform. 

Terraform allows you to create infrastructure in configuration files(tf files) that describe the topology of cloud resources. These resources include virtual machines, storage accounts, networking interfaces, etc.

Pre-requisites:

  • Create an EC2 instance Manually for provisioning the infrastructure using terraform.

  • Install Terraform on your EC2 instance

  • You can provision resources in the AWS cloud using Terraform in two ways as mentioned below:

    1. AWS Access keys + secret keys (un-secure way)

    2. IAM Role with AmazonEC2FullAccess Policy. (more secure way)

  • Option 2 is recommended approach as we already installed Terraform on the EC2 instance that is inside the AWS cloud. So we do not need Access Keys + secret keys. But if you have installed Terraform on your local machine you would need to go with Option 1.


Let's create AWS EC2 using Terraform

We will see how you can use Terraform to provision an EC2 instance. Please do the below steps for provisioning EC2 instances on AWS:-

Step - 1: Create an IAM role to provision EC2 instance in AWS

Go to the AWS console, click on IAM

Select AWS service, EC2, and Click on Next Permissions

Type EC2 and choose AmazonEC2FullAccess as policy

Click on Next tags, Next Review give some role name and click on Create role

Step - 2: Assign the IAM role to an EC2 instance

Go back to the EC2 instance, click on the EC2 instance, Security, Modify IAM role

Type your IAM role name  my-ec2-terraform-role  and Save it to attach that role to the EC2 instance.

Login to the EC2 instance where you have installed Terraform.

Step - 3: Create Terraform files

Creating separate directory for terraform files.

cd ~

mkdir project-terraform

cd project-terraform

Create Terraform Files:

make sure you change whatever is covering Square Bracket below per your settings.

sudo vi variables. tf

variable "aws_region" {
       description = "The AWS region to create things in." 
       default     = ["us-east-2"]  #You Can Change Whatever region you want
}

variable "key_name" { 
    description = " SSH keys to connect to ec2 instance" 
    default     =  ["myJan26Key"] #You Can Change Whatever key name U want
}

variable "instance_type" { 
    description = "instance type for ec2" 
    default     =  "t2.micro" 
}

variable "security_group" { 
    description = "Name of security group" 
    default     = "my-jenkins-security-group-2022" 
}

variable "tag_name" { 
    description = "Tag Name of for Ec2 instance" 
    default     = "my-ec2-instance" 
} 
variable "ami_id" { 
    description = "AMI for Ubuntu Ec2 instance" 
    default     = ["ami-0b9064170e32bde34"] #Write Your own AMI-ID
}

#Make sure after your custom changes there is no need for square bracket, i only give it for understanding the concept..

Save the file with ESC then :wq! Command.

Now create main.tf file

sudo vi main.tf

provider "aws" {
  region = var.aws_region
}

resource "aws_vpc" "main" {
  cidr_block = "172.16.0.0/16"
  instance_tenancy = "default"
  tags = {
    Name = "main"
  }
}


#Create security group with firewall rules
resource "aws_security_group" "jenkins-sg-2022" {
  name        = var.security_group
  description = "security group for jenkins"

  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

 ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

 # outbound rule
  egress {
    from_port   = 0
    to_port     = 65535
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags= {
    Name = var.security_group
  }
}

resource "aws_instance" "myFirstInstance" {
  ami           = var.ami_id
  key_name = var.key_name
  instance_type = var.instance_type
  vpc_security_group_ids = [aws_security_group.jenkins-sg-2022.id]
  tags= {
    Name = var.tag_name
  }
}

# Create Elastic IP address
resource "aws_eip" "myElasticIP" {
  vpc      = true
  instance = aws_instance.myFirstInstance.id
tags= {
    Name = "jenkins_elastic_ip"
  }
}

Save the file with ESC then :wq! Command.

Step - 4: Execute Terraform Commands

Now execute the below command:

terraform init

Execute the below command:

terraform plan

the above command will show how many resources will be added.

Plan: 4 to add, 0 to change, 0 to destroy

Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.

Enter a value: yes
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

Next, apply the changes to your AWS environment:

terraform apply --auto-approve

Now login to the EC2 console, to see the new instances up and running.

List Resources created by Terraform:-

Execute the below command to view a list of the resources created by Terraform.

terraform state list

You should be able to see the EC2 instance up and running in AWS console.


How to push Terraform files into GitHub?

All Terraform files should be checked into version control systems such as GitHub, BitBucket or GitLab. Let us see how to push code changes into GitHub. Make sure you are in the directory where Terraform files are created.

Create Remote repo on GitHub

Create a new repo with the below name, make sure it is a private repo. Also do not click on initialize this repository with a README option.

Note down the remote URL as highlighted below:

Note:
If you have any issues in uploading .tf files, you may not have created ssh-keys and uploaded them into GitHub. Create ssh keys using the ssh-keygen command:

ssh-keygen

This should generate both public and private keys.

Copy the public keys by executing the below command:

sudo cat ~/.ssh/id_rsa.pub

Initialize the directory first

git init .

The above command will create a local git repository.
Now add terraform files.

git add *.tf

Then commit it with the below command:

git commit -m "Added terraform files"

Add Your remote repository URL with the local repo and execute the below command:

git remote add origin <your remote repo URL>

Now push the code into GitHub

git push -u origin master

Now Login to GitHub to view the Terraform files

You may get this error if you have not uploaded ssh keys into GitHub/BitBucket.

So make sure you upload SSH keys into your SCM.


Conclusion

Terraform makes it easy for administrators to provision cloud resources in AWS. Using Terraform’s command files, you can automate provisioning to reduce the overhead of manually creating instances in the AWS dashboard.


Did you find this article valuable?

Support Biswajit Mohapatra by becoming a sponsor. Any amount is appreciated!