Skip to content

Instantly share code, notes, and snippets.

@sonoroot
Last active December 14, 2019 17:24
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 sonoroot/e401ab009571750ff863042ba4aeb64a to your computer and use it in GitHub Desktop.
Save sonoroot/e401ab009571750ff863042ba4aeb64a to your computer and use it in GitHub Desktop.

Terraform

Templates

Basic AWS instance

provider "aws" {
  region = "eu-central-1"
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-*-18.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

resource "aws_instance" "my-instance" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.nano"

  tags = {
    Name = "MyInstance"
  }
}

# Optionally assign Elastic IP (implicit dependancy)

resource "aws_eip" "ip" {
    vpc = true
    instance = aws_instance.my-instance.id
}

Basic S3 bucket and EC2 (with explicit dependancy)

provider "aws" {
  region = "eu-central-1"
}

resource "aws_s3_bucket" "example" {
  bucket = "bucket-from-hell"
  acl    = "private"
}

resource "aws_instance" "instance-name-here" {
  ami           = "ami-xxxxx
  instance_type = "t2.micro"

  depends_on = [aws_s3_bucket.example]
}

Local Provisioner

resource "aws_instance" "example" {
  ami           = "ami-b374d5a5"
  instance_type = "t2.micro"

  provisioner "local-exec" {
    command = "echo ${aws_instance.example.public_ip} > ip_address.txt"
  }
}

Remote Provisioner

resource "aws_key_pair" "example" {
  key_name = "examplekey"
  public_key = file("~/.ssh/id_rsa.pub")
}

resource "aws_instance" "web" {
  key_name = aws_key_pair.example.key_name
  # ...

 connection {
    type     = "ssh"
    user     = "root"
    private_key = file("~/.ssh/id_rsa")
    host     = self.ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }

VARIABLES

# Lists

# implicitly by using brackets [...]
variable "cidrs" { default = [] }

# explicitly
variable "cidrs" { type = list }

# Maps

variable "amis" {
  type = "map"
  default = {
    "us-east-1" = "ami-b374d5a5"
    "us-west-2" = "ami-4b32be2b"
  }
}

# how to use it:

resource "aws_instance" "example" {
  ami           = var.amis[var.region]
  instance_type = "t2.micro"
}

OUTPUTS

output "ip" {
  value = aws_eip.ip.public_ip
}

CLI

Taint (destroy and re-create)

terraform taint aws_instance.myinstance

Assign variables on the fly

terraform apply -var 'region=us-east-2'
terraform apply -var 'amis={ us-east-1 = "foo", us-west-2 = "bar" }'

Show output

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