Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 35 ยท Automation and Terraform

Terraform on DigitalOcean

Describe DigitalOcean infrastructure as code with Terraform: the provider, VPC, Droplet, firewall and Load Balancer resources, variables, state in Spaces and plan and apply.

Shell scripts that call doctl create things, but they do not know what already exists or what changed. Terraform is declarative: you write what you want, and Terraform compares it with the real world (recorded in a state file) and works out the creates, updates and deletes. The official digitalocean/digitalocean provider covers Droplets, VPCs, firewalls, Load Balancers, volumes, domains, Kubernetes clusters, databases, Spaces, projects and more.

Terraform and DigitalOcean cannot run on this site, so the HCL is read-only and no output is invented. The Python blocks are labelled stand-ins that model how Terraform plans a change and how it expands repeated resources.

Project layout

TEXT
infra/
  versions.tf      # terraform and provider versions
  variables.tf
  main.tf
  outputs.tf
HCL
# versions.tf
terraform {
  required_version = ">= 1.6"
  required_providers {
    digitalocean = {
      source  = "digitalocean/digitalocean"
      version = "~> 2.0"
    }
  }
}

provider "digitalocean" {
  token = var.do_token
}
HCL
# variables.tf
variable "do_token" {
  type      = string
  sensitive = true
}

variable "region" {
  type    = string
  default = "nyc1"
}

variable "web_count" {
  type    = number
  default = 2
}

Pass the token with the environment variable TF_VAR_do_token (or DIGITALOCEAN_TOKEN, which the provider also reads) and never write it into a .tf file or Git.

Resources

HCL
# main.tf
data "digitalocean_ssh_key" "laptop" {
  name = "laptop"
}

resource "digitalocean_vpc" "main" {
  name     = "app-vpc"
  region   = var.region
  ip_range = "10.10.0.0/24"
}

resource "digitalocean_droplet" "web" {
  count    = var.web_count
  name     = "web-${count.index + 1}"
  region   = var.region
  size     = "s-1vcpu-1gb"
  image    = "ubuntu-24-04-x64"
  vpc_uuid = digitalocean_vpc.main.id
  ssh_keys = [data.digitalocean_ssh_key.laptop.id]
  tags     = ["web"]
  user_data = file("${path.module}/cloud-init.yaml")
}

resource "digitalocean_firewall" "web" {
  name = "web-fw"
  tags = ["web"]

  inbound_rule {
    protocol         = "tcp"
    port_range       = "443"
    source_addresses = ["0.0.0.0/0", "::/0"]
  }
  outbound_rule {
    protocol              = "tcp"
    port_range            = "1-65535"
    destination_addresses = ["0.0.0.0/0", "::/0"]
  }
}

resource "digitalocean_loadbalancer" "public" {
  name     = "web-lb"
  region   = var.region
  vpc_uuid = digitalocean_vpc.main.id

  forwarding_rule {
    entry_port     = 80
    entry_protocol = "http"
    target_port    = 8080
    target_protocol = "http"
  }
  healthcheck {
    port     = 8080
    protocol = "http"
    path     = "/healthz"
  }
  droplet_tag = "web"
}

output "lb_ip" {
  value = digitalocean_loadbalancer.public.ip
}

Things to notice: references such as digitalocean_vpc.main.id create dependencies, so Terraform builds the VPC first; count makes N Droplets; data blocks read existing objects (your SSH key) without managing them; the cloud-init file configures each server at first boot.

The workflow

Terminal
terraform init
terraform fmt
terraform validate
terraform plan -out=tfplan
terraform apply tfplan
terraform destroy

init downloads the provider, plan shows what would change (read it every time), and apply makes the changes. destroy deletes everything in the state, so be sure which workspace and token you use.

flowchart LR
  A["Your .tf files<br/>desired state"] --> P["terraform plan"]
  S["State file<br/>what Terraform knows"] --> P
  R["DigitalOcean API<br/>what is real"] --> P
  P --> D["Create / update / destroy list"]
  D --> AP["terraform apply"]
  AP --> S

Plan compares three things: your configuration, the state and the real resources.

A planner in miniature

This stand-in compares desired and current resource sets and prints the actions Terraform would plan.

Python Stand-in: a tiny plan

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Some changes (for example the image of a Droplet) cannot happen in place, so Terraform shows -/+ (replace). Always read a plan for unexpected destroys.

count versus for_each

count addresses items by position, so removing the first of three shifts the others and may recreate them. for_each addresses items by key, which is safer.

Python Stand-in: expand for_each

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

State, secrets and teamwork

  • The state file holds resource IDs and often sensitive values. Do not commit it. For teams use a remote backend: DigitalOcean Spaces is S3-compatible, so Terraform's s3 backend works with a custom endpoint and the settings that skip AWS-specific validations. Check the current backend options in the Terraform and DigitalOcean docs because the required flags change between Terraform versions.
  • Mark secrets sensitive; they are hidden from the plan output but still stored in state.
  • Use terraform import to bring existing resources under management, and lifecycle { prevent_destroy = true } on things you can never lose (databases, volumes).
  • Run plan in CI for every change and apply only after review.
  • Resources created outside Terraform and then edited in the panel cause drift; plan will show it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does terraform plan do?

    Plan compares configuration, state and reality, and lists the actions.
  2. 2. Why prefer for_each to count for named servers?

    Index-based addresses change when the list changes; key-based addresses stay stable.
  3. 3. Where should the state file live for a team?

    A shared remote backend avoids conflicts and keeps secrets out of Git.
  4. 4. How do you give the provider your token safely?

    Environment variables keep the token out of the repository.

Summary

  • Terraform describes DigitalOcean infrastructure declaratively and plans changes by comparing configuration, state and reality.
  • The provider offers VPCs, Droplets, firewalls, Load Balancers, volumes, Kubernetes and more; references create dependencies.
  • Read every plan, use for_each for named resources, and protect precious resources with prevent_destroy.
  • Keep state remote and private, and keep tokens out of code.

Next: cloud-init and Droplet User Data