Skip to content

Instantly share code, notes, and snippets.

@egonSchiele
Last active December 3, 2024 15:01
Show Gist options
  • Save egonSchiele/9a93363e4bc0952494968fc10acef54f to your computer and use it in GitHub Desktop.
Save egonSchiele/9a93363e4bc0952494968fc10acef54f to your computer and use it in GitHub Desktop.
Example code that will create an EC2 instance in AWS that you can connect to from your machine
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-west-1"
# This will tag all resources we create
# so we can easily find them later to delete.
default_tags {
tags = {
Terraform = "true"
}
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
# If you set the `Name` tag, AWS will use it
# for adding a name to your resource in the console view.
# This works for some resources but not others.
tags = {
Name = "terraform"
}
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
# assign it a public ip so we can connect to it
associate_public_ip_address = true
# references security group created below
vpc_security_group_ids = [aws_security_group.sg.id]
lifecycle {
replace_triggered_by = [aws_security_group.sg]
}
# subnet to launch the instance in
subnet_id = aws_subnet.public.id
# simple server running on port 80 so we can verify
# that the instance is up and we can connect to it
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p "80" &
EOF
}
resource "aws_security_group" "sg" {
name = "terraform"
# We need to explicitly put the security group in this VPC
vpc_id = aws_vpc.main.id
# Inbound HTTP from anywhere
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main.id
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
}
resource "aws_route_table_association" "public_subnet_asso" {
subnet_id = aws_subnet.public.id
route_table_id = aws_route_table.public.id
}
output "public-ip" {
value = aws_instance.web.public_ip
}
# Optional, print the URL for convenience
output "url" {
value = "http://${aws_instance.web.public_ip}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment