Introduction
This Terraform project sets up an AWS EC2 instance named "myweb" with a specified AMI and instance type in the "ap-south-1" region. It attaches an EBS volume ("ebs1") to the instance and configures an Apache web server on it. The project then launches Chrome locally to access the webpage hosted on the EC2 instance via its public IP address.
Prerequisites
AWS Account: Ensure you have an active AWS account with appropriate permissions to create EC2 instances, security groups, and key pairs.
Terraform Installation: Install Terraform on your local machine. You can download Terraform from the official website and follow the installation instructions.
AWS CLI Setup : Configure the AWS CLI on your machine if you prefer managing AWS credentials locally. You can install and configure AWS CLI by following the AWS CLI documentation.
Step 1: Manually Prepare AWS Resources
Create Security Group:
Log in to the AWS Management Console.
Navigate to EC2 > Security Groups.
Create a new security group allowing inbound traffic on ports 22 (SSH) and 80 (HTTP).
Create Key Pair:
Navigate to EC2 > Key Pairs.
Create a new key pair and download the
.pem
file.
Step 2: Prepare Terraform Configuration
Create
main.tf
: with vim main.tf and write this codeCreate a New Directory: Open a terminal or command prompt and create a new directory for your Terraform project:
provider "aws" { region = "ap-south-1" } //this block of code will launch aws ec2 instance resource "aws_instance" "myweb" { ami = "ami-013e83f579886baeb" instance_type = "t2.micro" key_name = "keyy" security_groups = ["securityy"] tags = { Name = "webserverss" } } // this block of code will create storage resource "aws_ebs_volume" "ebs1" { size = 2 availability_zone = aws_instance.myweb.availability_zone tags = { Name = "extra volume" } } //this block of code will attach storage with ec2 instance resource "aws_volume_attachment" "ebs_attach" { device_name = "/dev/sdb" volume_id = aws_ebs_volume.ebs1.id instance_id = aws_instance.myweb.id } //this block of code first block will help to run commands i ec2 instance os and second block will connect to the launched instance resource "null_resource" "nullremote1" { provisioner "remote-exec" { inline = [ "sudo mkfs.xfs /dev/xvdb", "sudo yum install httpd -y", "sudo mount /dev/xvdb /var/www/html", "sudo sh -c \"echo 'welcome to server' > /var/www/html/index.html\"", "sudo systemctl restart httpd" ] } connection { type = "ssh" user = "ec2-user" private_key = file("C:/Users/DELL/Downloads/keyy.pem") host = aws_instance.myweb.public_ip } } //this block of code will launch the website from local computer's command prompt resource "null_resource" "nulllocalchrome" { provisioner "local-exec" { command = "chrome http://${aws_instance.myweb.public_ip}/" } }
Congratulations you successfully launched the server.