Cloud and deployment · Intermediate · 22 min
Create and manage a DigitalOcean Droplet with OpenTofu
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · digitalocean/digitalocean 2.109 · doctl 2.11.0
You will describe a DigitalOcean Droplet with cloud-init user data, a reserved IP, a cloud firewall and a project in OpenTofu, test it offline, apply it, resize it, turn on backups and destroy it all.
On this page
A Droplet you click together in the DigitalOcean control panel works, but nothing records how you made it. Six months later you cannot say which firewall rules it has, why it sits in that region, or how to build a second one the same way. Describing it in OpenTofu fixes that: the files say what exists, the plan says what will change before it changes, and tofu destroy removes everything you made in one go.
In this tutorial you build a small web server on DigitalOcean from code. The configuration has five parts: your SSH key, a Droplet running Ubuntu 26.04 that installs Nginx on first boot through cloud-init, a reserved IP that stays the same when the Droplet changes, a cloud firewall, and a project that groups them in the control panel. Before you spend anything, you test the whole configuration offline against a mock provider. Then you apply it, make two kinds of change and learn to tell from the plan which one is safe, turn on backups, and destroy it.
You also install doctl, DigitalOcean's command-line tool, to look up regions and sizes and to confirm from outside OpenTofu what really exists. If you want to manage a server only with a CLI instead, see the Hetzner tutorial linked at the end; this one is about the declarative approach.
The Droplet and its backups are billed by DigitalOcean from the moment tofu apply creates them until tofu destroy removes them. The last step removes everything, so do the whole tutorial in one sitting if you can.
Step 1 · Install OpenTofu and doctl
Both tools ship as release archives with published SHA-256 checksums. Install curl, then download OpenTofu and check it before you unpack it. dpkg --print-architecture picks amd64 or arm64 for your machine:
sudo apt update
sudo apt install -y curl ca-certificates
TOFU_VERSION=1.13.10
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/opentofu/opentofu/releases/download/v${TOFU_VERSION}/tofu_${TOFU_VERSION}_linux_${ARCH}.tar.gz"
curl -fsSLO "https://github.com/opentofu/opentofu/releases/download/v${TOFU_VERSION}/tofu_${TOFU_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "tofu_${TOFU_VERSION}_SHA256SUMS"
tar -xzf "tofu_${TOFU_VERSION}_linux_${ARCH}.tar.gz" tofu
sudo install -m 0755 tofu /usr/local/bin/tofu
tofu versionDo the same for doctl, in the same terminal so ARCH is still set:
DOCTL_VERSION=2.11.0
curl -fsSLO "https://github.com/digitalocean/doctl/releases/download/v${DOCTL_VERSION}/doctl-${DOCTL_VERSION}-linux-${ARCH}.tar.gz"
curl -fsSLO "https://github.com/digitalocean/doctl/releases/download/v${DOCTL_VERSION}/doctl-${DOCTL_VERSION}-checksums.sha256"
sha256sum --ignore-missing -c "doctl-${DOCTL_VERSION}-checksums.sha256"
tar -xzf "doctl-${DOCTL_VERSION}-linux-${ARCH}.tar.gz" doctl
sudo install -m 0755 doctl /usr/local/bin/doctl
doctl versionBinaries you install this way get no updates through apt. When a new release is out, run the same commands with the new version number.
Check it worked
Each sha256sum line ends in OK. tofu version prints OpenTofu v1.13.10 and your platform, and doctl version prints something like doctl version 2.11.0-release.
Step 2 · Give both tools your API token
In the control panel, open API from the left-hand menu (or Account, then API), go to the Tokens tab and choose Generate New Token. Give it a name such as tofu-demo, a short expiry, and Full Access if this is a throwaway account; with Custom Scopes you pick each permission yourself, and the scopes cannot be changed afterwards. DigitalOcean shows the token only once, so copy it straight away.
Do not paste the token into a file or onto a command line, where it would end up in your shell history. Read it from a prompt into an environment variable instead. Both the OpenTofu provider and doctl read DIGITALOCEAN_ACCESS_TOKEN, so one variable serves both:
read -rs -p "DigitalOcean token: " DIGITALOCEAN_ACCESS_TOKEN; echo
export DIGITALOCEAN_ACCESS_TOKEN
doctl account getThe variable lasts until you close this terminal. Since doctl 2.0, a token that comes from the environment is not saved to doctl's config file.
Now choose a region and a size. List them:
doctl compute region list
doctl compute size list --format Slug,Memory,VCPUs,Disk,PriceMonthlyThis tutorial uses lon1 and the s-1vcpu-1gb size. Pick the region closest to the people who will use the server, and read the monthly price for the sizes you will use (s-1vcpu-1gb now and s-1vcpu-2gb in the resize step) before you go on. If your users are in West or North Africa, London, Amsterdam and Frankfurt are usually the nearest regions; measure from where your users are rather than guessing.
Check it worked
doctl account get prints your account email and a status of active. If it says Unable to authenticate you, the token was mistyped or has expired: run the read line again.
Step 3 · Describe the SSH key and the Droplet
Make a folder for the project:
mkdir -p ~/do-tofu-demo
cd ~/do-tofu-demoversions.tf pins OpenTofu and the provider. ~> 2.109 allows any 2.x release from 2.109 up, never 3.0. The empty provider block is deliberate: with no token argument, the provider reads it from DIGITALOCEAN_ACCESS_TOKEN, so the secret never appears in your files.
cat > versions.tf <<'HCL'
terraform {
required_version = ">= 1.13.0"
required_providers {
digitalocean = {
source = "digitalocean/digitalocean"
version = "~> 2.109"
}
}
}
provider "digitalocean" {}
HCLvariables.tf holds every input. ssh_cidr has no default on purpose: you must say which address may reach port 22, and the validation refuses 0.0.0.0/0, which would open SSH to the whole internet.
cat > variables.tf <<'HCL'
variable "name" {
type = string
description = "Prefix for every resource name."
default = "web-demo"
}
variable "region" {
type = string
description = "DigitalOcean region slug, from doctl compute region list."
default = "lon1"
}
variable "size" {
type = string
description = "Droplet size slug, from doctl compute size list."
default = "s-1vcpu-1gb"
}
variable "ssh_public_key_file" {
type = string
description = "Path to the public key uploaded to DigitalOcean."
default = "~/.ssh/id_ed25519.pub"
}
variable "ssh_cidr" {
type = string
description = "The one IPv4 range allowed to reach port 22, such as 203.0.113.7/32."
validation {
condition = can(cidrhost(var.ssh_cidr, 0)) && var.ssh_cidr != "0.0.0.0/0"
error_message = "ssh_cidr must be an IPv4 CIDR block narrower than 0.0.0.0/0, such as 203.0.113.7/32."
}
}
variable "page_message" {
type = string
description = "Text the home page shows."
default = "Hello from a Droplet built with OpenTofu"
}
variable "backups" {
type = bool
description = "Turn on weekly Droplet backups (billed extra)."
default = false
}
HCLThe user data is a cloud-init file that installs Nginx and writes a home page. Keep it as a template, so the page text comes from a variable. defer: true writes the file after the packages are installed:
cat > cloud-init.yaml.tftpl <<'YAML'
#cloud-config
package_update: true
packages:
- nginx
write_files:
- path: /var/www/html/index.html
permissions: "0644"
defer: true
content: |
<!doctype html>
<title>${page_message}</title>
<h1>${page_message}</h1>
YAMLmain.tf uploads your public key and creates the Droplet with it:
cat > main.tf <<'HCL'
resource "digitalocean_ssh_key" "me" {
name = "${var.name}-key"
public_key = file(pathexpand(var.ssh_public_key_file))
}
resource "digitalocean_droplet" "web" {
name = "${var.name}-web"
region = var.region
image = "ubuntu-26-04-x64"
size = var.size
ssh_keys = [digitalocean_ssh_key.me.fingerprint]
user_data = templatefile("${path.module}/cloud-init.yaml.tftpl", { page_message = var.page_message })
monitoring = true
resize_disk = false
backups = var.backups
tags = [var.name]
dynamic "backup_policy" {
for_each = var.backups ? [1] : []
content {
plan = "weekly"
weekday = "SUN"
hour = 4
}
}
}
HCLTwo settings matter later. resize_disk = false means a resize changes CPU and memory only, so you can size down again; the provider's default, true, also grows the disk, and a disk on DigitalOcean can never shrink. The dynamic "backup_policy" block adds the backup schedule only when backups is true.
Now tell OpenTofu your own public IP address, so the firewall lets you in on port 22. Find it from your router, your provider or any "what is my IP" page, and type it at the prompt:
read -r -p "Your public IPv4 address: " MY_IPprintf 'ssh_cidr = "%s/32"\n' "$MY_IP" > terraform.tfvars
cat terraform.tfvarsOn a mobile connection your public address can change between sessions, because many mobile networks share one address between customers and rotate it. If SSH stops working later, write the new address to terraform.tfvars and apply again; the firewall updates in place in a few seconds.
Download the provider and check the files:
tofu init
tofu fmt -check
tofu validateThe DigitalOcean provider is a download of a few tens of megabytes. On metered or prepaid data, run init once on a good connection; later runs reuse the copy in .terraform/.
Check it worked
tofu init ends with OpenTofu has been successfully initialized! and installs a digitalocean/digitalocean v2.109.x provider. tofu fmt -check prints nothing, and tofu validate prints Success! The configuration is valid.
Step 4 · Add the reserved IP, firewall and project
A Droplet's own public address belongs to that Droplet. If OpenTofu ever replaces the Droplet, the new one gets a new address and anything pointing at the old one breaks. A reserved IP is an address you keep and point at whichever Droplet is current. Put DNS records on the reserved IP, not on the Droplet.
Write the rest in a second file. OpenTofu reads every .tf file in the folder as one configuration:
cat > network.tf <<'HCL'
resource "digitalocean_reserved_ip" "web" {
region = var.region
droplet_id = digitalocean_droplet.web.id
}
resource "digitalocean_firewall" "web" {
name = "${var.name}-fw"
droplet_ids = [digitalocean_droplet.web.id]
inbound_rule {
protocol = "tcp"
port_range = "22"
source_addresses = [var.ssh_cidr]
}
inbound_rule {
protocol = "tcp"
port_range = "80"
source_addresses = ["0.0.0.0/0", "::/0"]
}
inbound_rule {
protocol = "icmp"
source_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "tcp"
port_range = "1-65535"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "udp"
port_range = "1-65535"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
outbound_rule {
protocol = "icmp"
destination_addresses = ["0.0.0.0/0", "::/0"]
}
}
resource "digitalocean_project" "web" {
name = var.name
description = "Web server managed by OpenTofu in ~/do-tofu-demo"
purpose = "Web Application"
environment = "Development"
resources = [
digitalocean_droplet.web.urn,
digitalocean_reserved_ip.web.urn,
]
}
output "web_ip" {
description = "The reserved IP. Point DNS here."
value = digitalocean_reserved_ip.web.ip_address
}
output "ssh_command" {
value = "ssh root@${digitalocean_reserved_ip.web.ip_address}"
}
HCL
tofu fmt -check
tofu validateThe cloud firewall runs in DigitalOcean's network, in front of the Droplet, so blocked traffic never reaches the server. Anything not listed in an inbound_rule is dropped. The project uses URNs, DigitalOcean's names for resources across products, which each resource exports as urn. Without a project, the Droplet lands in your account's default project.
Check it worked
tofu validate prints Success! The configuration is valid. again, and ls shows cloud-init.yaml.tftpl, main.tf, network.tf, terraform.tfvars, variables.tf and versions.tf.
Step 5 · Test the configuration offline
You can catch most mistakes before you create anything that bills. Start with the user data: tofu console evaluates an expression with your configuration loaded, so you can read the file cloud-init will receive:
echo 'templatefile("cloud-init.yaml.tftpl", { page_message = var.page_message })' | tofu consoleThen write a test. tofu test runs the configuration against a mock provider that never calls DigitalOcean and needs no token. A mock invents values for anything the API would return, such as IDs. That causes one problem here: the firewall and the reserved IP need the Droplet's ID as a number, and an invented random string will not convert. The mock_resource blocks give fixed, realistic values instead. The tests also use a dummy key file, so they do not need yours:
mkdir -p tests
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDummyKeyForTestsOnly test-only" > tests/test_key.pub
cat > tests/web.tftest.hcl <<'HCL'
mock_provider "digitalocean" {
mock_resource "digitalocean_droplet" {
defaults = {
id = "424242"
urn = "do:droplet:424242"
ipv4_address = "203.0.113.10"
}
}
mock_resource "digitalocean_reserved_ip" {
defaults = {
ip_address = "203.0.113.50"
urn = "do:reservedip:203.0.113.50"
}
}
}
variables {
ssh_cidr = "203.0.113.7/32"
ssh_public_key_file = "tests/test_key.pub"
}
run "creates_the_web_server" {
command = apply
assert {
condition = digitalocean_droplet.web.image == "ubuntu-26-04-x64" && digitalocean_droplet.web.size == "s-1vcpu-1gb"
error_message = "The Droplet should run Ubuntu 26.04 on s-1vcpu-1gb by default."
}
assert {
condition = digitalocean_droplet.web.resize_disk == false && digitalocean_droplet.web.backups == false
error_message = "Resizes should leave the disk alone, and backups should start off."
}
assert {
condition = digitalocean_reserved_ip.web.droplet_id == 424242
error_message = "The reserved IP should point at the Droplet."
}
assert {
condition = contains(digitalocean_firewall.web.droplet_ids, 424242)
error_message = "The firewall should protect the Droplet."
}
assert {
condition = one([for r in digitalocean_firewall.web.inbound_rule : r.source_addresses if r.port_range == "22"]) == toset(["203.0.113.7/32"])
error_message = "Port 22 should be open to ssh_cidr only."
}
assert {
condition = length(digitalocean_project.web.resources) == 2
error_message = "The project should hold the Droplet and the reserved IP."
}
assert {
condition = output.web_ip == "203.0.113.50"
error_message = "web_ip should be the reserved IP, not the Droplet's own address."
}
}
run "backups_get_a_weekly_policy" {
command = apply
variables {
backups = true
}
assert {
condition = digitalocean_droplet.web.backups && digitalocean_droplet.web.backup_policy[0].plan == "weekly"
error_message = "backups = true should add a weekly backup policy."
}
}
run "refuses_ssh_open_to_everyone" {
command = plan
variables {
ssh_cidr = "0.0.0.0/0"
}
expect_failures = [var.ssh_cidr]
}
HCL
tofu testThe first two runs apply the configuration against the mock and check the result. The last one plans with a bad input and passes only if the validation refuses it. Keep the tests/ folder: run tofu test after every change, and in CI, before anyone runs a real plan.
Check it worked
The console prints the cloud-config text between <<EOT and EOT, with Hello from a Droplet built with OpenTofu in the title and the heading. tofu test lists each run as pass and ends with something like Success! 3 passed, 0 failed. If a run fails, its error_message says which rule broke.
Step 6 · Plan and apply
Make sure the token is still in this terminal (doctl account get works), then save a plan and read it:
tofu plan -out=tfplanThe plan lists five resources that will be created: the SSH key, the Droplet, the reserved IP, the firewall and the project. It ends Plan: 5 to add, 0 to change, 0 to destroy. This is the point where billing starts, so check the region and size lines before you apply:
tofu apply tfplan
tofu outputThe apply takes a minute or two, most of it waiting for the Droplet to boot. cloud-init then needs another minute or so to install Nginx.
If the apply fails with an error that the SSH key is already in use on your account, you uploaded this key before. Find its ID and bring it under OpenTofu instead of creating a second copy:
doctl compute ssh-key list
tofu import digitalocean_ssh_key.me <key-id>Replace <key-id> with the ID from the list, then run the plan and apply again.
Check it worked
Fetch the page from the reserved IP, and check from outside OpenTofu that the parts exist:
curl -s "http://$(tofu output -raw web_ip)/"
doctl compute droplet list --format Name,PublicIPv4,Memory,VCPUs,Disk,Status
doctl compute reserved-ip list
doctl projects listcurl returns the HTML with Hello from a Droplet built with OpenTofu. If it says the connection was refused, cloud-init is still installing Nginx: wait a minute and try again. doctl shows web-demo-web as active with 1024 MB of memory, the reserved IP assigned to it, and a web-demo project. ssh root@<web_ip> logs you in with your key; from any other address, port 22 times out.
Step 7 · Resize the Droplet and read the plan
Not every change is equal. Some update a resource where it stands, others delete it and create a new one, and on a server a new one means a new disk with nothing you added by hand. The plan tells you which, before anything happens. Try both.
First, move to the next size up. Add the size to your variables file:
echo 'size = "s-1vcpu-2gb"' >> terraform.tfvars
cat terraform.tfvarstofu planThe plan shows something like this:
# digitalocean_droplet.web will be updated in-place
~ resource "digitalocean_droplet" "web" {
id = "512345678"
name = "web-demo-web"
~ size = "s-1vcpu-1gb" -> "s-1vcpu-2gb"
# (other attributes unchanged)
}
Plan: 0 to add, 1 to change, 0 to destroy.~ and updated in-place mean the Droplet keeps its ID, disk and address. The provider resizes it through the API, which powers the Droplet down first, so expect a short outage. Because resize_disk is false, the disk stays the same size, and you can go back to s-1vcpu-1gb later.
Now see a change that replaces the server. Plan, without applying, a new home page message:
tofu plan -var 'page_message=Version two'This time the Droplet must be replaced, and the user_data line is marked # forces replacement: cloud-init only reads user data on the first boot, so the provider can only apply new user data by building a new Droplet. The same is true of ssh_keys. The reserved IP, the firewall and the project show updated in-place, because they now point at the new Droplet's ID. That is the reserved IP doing its job: the address you published does not change. The summary reads something like Plan: 1 to add, 3 to change, 1 to destroy.
Do not apply that plan. Apply the resize only:
tofu applyRead the plan it shows, check it is the in-place size change, and type yes.
Check it worked
doctl compute droplet list --format Name,Memory,VCPUs,Disk,Status shows web-demo-web with 2048 MB of memory, the same disk size as before, and active again after a minute or two. curl against the reserved IP returns the same page, and a fresh tofu plan says No changes.
Step 8 · Turn on backups
Backups cost extra. On 26 November 2026, DigitalOcean's pricing page listed weekly backups at 20% and daily backups at 30% of the Droplet's monthly cost. Check the page for the current rates before you turn them on.
echo 'backups = true' >> terraform.tfvars
cat terraform.tfvarstofu plan
tofu applyThe plan shows backups changing from false to true and a backup_policy block being added, as an in-place update. The policy in main.tf takes one backup a week in the window starting at 04:00 UTC on Sunday. Change weekday and hour to suit you: the provider accepts SUN to SAT, and hours 0, 4, 8, 12, 16 or 20.
Check it worked
tofu state show digitalocean_droplet.web shows backups = true and the backup_policy block. In the control panel, the Droplet's Backups tab shows backups as enabled with the weekly schedule; the first backup appears after the next window.
Step 9 · Destroy everything
When you are finished, remove everything this configuration created. If you want to keep a backup, convert it to a snapshot in the control panel first. tofu destroy lists every resource it will delete and asks you to type yes:
tofu destroyRead the list before you answer. It names all five resources and ends Plan: 0 to add, 0 to change, 5 to destroy. The reserved IP is released too. That matters: DigitalOcean bills a reserved IP that is kept but not assigned to a Droplet.
Check from outside OpenTofu that nothing is left, then delete the token in the control panel's API page if you made it only for this tutorial:
doctl compute droplet list
doctl compute reserved-ip list
doctl compute firewall list
doctl projects list
unset DIGITALOCEAN_ACCESS_TOKENFinally, remove the folder. It holds the state file, which lists what existed and should not be left lying around:
cd ~
rm -rf ~/do-tofu-demoCheck it worked
The Droplet, reserved IP and firewall lists no longer show anything named web-demo, the web-demo project is gone from doctl projects list, and ls ~/do-tofu-demo reports that there is no such folder.
Next steps
- If any of the plan, apply, state or drift ideas here felt new, go back over them with local providers in manage infrastructure as code with OpenTofu.
- Grow the user data into a proper first-boot setup with a sudo user and SSH locked down: set up a new cloud server on first boot with cloud-init user data.
- Compare the imperative way of doing the same job on another provider: create a Hetzner Cloud server with the hcloud CLI. If you serve users in Africa, read choose a cloud region in Africa before you settle on
lon1.
Related tutorials
- How to Manage Infrastructure as Code with OpenTofuYou will install OpenTofu 1.13 on Ubuntu 26.04 from a checksum-verified release, describe two resources in code, create them with a saved plan, change and repair them, and then destroy everything, all without a cloud account.
- Create a Hetzner Cloud server with the hcloud CLI, a firewall and cloud-initYou will create an Ubuntu 26.04 server on Hetzner Cloud entirely from the hcloud command line, behind a cloud firewall and set up on first boot by your cloud-init file, then snapshot it and delete everything so billing stops.
- Set up a new cloud server on first boot with cloud-init user dataYou will write and validate one cloud-init file that gives a new Ubuntu 26.04 server a key-only sudo user, blocks root login, installs and upgrades packages, writes files with the right owners and runs setup commands once, ready to paste into any provider's user data field.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials