resource "aws_vpc" "prod-vpc" {
cidr_block = "10.0.0.0/16"
# 2. Create Internet Gateway
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.prod-vpc.id
# 3. Create Custom Route Table
resource "aws_route_table" "prod-route-table" {
vpc_id = aws_vpc.prod-vpc.id
gateway_id = aws_internet_gateway.gw.id
gateway_id = aws_internet_gateway.gw.id
resource "aws_subnet" "subnet-1" {
vpc_id = aws_vpc.prod-vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-2a"
# 5. Associate subnet with Route Table
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.subnet-1.id
route_table_id = aws_route_table.prod-route-table.id
# 6. Create Security Group to allow port 22,80,443
resource "aws_security_group" "allow_web" {
name = "allow_web_traffic"
description = "Allow Web inbound traffic"
vpc_id = aws_vpc.prod-vpc.id
cidr_blocks = ["0.0.0.0/0"]
cidr_blocks = ["0.0.0.0/0"]
cidr_blocks = ["0.0.0.0/0"]
cidr_blocks = ["0.0.0.0/0"]
# 7. Create a network interface with an ip in the subnet that was created in step 4
resource "aws_network_interface" "web-server-nic" {
subnet_id = aws_subnet.subnet-1.id
private_ips = ["10.0.1.11"]
security_groups = [aws_security_group.allow_web.id]
# 8. Assign an elastic IP to the network interface created in step 7
resource "aws_eip" "one" {
network_interface = aws_network_interface.web-server-nic.id
associate_with_private_ip = "10.0.1.11"
depends_on = [aws_internet_gateway.gw]
output "server_public_ip" {
value = aws_eip.one.public_ip
# 9. Create Ubuntu server and install/enable apache2
resource "aws_instance" "web-server-instance" {
ami = "ami-07efac79022b86107"
instance_type = "t2.micro"
availability_zone = "us-east-2a"
network_interface_id = aws_network_interface.web-server-nic.id
sudo apt install apache2 -y
sudo systemctl start apache2
sudo bash -c 'echo "<h1>my first server created by Terraform.</h1>" > /var/www/html/index.html'
output "server_private_ip" {
value = aws_instance.web-server-instance.private_ip
value = aws_instance.web-server-instance.id