Skip to main content

Command Palette

Search for a command to run...

Deploying a basic AWS EC2 Instance -Terraform

Updated
5 min read
Deploying a basic AWS EC2 Instance -Terraform

Note : Here we are using - Amazon Linux 2 AMI of Kernel -5.10

  1. Install the terraform tools locally in your machine or use an existing EC2 instance for downloading the terraform. Here I’m using an existing EC2 instance

  2. Perform the below commands one-by-one for Terraform installation

    Install yum-config-manager to manage your repositories.

     $ sudo yum install -y yum-utils
    

    Use yum-config-manager to add the official HashiCorp Linux repository.

     $ sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo
    

    Install Terraform from the new repository.

     $ sudo yum -y install terraform
    
    1. Once the installation is done, create .tf file with any name. Here I’ll use main.tf, which is standard one.

    2. open the created file → vim main.tf and give the following HCL code and save it

       provider "aws" {
         region = "us-east-1"
       }
      
       resource "aws_instance" "abcd" {
         tags = {
           Name        = "Terraform-ec2"
           Environment = "Dev"
           Project     = "Zomato"
         }
         ami                         = "ami-0166fe664262f664c"
         instance_type               = "t2.micro"
         key_name                    = "NEW_KEY_PAIR"
         availability_zone           = "us-east-1e"
         root_block_device {
           volume_size = 10
         }
         count = 2
       }
      

      Here's a breakdown of the provided Terraform code:

      1. Provider Configuration

       provider "aws" {
          region = "us-east-1"
       }
      
      • Purpose: Configures Terraform to interact with AWS.

      • region: Specifies the AWS region where resources will be deployed (in this case, us-east-1, which is the North Virginia region).


2. AWS EC2 Instance Resource

        resource "aws_instance" "abcd" {
  • Purpose: Defines an EC2 instance resource named abcd.

  • Resource Type: aws_instance represents an Amazon EC2 instance.

  • Resource Name: abcd is the logical name for this resource in Terraform.


3. Tags Block

        tags = {
           Name = "Terraform-ec2"
           Environment = "Dev"
           Project = "Zomato"
        }
  • Purpose: Adds metadata (tags) to the EC2 instance.

  • Tags:

    • Name: A human-readable identifier (Terraform-ec2) for the instance.

    • Environment: Categorizes the instance for the Dev (development) environment.

    • Project: Associates the instance with the Zomato project.


4. AMI (Amazon Machine Image)

        ami = "ami-0166fe664262f664c"
  • Purpose: Specifies the AMI used to launch the instance.

  • ami-0166fe664262f664c: Represents a specific image ID available in the us-east-1 region. This image determines the operating system and configuration of the instance.


5. Instance Type

        instance_type = "t2.micro"
  • Purpose: Defines the size of the instance.

  • t2.micro: A small instance type suitable for low-traffic workloads. It’s often free-tier eligible.


6. Key Pair

        key_name = "NEW_KEY_PAIR"
  • Purpose: Specifies the key pair used to SSH into the instance.

  • NEW_KEY_PAIR: The name of the key pair that must exist in the AWS account and us-east-1 region.

7. Availability Zone

        availability_zone = "us-east-1e"
  • Purpose: Specifies the availability zone where the instance will be deployed.

  • us-east-1e: One of the availability zones in the us-east-1 region.


8. Root Block Device

        root_block_device {
           volume_size = 10
        }
  • Purpose: Configures the root block storage attached to the instance.

  • volume_size: Sets the size of the root volume (10 GiB in this case).


9. Count

        codecount = 2
  • Purpose: Creates multiple instances of the resource.

  • count = 2: Deploys two EC2 instances with the specified configuration.


Summary

This Terraform script:

  1. Configures the AWS provider for the us-east-1 region.

  2. Deploys two EC2 instances with the following:

    • AMI: ami-0166fe664262f664c

    • Type: t2.micro

    • Key pair: NEW_KEY_PAIR

    • Security group: mysg

    • Availability zone: us-east-1e

    • Root volume size: 10 GiB

    • Tags: Terraform-ec2, Dev, Zomato.

It assumes:

  • The key pair (NEW_KEY_PAIR) is pre-created.

  • The AMI ID and availability zone are valid for the AWS region.

    1. After setting up the main.tf file with the Terraform configuration, follow these steps to deploy and manage your infrastructure:

1. Initialize Terraform

Run the following command to initialize the Terraform working directory:

        terraform init
  • Purpose: Downloads the required provider plugins and sets up the working directory.

  • If successful, you’ll see a message like:
    Terraform has been successfully initialized!


2. Validate the Configuration

Check if your configuration is syntactically valid:

        terraform validate
  • Purpose: Ensures the configuration file has no syntax or basic logical errors.

3. Plan the Deployment

Generate a detailed execution plan:

        terraform plan
  • Purpose: Shows what Terraform will do without actually making any changes.

  • Verify the resources to be created and ensure everything matches your expectations.


4. Apply the Configuration

Deploy the resources:

        terraform apply
  • Purpose: Creates the specified AWS resources.

  • Confirmation: You’ll be prompted to type yes to proceed.

  • After execution, Terraform will display the created resource details, such as instance IDs.


5. Verify the Deployment

Log in to the AWS Management Console and check:

  1. Go to the EC2 Dashboard.

  2. Look for the instances with the specified tags (Terraform-ec2, Dev, Zomato).

  3. Verify that two instances are running with the correct configurations.


6. Manage Resources

Once deployed, you can manage your resources with Terraform commands:

  • To Update Resources: Modify the main.tf file and re-run:

      terraform apply
    
  • To Destroy Resources: Clean up the deployed infrastructure:

      terraform destroy
    
    • This will remove all the resources defined in the main.tf file. Confirm by typing yes. The same will be reflected in AWS console.