This is a basic template to deploy a droplet/server on Digital Ocean using Terraform, so you don't have to use their graphical interface.
Checklist
- Install Terraform
- Create a account on Digital Ocean (Use this link to get $100 credit)
- Generate a Token/Key for your Digital Ocean account
Generate Token on Digital Ocean
Currently (2021-08-05), the flow on Digital Ocean's 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:
Managing remote servers with SSH and SFTP connections: a step-by-step guide
Lourenço Costa ・ Jul 17 '21 ・ 12 min read
#ssh #sftp #devops #security
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. ⚠️
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, replacing $DIGITALOCEAN_TOKEN
with your generated token.
For your convenience, here's a Python template for that:
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 | Dev.to | Buy me a coffee | GitHub
Referal links (get $100 on Digital Ocean):
Top comments (0)