provider "aws" {
region = "us-east-1"
access_key = ""
secret_key = "6N+"
}
# 1. Create vpc
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "lab"
}
}
# 2. Create internet gateway
resource "aws_internet_gateway" "mygw" {
vpc_id = aws_vpc.myvpc.id
tags = {
Name = "lab"
}
}
# 3. Create custom route table
resource "aws_route_table" "myroutetable" {
vpc_id = aws_vpc.myvpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.mygw.id
}
tags = {
Name = "lab"
}
}
# 4. Create a subnet
resource "aws_subnet" "subnet-1" {
vpc_id = aws_vpc.myvpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "lab"
}
}
# 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.myroutetable.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.myvpc.id
ingress {
description = "Web 443 from VPC"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "Web 80 from VPC"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "SSH from VPC"
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"]
ipv6_cidr_blocks = ["::/0"]
}
tags = {
Name = "allow_web_and_ssh"
}
}
# 7. Create a network interface with an ip in the subnet that was created in Step 4
resource "aws_network_interface" "webserver-nic" {
subnet_id = aws_subnet.subnet-1.id
private_ips = ["10.0.1.50"]
security_groups = [aws_security_group.allow_web.id]
# attachment {
# instance = aws_instance.test.id
# device_index = 1
# }
}
# 8. Assign an elastic IP to the network interface created in step 7
resource "aws_eip" "one" {
domain = "vpc"
network_interface = aws_network_interface.webserver-nic.id
associate_with_private_ip = "10.0.1.50"
depends_on = [aws_internet_gateway.mygw]
}
# 8a. Output public IP
output "server_public_ip" {
value = aws_eip.one.public_ip
}
# 9. Create Ubuntu Server and install/enable apache2
resource "aws_instance" "webserver" {
# AMI get from AWS EC2 portal
ami = "ami-053b0d53c279acc90"
instance_type = "t3.micro"
availability_zone = "us-east-1a"
key_name = "LAB Key"
network_interface {
network_interface_id = aws_network_interface.webserver-nic.id
device_index = 0
}
user_data = <<-EOF
#!/bin/bash
sudo apt update -y
sudo apt install apache2 -y
sudo systemctl start apache2
sudo bash -c 'curl checkip.dyndns.org -o /var/www/html/index.html'
EOF
tags = {
Name = "Lab"
}
}
# 9a. Output instance id
output "server_private_ip" {
value = aws_instance.webserver.private_ip
}
output "server_id" {
value = aws_instance.webserver.id
}