Today I created a virtual machine in Digital Ocean with Terraform! Had been a while, it’s surprising how straight forward things can be now a days in the DevOps space. You can register in Digital Ocean here, create a personal token here and generate the ssh keys here.

Really solid docs on how to install and do a quick start in Terraform as well as the Digital Ocean provider. Less than 5 minutes and you have your automation for creating infrastructure!

Put the following content in a main.tf file after installing terraform

# Define variables
variable "do_token" {}
variable "do_sshkey" {}

# Define dependencies (The digital ocean provider)
terraform {
  required_providers {
    digitalocean = {
      source = "digitalocean/digitalocean"
    }
  }
}

# Give the provider your token
provider "digitalocean" {
  token = var.do_token
}

# Define the VM resource, ubuntu LTS in SF with the cheapest configuration
resource "digitalocean_droplet" "web" {
  image    = "ubuntu-20-04-x64"
  name     = "web-1"
  region   = "sfo3"
  size     = "s-1vcpu-1gb"
  ssh_keys = [var.do_sshkey]
}

And do it

> terraform init
> terraform validate

# Replace xxxxxxx with your personal access token and yyyyyyy with your ssh key id.

# See what terraform will do!
> terraform plan --var do_sshkey=yyyyyyy --var do_token=xxxxxxx

# Create the VM!
> terraform apply --var do_sshkey=yyyyyyy --var do_token=xxxxxxx

# Get the IP
> terraform show | grep "ipv4"

# Connect to it, replace xxxx.xxxx.xxxx.xxxx with your IP.
> ssh root@xxxx.xxxx.xxxx.xxxx 

Once you’re done playing with with it, delete it so that it doesn’t cost you money

terraform destroy --var do_sshkey=yyyyyyy --var do_token=xxxxxxx

You can check the final repo in my github here