How to Provision a Digitalocean Droplet with Terraform and Run Post-deployment Scripts

Learning how to provision a DigitalOcean Droplet with Terraform and run post-deployment scripts gives you a repeatable, automated way to spin up servers. Instead of clicking through a dashboard every time, you define your infrastructure as code. Terraform handles the creation. A shell script handles the configuration. The result is a consistent, version-controlled server setup you can reproduce in minutes. This tutorial walks you through the entire process. You’ll write a Terraform configuration file, connect it to your DigitalOcean account, and attach a post-deployment script that runs automatically on first boot. By the end, you’ll have a working Droplet with software pre-installed and configured , no manual SSH required.

Prerequisites for Provisioning a DigitalOcean Droplet with Terraform

Before you start, make sure you have the following in place.

Required tools and access:

  • A DigitalOcean account with a valid API token
  • Terraform installed on your local machine (version 1.3 or higher)
  • An SSH key added to your DigitalOcean account
  • Basic familiarity with the Linux command line
  • A text editor (VS Code, Nano, or Vim all work fine)

Estimated time: 30–45 minutes

To install Terraform, visit the official Terraform installation page and follow the instructions for your operating system. On Ubuntu, you can install it with a few apt commands. On macOS, Homebrew works well.

You’ll also need your DigitalOcean API token ready. Log into your DigitalOcean dashboard, go to API, and generate a personal access token with read and write permissions. Keep it somewhere safe. You’ll use it in the next section.

No prior Terraform experience is needed. If you understand basic shell scripting and have used Linux before, you’re ready to follow along.

Step-by-Step Guide to Provisioning Your Droplet with Terraform

For a related walkthrough, see: How to Create and Register Custom Post Types in WordPress with the Register_post_type() Function

Step 1: Create a project directory

Start by creating a dedicated folder for your Terraform project.

mkdir terraform-droplet
cd terraform-droplet

This keeps all your configuration files in one place. Terraform looks for .tf files in the current directory when you run commands.

Step 2: Write your post-deployment shell script

Create a file called setup.sh. This script runs on the Droplet immediately after it boots for the first time.

#!/bin/bash
apt-get update -y
apt-get install -y nginx ufw
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable
systemctl enable nginx
systemctl start nginx
echo "Droplet setup complete" >> /var/log/setup.log

This script updates the package list, installs Nginx, configures the firewall, and starts the web server. You can extend it to install PHP, MySQL, or anything else you need.

Step 3: Create the main Terraform configuration file

Create a file called main.tf in your project directory.

terraform {
  required_providers {
    digitalocean = {
      source  = "digitalocean/digitalocean"
      version = "~> 2.0"
    }
  }
}

provider "digitalocean" {
  token = var.do_token
}

data "digitalocean_ssh_key" "my_key" {
  name = var.ssh_key_name
}

resource "digitalocean_droplet" "web" {
  image    = "ubuntu-22-04-x64"
  name     = "web-server-01"
  region   = "nyc3"
  size     = "s-1vcpu-1gb"
  ssh_keys = [data.digitalocean_ssh_key.my_key.id]
  user_data = file("setup.sh")
}

The user_data argument is where the magic happens. DigitalOcean passes the contents of setup.sh to cloud-init. Cloud-init runs the script as root on first boot. This is how you automate post-deployment configuration without ever logging in manually.

Step 4: Create a variables file

Create a file called variables.tf to define your input variables.

variable "do_token" {
  description = "DigitalOcean API token"
  type        = string
  sensitive   = true
}

variable "ssh_key_name" {
  description = "Name of the SSH key in DigitalOcean"
  type        = string
}

Step 5: Create a terraform.tfvars file

Create terraform.tfvars to supply values for those variables. Never commit this file to version control.

do_token     = "your_digitalocean_api_token_here"
ssh_key_name = "your_ssh_key_name_here"

Replace the placeholder values with your actual token and the exact name of your SSH key as it appears in DigitalOcean.

Step 6: Initialize Terraform

Run the following command to download the DigitalOcean provider plugin.

terraform init

You’ll see Terraform download the provider and create a .terraform directory. This only needs to run once per project.

Step 7: Preview and apply your configuration

First, preview what Terraform will create.

terraform plan

Review the output carefully. You should see one resource being created: your Droplet. When you’re happy with it, apply the configuration.

terraform apply

Type yes when prompted. Terraform will provision the Droplet. After 30–60 seconds, it’ll be live. The post-deployment script starts running in the background immediately on first boot.

Step 8: Verify the setup

Grab the Droplet’s IP address from the Terraform output or your DigitalOcean dashboard. Then SSH in and check the log file your script created.

ssh root@your_droplet_ip
cat /var/log/setup.log

If you see “Droplet setup complete”, the script ran successfully. You can also check Nginx with systemctl status nginx.

Troubleshooting Common Post-deployment Script Issues

Script didn’t run at all
Check that your setup.sh file starts with #!/bin/bash. Without the shebang line, cloud-init won’t execute it correctly. Also verify the file exists in the same directory as main.tf.

Terraform can’t find your SSH key
The name in terraform.tfvars must match exactly what’s in your DigitalOcean account. Go to Settings → Security → SSH Keys and copy the name precisely.

API authentication error
Double-check your token has both read and write permissions. A read-only token won’t let Terraform create resources.

Droplet created but Nginx isn’t running
SSH into the Droplet and check the cloud-init log for errors.

cat /var/log/cloud-init-output.log

This log shows exactly what happened during the user_data script execution. Most errors are package name typos or missing dependencies.

Destroying resources
When you’re done testing, clean up to avoid charges.

terraform destroy

Type yes to confirm. Terraform removes all resources it created. For more details on managing DigitalOcean infrastructure, check the DigitalOcean API documentation.

Conclusion

You now know how to provision a DigitalOcean Droplet with Terraform and run post-deployment scripts automatically on first boot. You wrote a reusable Terraform configuration, attached a shell script via user_data, and deployed a fully configured server without touching the DigitalOcean dashboard. This workflow scales well. You can add more resources, use Terraform modules, or extend your setup script to install WordPress, configure databases, or set up SSL certificates. The same pattern works for staging environments, production servers, and everything in between. Infrastructure as code means fewer mistakes and faster deployments every time you need a new server.

Similar Posts