Skip to content

Instantly share code, notes, and snippets.

@franzwong
Created February 4, 2019 10:12
Show Gist options
  • Save franzwong/2f57745ba9f75925a811ceb3eb859a63 to your computer and use it in GitHub Desktop.
Save franzwong/2f57745ba9f75925a811ceb3eb859a63 to your computer and use it in GitHub Desktop.
Sample Terraform stack for EC2 and VPC
variable "aws_region" {
default = "us-east-1"
}
variable "vpc_cidr" {
default = "10.0.0.0/16"
}
variable "webSubnetCidr" {
default = "10.0.1.0/24"
}
variable "appSubnetCidr" {
default = "10.0.2.0/24"
}
variable "ami" {
default = "ami-035be7bafff33b6b6"
}
variable "keypair" {
default = "myKeyPair"
}
provider "aws" {
region = "${var.aws_region}"
}
resource "aws_instance" "web" {
ami = "${var.ami}"
instance_type = "t2.micro"
subnet_id = "${aws_subnet.web.id}"
key_name = "${var.keypair}"
vpc_security_group_ids = ["${aws_security_group.web.id}"]
associate_public_ip_address = true
root_block_device {
volume_size = "8"
volume_type = "gp2"
}
}
resource "aws_instance" "app" {
ami = "${var.ami}"
instance_type = "t2.micro"
subnet_id = "${aws_subnet.app.id}"
key_name = "${var.keypair}"
vpc_security_group_ids = ["${aws_security_group.app.id}"]
associate_public_ip_address = false
root_block_device {
volume_size = "8"
volume_type = "gp2"
}
}
resource "aws_vpc" "default" {
cidr_block = "${var.vpc_cidr}"
enable_dns_hostnames = true
}
resource "aws_subnet" "web" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "${var.webSubnetCidr}"
}
resource "aws_subnet" "app" {
vpc_id = "${aws_vpc.default.id}"
cidr_block = "${var.appSubnetCidr}"
}
resource "aws_internet_gateway" "default" {
vpc_id = "${aws_vpc.default.id}"
}
resource "aws_route_table" "public" {
vpc_id = "${aws_vpc.default.id}"
route {
cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.default.id}"
}
}
resource "aws_route_table_association" "public" {
subnet_id = "${aws_subnet.web.id}"
route_table_id = "${aws_route_table.public.id}"
}
resource "aws_security_group" "web" {
name = "web"
vpc_id = "${aws_vpc.default.id}"
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 = -1
to_port = -1
protocol = "icmp"
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 = ["${var.appSubnetCidr}"]
}
}
resource "aws_security_group" "app" {
name = "app"
vpc_id = "${aws_vpc.default.id}"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["${var.webSubnetCidr}"]
}
ingress {
from_port = -1
to_port = -1
protocol = "icmp"
cidr_blocks = ["${var.webSubnetCidr}"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["${var.webSubnetCidr}"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment