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" }


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"
}
}

STEP 3: Go to view and Click on Terminal.

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


STEP 5: Generate an execution plan using the command.
terraform plan


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


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

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!
Add a Comment