Logo

Terraform For EC2

Here's some non-trivial terraform for spinning up an EC2 instance:

Hope this helps someone!

data "aws_security_group" "selected" {
  name = "webserver rules"
}

data "aws_key_pair" "web" {
  key_name = "awskeypair-webserver"
}

resource "aws_instance" "web" {
  ami           = "ami-007855ac798b5175e"
  instance_type = "t2.micro"
  vpc_security_group_ids = [data.aws_security_group.selected.id]
  tags = {
    Name = "Nginx"
  }
  key_name = data.aws_key_pair.web.key_name
  user_data = "${file("init.sh")}"
  user_data_replace_on_change = true
  provisioner "file" {
    source      = "ssl/generated-private-key.txt"
    destination = "/home/ubuntu/generated-private-key.txt"
    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/.ssh/awskeypair-webserver.pem")}"
      host        = "${self.public_dns}"
    }
  }
  provisioner "file" {
    source      = "ssl/chained.crt"
    destination = "/home/ubuntu/chained.crt"
    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/.ssh/awskeypair-webserver.pem")}"
      host        = "${self.public_dns}"
    }
  }
  provisioner "file" {
    source      = "nginx.conf"
    destination = "/home/ubuntu/nginx.conf"
    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = "${file("~/.ssh/awskeypair-webserver.pem")}"
      host        = "${self.public_dns}"
    }
  }
}

resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.web.id
  allocation_id = data.aws_eip.nginx.id
}

data "aws_eip" "nginx" {
  tags = {
    Name = "nginx"
  }
}

Here is init.sh. Note that installing nginx seems to start it for us, so to pick up our config we have to restart it.

echo "Updating the OS"
apt update -y

echo "Installing nginx"
apt install -y nginx
echo "Removing the default site"
rm /etc/nginx/sites-enabled/default
echo "Linking my-site.conf -> nginx.conf"
ln -s /home/ubuntu/nginx.conf /etc/nginx/sites-enabled/my-site.conf

echo "Starting nginx"
nginx

echo "Trying to restart nginx"
nginx -s stop
nginx