Deploying an EC2 Instance in Terraform Using VSC.

Deploying an EC2 Instance in Terraform Using VSC.

EC2 Instance:

An EC2 instance in AWS (Amazon Web Services) is a virtual server that runs applications and services in the cloud. It is part of the Elastic Compute Cloud (EC2) service, which allows users to launch and manage virtual machines (VMs) in the cloud. EC2 instances provide a flexible, cost-effective way to run applications and services in the cloud without the need for physical hardware.

Terraform:

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp, that lets you build, change, and version cloud and on-prem resources safely and efficiently in human-readable configuration files that you can version, reuse, and share.

In this article, I will demonstrate how to launch an Amazon EC2 instance using a Terraform script, with Visual Studio Code (VSCode) as the code editor.

Requirements:

  • AWS Cloud Account.
  • IAM User with Access and Secret Access keys.
  • AWS CLI installed on your local machine.
  • Terraform Installed on your local machine.
  • Visual Studio Code.

STEP 1: Go to Visual studio code and select your folder.

  • Create providers.tf file Enter the following command and save it.
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-east-1"
}
Screenshot 2024 12 16 133104
Screenshot 2024 12 16 133201

STEP 2: Now, Create a another file main.tf.

  • Enter the command and save it.
  • AMI : Find the AMI ID on the ‘Launch Instance’ page of the Amazon EC2 console, as shown below.
  • NAME : your instance name.
resource "aws_instance" "webserver" {
  ami           = "ami-0e2c8caa4b6378d8c"
  instance_type = "t2.micro"

  tags = {
    Name = "My-server"
  }
}
Screenshot 2024 12 16 134118

STEP 3: Go to view and Click on Terminal.

Screenshot 2024 12 16 134151

STEP 4: Initialize the configuration directory. Enter the following command.

terraform init
Screenshot 2024 12 16 134229
Screenshot 2024 12 16 140250

STEP 5: Generate an execution plan using the command.

terraform plan
Screenshot 2024 12 16 140328
Screenshot 2024 12 16 140412

STEP 6: Finally, apply the configuration to create our infrastructure using the command below.

terraform apply --auto-approve
Screenshot 2024 12 16 140446
Screenshot 2024 12 16 140634

STEP 7: Go to AWS EC2 dashboard you will see your instance.

Screenshot 2024 12 16 14074611

Conclusion.

Now that you’ve learned how to launch an EC2 instance with Terraform, you can start exploring more advanced Terraform features like modules, state management, and integrations with other AWS services. The possibilities are endless!

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *