Skip to main content
  1. Posts/

Provisioning VPS With Terraform

Table of Contents

Terraform (TF) provides a declarative way to create, change, and version your infrastructure. Whenever you need to add a load balancer, change DNS records, create new Kubernetes cluster or just VPS, TF has you covered. Let’s use DigitalOcean (DO) to showcase how infrastructure as code can simplify the organization of online resources.

Token #

To access DO resources you need access token. Place the token into .zshrc and load newly exported env variable with source ~/.zshrc.

export DIGITALOCEAN_TOKEN=<token>

SSH key #

Upload your public ssh key to DO and copy fingerprint. If you have doctl installed and already added your ssh key to your DigitalOcean account, run doctl compute ssh-key list.

Terraform #

resource "digitalocean_droplet" "vps" {
  image    = "ubuntu-18-04-x64"
  name     = "vps"
  region   = "fra1"
  size     = "s-1vcpu-1gb"
  ssh_keys = ["<insert_ssh_key_fingerprint_from_DO>"]
}

output "ip_address" {
  value = "${digitalocean_droplet.vps.ipv4_address}"
}

Create vps.tf file with config above and put the SSH fingerprint into it. It will create a droplet (DO’s name for VPS) with Ubuntu OS in Frankfurt with 1 vCPU and 1 GB memory and after creation TF will output the IP address. Now that we have saved our file we can start with TF initialization.

terraform init

Terraform downloads DO provider and we are ready to go. Before running our file we should validate our it.

terraform validate

If we have a previous infrastructure plan will show us the differences when running apply.

terraform plan

Now we run apply. TF will inform you that it will create a new droplet. You confirm your action and TF will create VPS on DO on your behalf.

terraform apply

After successful creation, you get an IP address. You could ssh to your VPS like so ssh root@<ip> or use code below to add it to ssh hosts.

cat <<EOF >> ~/.ssh/config
Host vps
  HostName <ip>
  User root
EOF

Now you can connect by just ssh vps.

If you feel ready to prime time you can add more lines with DNS record pointing to your VPS.

When you are done with experimenting just delete the VPS with

terraform destroy