Install Apache Server in Ubuntu EC2 instance using Terraform

Linu Bajy
2 min readDec 16, 2022

--

Hi everyone,

This article will show you how you can create an Ubuntu EC2 instance and install Apache Server in a single go without any manual intervention.

Prerequisite:

  • Generate a key pair of .pem extension since we need to have SSH access to an Ubuntu Instance.

Terraform file important actions:

  • Creates an Security group and adds the necessary Inbound(Ingress)/Outbound(Egress) rules
  • The Security Group is attached to an EC2 instance.
  • The Key pair name is specified which is attached to the instance.
  • The Key is used for SSH connection to the Instance.

The “remote-exec” provisioner block spcifies the commands that needs to be run in the remote instance after the instance is created.

  • The Public IP of the instance is the Output which serves the Apache server.

File Link: https://github.com/linubajy/Terraform/blob/main/remote-exec.tf


provider "aws" {
region = "us-east-1"
access_key = "demo"
secret_key = "demo"
}

resource "aws_security_group" "remote_exec_sg" {
name = "SG-1"

ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}

}


resource "aws_instance" "myec2" {
ami = "ami-0574da719dca65348"
instance_type = "t2.micro"
key_name = "ubuntu-terraform"
security_groups = [aws_security_group.remote_exec_sg.name]

connection {
type = "ssh"
user = "ubuntu"
private_key = file("./ubuntu-terraform.pem")
host = self.public_ip
}

provisioner "remote-exec" {
inline = [
"sudo apt-get install apache2 -y",
"sudo systemctl start apache2",
]
}
}

output "public_ip" {
value = aws_instance.myec2.public_ip
}

Output:

remote-exec.tf(1)
remote-exec.tf(2)
remote-exec.tf(3)

Remember , Practice makes you better, if not perfect :)

Cheers!

--

--

Linu Bajy
Linu Bajy

Written by Linu Bajy

Enthusiastic Learner . DevOps Professional .

No responses yet