Using Terraform provision Apache, VPC on AWS
📃Write terraform code to configure the following things on AWS -
📍Launch One VPC in north virginia having name as lwterra
📍 Create EC2 instance in this VPC
📍Launch Webserver using apache
📍Create a index.html file having content about your skills.
📍Start the webserver on port 80
📍 Create the snapshot of volume attached with the EC2 instance.
📍Destroy all the resources created in this task.
First of all create a Notepad file with name Profile.tf to install the plugins
then write following terraform code :
provider "aws" {
region = "ap-south-1"
access_key = "[access_key]"
secret_key = "[your_secret_key]"
}
Note: Replace [access_key] and [your_secret_key] with yours.
Let's start writing main.tf
(i) Let's now launch VPC for our EC2 with name lwterra .
we will take port 80
resource "aws_vpc" "lwterra" {
cidr_block = "10.0.0.0/16"
}
resource "aws_default_subnet" "subnetlw" {
availability_zone = "us-east-1a"
tags = {
Name = "Subnet for North Virginia"
}
}
resource "aws_security_group" "SecGroup" {
name = "TLS"
description = "Allow TLS inbound traffic"
vpc_id = aws_vpc.lwterra.id
ingress {
description = "TLS from VPC"
from_port = 80
to_port = 80
protocol = "tcp"
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "vpc for ec2"
}
}
(ii) Let's launch on EC2
Recommended by LinkedIn
(iii) Now we will be writing code for Webserver using apache
resource "null_resource" "test1" {
connection {
type = "ssh"
user = "ec2-user"
private_key = file("C:/Users/Aakash/Downloads/terraform_trial.pem")
host = aws_instance.webserver1.public_ip
}
provisioner "remote-exec" {
inline = [
"sudo yum install http -y",
"sudo yum install php -y",
"sudo systemctl start httpd",
"sudo systemctl start php",
"cd /var/www/html",
"vim index.html",
"<html><body><h1>Hello if you see this than you have apache running </h1></body></html>"
]
}
}
(iv) Create the snapshot of volume attached with the EC2 instance.
resource "aws_ebs_volume" "aakash_storage" {
availability_zone = aws_instance.os1.availability_zone
size = 1
tags = {
Name = "instance storage"
}
}
resource "aws_volume_attachment" "ec2_attach" {
device_name = "/dev/sdh"
instance_id = aws_instance.os1.id
volume_id = aws_ebs_volume.aakash_storage.id
}
Testing the Project
You can create your infrastructure by doing the following:
terraform init
terraform plan
# create infrastructure
terraform apply
Now we will go on our apache server
To destroy:
# cleanup infrastructure
terraform destroy
Conclusion
This completes the infrastructure concern for our web app. With this infrastructure, we have two usable networks:
Yayyy, whole task is executed.
Thanks.✌