Skip to content

Instantly share code, notes, and snippets.

@davidhamann
Last active June 8, 2020 13:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhamann/71aec97c54ee0fa5da6ad201e72a4190 to your computer and use it in GitHub Desktop.
Save davidhamann/71aec97c54ee0fa5da6ad201e72a4190 to your computer and use it in GitHub Desktop.
Sample terraform config for blog post
variable "region" { type = string }
variable "ssh_source_ips" { type = list(string) } # list of CIDR blocks
variable "ami_owner_id" { type = string }
variable "key" { type = tuple([string, string]) } # key_name and path to local private key
provider "aws" {
profile = "terraform"
region = var.region
}
data "aws_ami" "ubuntu_18" {
most_recent = true
owners = [var.ami_owner_id]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*"]
}
}
resource "aws_instance" "my_vm" {
ami = data.aws_ami.ubuntu_18.id
instance_type = "t2.micro"
key_name = var.key[0]
security_groups = [aws_security_group.ssh_http.name]
provisioner "remote-exec" {
inline = [
"sleep 10",
"sudo apt-get update",
"sudo apt-get -y install apache2",
]
connection {
type = "ssh"
user = "ubuntu"
private_key = file(var.key[1])
host = self.public_ip
}
}
}
resource "aws_security_group" "ssh_http" {
name = "ssh_http"
description = "Allow SSH and HTTP"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.ssh_source_ips
}
ingress {
from_port = 80
to_port = 80
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"]
}
}
output "instance_ip" {
value = aws_instance.my_vm.public_ip
}
output "chosen_ami" {
value = data.aws_ami.ubuntu_18.id
}
ssh_source_ips = ["x.x.x.x/28", "x.x.x.x/32"]
ami_owner_id = "099720109477". # Canonical
key = ["terraform", "~/.ssh/terraform"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment