Skip to content

Instantly share code, notes, and snippets.

@suryakun
Created October 10, 2021 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suryakun/84506e926ec9c58b2494d6d296460ca3 to your computer and use it in GitHub Desktop.
Save suryakun/84506e926ec9c58b2494d6d296460ca3 to your computer and use it in GitHub Desktop.
Simple Terraform EC2 setup
provider "aws" {
region = "ap-southeast-1"
}
variable "ingress" {
type = list(number)
default = [80, 433, 22]
}
variable "egress" {
type = list(number)
default = [80, 433, 22]
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = {
Name = "myvpc"
}
}
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch = true
tags = {
"Name" = "mySubnet"
}
}
resource "aws_internet_gateway" "ig" {
vpc_id = aws_vpc.main.id
tags = {
"Name" = "myIG"
}
}
resource "aws_route_table" "public_rt" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.ig.id
}
tags = {
"Name" = "Public_RT"
}
}
resource "aws_route_table_association" "public_rt_asso" {
subnet_id = aws_subnet.main.id
route_table_id = aws_route_table.public_rt.id
}
resource "aws_security_group" "web_sg" {
vpc_id = aws_vpc.main.id
name = "Allow web traffic"
dynamic "ingress" {
iterator = port
for_each = var.ingress
content {
from_port = port.value
to_port = port.value
protocol = "TCP"
cidr_blocks = ["0.0.0.0/0"]
}
}
dynamic "egress" {
iterator = port
for_each = var.egress
content {
from_port = port.value
to_port = port.value
protocol = "TCP"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
resource "aws_key_pair" "myKey" {
key_name = "deployer-key"
public_key = file("~/.ssh/id_rsa.pub")
}
resource "aws_instance" "web" {
ami = "ami-0d058fe428540cd89"
instance_type = "t2.micro"
security_groups = [aws_security_group.web_sg.id]
subnet_id = aws_subnet.main.id
user_data = file("server-script.sh")
key_name = aws_key_pair.myKey.key_name
tags = {
Name = "Web Server"
}
}
resource "aws_eip" "web_ip" {
instance = aws_instance.web.id
}
output "PublicIP" {
value = aws_eip.web_ip.public_ip
}
@suryakun
Copy link
Author

server-script.sh

#!/bin/bash
sudo apt update
sudo apt install nginx-full

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment