basic-docker-host/main.tf

157 lines
3.3 KiB
HCL

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.45.0"
}
}
}
provider "aws" {
region = var.aws_region
access_key = var.aws_access_key
secret_key = var.aws_secret_key
}
resource "aws_vpc" "main_vpc" {
cidr_block = var.vpc_cidr
tags = {
Name = "main-vpc"
}
}
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main_vpc.id
tags = {
Name = "main-igw"
}
}
resource "aws_subnet" "public_subnet" {
vpc_id = aws_vpc.main_vpc.id
cidr_block = var.public_cidr
availability_zone = "${var.aws_region}a"
map_public_ip_on_launch = true
tags = {
Name = "public-subnet"
}
}
# Create a route table with a route to the internet through the Internet Gateway
resource "aws_route_table" "public_rt" {
vpc_id = aws_vpc.main_vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
}
# Associate route table with the public subnet, enabling outgoing traffic to reach the internet.
resource "aws_route_table_association" "public_rt_association" {
subnet_id = aws_subnet.public_subnet.id
route_table_id = aws_route_table.public_rt.id
}
resource "tls_private_key" "ssh_key" {
algorithm = "RSA"
rsa_bits = 4096
}
resource "local_file" "private_key" {
content = tls_private_key.ssh_key.private_key_pem
filename = "./.ssh/terraform_rsa"
}
resource "local_file" "public_key" {
content = tls_private_key.ssh_key.public_key_openssh
filename = "./.ssh/terraform_rsa.pub"
}
resource "aws_key_pair" "deployer" {
key_name = "ubuntu_ssh_key"
public_key = tls_private_key.ssh_key.public_key_openssh
}
# Firewall
resource "aws_security_group" "allow_ssh_http_https" {
vpc_id = aws_vpc.main_vpc.id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
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"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
data "aws_ami" "latest_ecs" {
most_recent = true
owners = ["591542846629"] # AWS
filter {
name = "name"
values = ["*amazon-ecs-optimized"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
# Ubuntu AMI ID search
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
resource "aws_instance" "ubuntu_instance" {
ami = data.aws_ami.ubuntu.id
# Ubuntu "ami-0a0e5d9c7acc336f1"
# ami = data.aws_ami.latest_ecs.ami # Amazon Linux
instance_type = var.instance_size
subnet_id = aws_subnet.public_subnet.id
vpc_security_group_ids = [aws_security_group.allow_ssh_http_https.id]
key_name = aws_key_pair.deployer.key_name
associate_public_ip_address = true
depends_on = [
aws_security_group.allow_ssh_http_https,
aws_internet_gateway.igw
]
user_data = var.user_data
}