Saturday, March 25, 2023

Create an ec2- instance in Amazon Web services using Terraform code.

Terraform is used to create an ec2-instance in Amazon Web Services.

Create an ec2- instance using Terraform code.

Copy the AMI id from the AWS management console's launch Instance. It also specifies the instance type as t2.micro.



Also, here is the HTML script for showcasing the webpage on the instance mention the directory of the webpage. sh. Furthermore, the tag Ec2 Demo is mentioned.

# Resource: EC2 Instance
resource "aws_instance" "myec2" {
  ami           = "ami-00c39f71452c08778"
  instance_type = "t2.micro"
  user_data     = file("${path.module}/htmlscript.sh")
  tags = {
    "Name" = "Ec2 Demo"
  }
}

Next step is to create a versions file which is available in registry.terraform.io website

Mention the versions as per the latest or given once below

Also mentions the provider as aws and region in which we are creating Ec2- instance. 

# Terraform Block
terraform {
  required_version = "~> 1.3.8"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.54.0"
    }
  }
}
# Provider Block
provider "aws" {
  region = "us-east-1"
}

The final step is to write an HTML script for the instance.

We are directly creating an HTML script, so no file sharing services are required.

The html script below is directly added to the user data of the Ec2 instance.

sudo yum update -y
sudo yum install -y httpd
sudo systemctl enable httpd
sudo service httpd start  
sudo echo '<h1>Welcome to Chaitanya AWS </h1>' | sudo tee /var/www/html/index.html
sudo mkdir /var/www/html/app1
sudo echo '<!DOCTYPE html> <html> <body style="background-color:rgb(255, 160, 122 );"> <h1>Welcome to Chaitanya AWS</h1> <p>Terraform Demo</p> <p>Application Version: V1</p> </body></html>' | sudo tee /var/www/html/app1/index.html
sudo curl http://169.254.169.254/latest/dynamic/instance-identity/document -o /var/www/html/app1/metadata.html

Following completion of all steps, follow the instructions below to create an ec2 instance in AWS using Terraform.

To install all of the required plugins, run terraform init.

Type terraform validate to see if there are any semantic errors in the code.

To get a detailed output of the instance we're creating, type terraform plan.

To create an instance in AWS, enter terraform apply -auto-approve. The task will then be completed in a matter of seconds.


Now, open the AWS management console and copy the public IPv4 address to a new browser window.



Now enter /app1/index.html after the ip address of the webpage then it will redirect to index.html page of the website



That's it; we've now created a webpage with Terraform.

Now, type terraform destroy -auto-approve to destroy the created instance; this will take a few seconds.




No comments:

Post a Comment