Automate servers/droplets on Digital Ocean using Terraform: a step-by-step guide
Tags: terraform, linux, devops
Published: 2021-08-05 16:05:03

This is a basic template to deploy a droplet/server on [Digital Ocean](https://m.do.co/c/54ff0945b808) using Terraform, so you don't have to use their graphical interface.


## Checklist
1. Install [Terraform](https://www.terraform.io/downloads.html)
- Create a account on [Digital Ocean](https://m.do.co/c/54ff0945b808) (Use this link to get $100 credit)
- Generate a Token/Key for your [Digital Ocean](https://m.do.co/c/54ff0945b808) account

## Generate Token on Digital Ocean
Currently (2021-08-05), the flow on [Digital Ocean's](https://m.do.co/c/54ff0945b808) website is : Go to API => Tokens/Keys => Generate New Token. Save the `string` generated.

## Terraform file
in a new folder, save this to `main.tf`:

```
terraform {
  required_providers {
    digitalocean = {
      source  = "digitalocean/digitalocean"
      version = "2.10.1"
    }
    random = {
      source  = "hashicorp/random"
      version = "3.1.0"
    }
  }
}

provider "random" {
}

resource "random_id" "server" {
  byte_length = 4
}


provider "digitalocean" {
  token = var.do_token
}

resource "digitalocean_ssh_key" "default" {
  name       = "Terraform Example"
  public_key = file("<public_key_path>")
}

resource "digitalocean_droplet" "web" {
  image    = var.image
  name     = "server-${random_id.server.hex}"
  region   = "fra1"
  size     = "s-1vcpu-1gb"
  ssh_keys = [digitalocean_ssh_key.default.fingerprint]
}

```

>In this scenario, I assume you wish to connect to the server using SSH keys, hence the "digitalocean_ssh_key" `resource`. Learn more here: 
{% link https://dev.to/costa86/managing-remote-servers-with-ssh-connection-using-windows-and-linux-45im %}

## Variables file
In the same folder, save this to `variables.tf`:
```
variable "do_token" {
  description = "Token"
  type        = string
}

variable "image" {
  description = "Linux distro"
  type        = string
  default     = "ubuntu-20-04-x64"
}
```

## Sensitive variables
If you wish to commit `variables.tf` to your version control system, you might want to use a different file for more sensitive info, such as your Digital Ocean's token. 
Save this to `terraform.tfvars`:

```
do_token = "<digital_ocean_token>"

```
>Make sure `*.tfvars` is in your `.gitignore` file. :warning:

## Digital Ocean's server/droplet settings
Notice our choices for `region`, `size` and `image` on `main.tf`. In order to obtain these values, refer to [Digital Ocean's API](https://docs.digitalocean.com/reference/api/api-reference/), replacing `$DIGITALOCEAN_TOKEN` with your generated token.
For your convenience, here's a Python template for that:

```python
import requests

url = "https://api.digitalocean.com/v2/regions"
token = "<digital_ocean_token>"

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {token}"
}
r = requests.get(url=url,headers=headers)

print(r.json())
```
## Build server

At this stage, we can use Terraform's default commands:

    terraform init
    terraform plan
    terraform apply -auto-approve
 
Now you can visit Digital Ocean's website to see if the server/droplet you just created is there. Also, make sure you can SSH-connect into it (use `root` as user).

## Delete server
This will undo everything Terraform has created. 

     terraform destroy


That's it, people.
### Thanks for the time reading this!
Follow me:
[LinkedIn](https://www.linkedin.com/in/costa86/) | [Dev.to](https://dev.to/costa86) | [Buy me a coffee](https://www.buymeacoffee.com/costa86) | [GitHub](https://github.com/costa86)
Referal links (get $100 on Digital Ocean):
[![DigitalOcean Referral Badge](https://web-platforms.sfo2.cdn.digitaloceanspaces.com/WWW/Badge%201.svg)](https://www.digitalocean.com/?refcode=54ff0945b808&utm_campaign=Referral_Invite&utm_medium=Referral_Program&utm_source=badge)