Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 35 ยท Droplets and Networking

Cloud-init and User Data: Automate Your Droplet's First Boot

Use cloud-init user data to configure a new Droplet automatically: packages, users, SSH keys, files and commands. Includes a full cloud-config example, debugging tips and a linter.

Logging in to every new server to run the same commands is slow and error-prone. Cloud-init solves that. It is the industry-standard tool that reads configuration when a virtual machine boots for the first time and applies it: it creates users, installs packages, writes files and runs commands. DigitalOcean's Ubuntu, Debian and other official images include it, and you provide your instructions as user data when you create the Droplet.

Two flavours of user data

The first line decides how cloud-init treats your text:

  1. #cloud-config: a YAML document with declarative modules (packages, users, write_files, runcmd...). Preferred, because it is readable and idempotent-ish.
  2. A script starting with a shebang such as #!/bin/bash: executed once as root at first boot. Good for quick jobs.

User data is limited in size (the limit is 64 KiB), so keep it short and let it download or clone anything large. User data is not secret: anyone with access to the Droplet can read it, and it may be visible through the metadata service. Do not put passwords or private keys in it; fetch secrets from a vault at runtime.

A complete cloud-config

YAML
#cloud-config
hostname: web-1
package_update: true
package_upgrade: true

users:
  - name: deploy
    groups: [sudo, docker]
    shell: /bin/bash
    sudo: "ALL=(ALL) NOPASSWD:ALL"
    ssh_authorized_keys:
      - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... alice@laptop

packages:
  - nginx
  - ufw
  - fail2ban

write_files:
  - path: /var/www/html/index.html
    owner: root:root
    permissions: "0644"
    content: |
      <h1>Hello from a cloud-init Droplet</h1>

runcmd:
  - ufw allow OpenSSH
  - ufw allow "Nginx Full"
  - ufw --force enable
  - systemctl enable --now nginx
  - sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
  - systemctl restart ssh

Reading it from top to bottom:

  • package_update and package_upgrade run apt update and apt upgrade.
  • users creates the deploy user with an SSH key. NOPASSWD:ALL is convenient for automation, but consider something narrower for shared machines.
  • packages installs software through the package manager.
  • write_files creates files before runcmd runs (cloud-init stages them in this order), so you can drop configuration in place and then start services.
  • runcmd runs shell commands in order, once, as root.

Supplying user data

In the control panel, expand Advanced Options and paste the text into Add Initialization scripts (free). With doctl:

Terminal
doctl compute droplet create web-1 \
  --region fra1 --size s-1vcpu-1gb --image ubuntu-24-04-x64 \
  --ssh-keys <fingerprint> \
  --user-data-file cloud-config.yaml --wait

In the API it is the user_data string. In Terraform it is the user_data argument of digitalocean_droplet; see Automation and Terraform.

Debugging when something does not work

Cloud-init runs once and does not tell you loudly when it fails. SSH in and look:

Terminal
cloud-init status --long        # done, running or error
sudo less /var/log/cloud-init-output.log   # output of your commands
sudo less /var/log/cloud-init.log          # cloud-init's own steps
sudo cloud-init schema --system            # validates your user data (recent versions)

The classic mistakes are bad YAML indentation, forgetting the #cloud-config first line (it is treated as a plain file and silently ignored), and assuming network or package mirrors are ready when a command runs. Re-running on the same Droplet needs sudo cloud-init clean --logs followed by a reboot, but it is cleaner to destroy and recreate a test Droplet.

flowchart LR
  A["Droplet boots"] --> B["cloud-init reads user data"]
  B --> C{"Starts with #cloud-config?"}
  C -- "yes" --> D["Apply modules:<br/>users, packages,<br/>write_files, runcmd"]
  C -- "no, shebang" --> E["Run as script"]
  D --> F["Droplet ready"]
  E --> F

First-boot configuration happens once, automatically.

A cloud-config linter (stand-in)

The real cloud-init validates against a JSON schema on the machine itself. The program below is a stand-in: a small checker that looks for the three mistakes most beginners make: a missing header, tabs in indentation, and oversize data. It also lists the top-level modules it recognizes, using plain string handling only.

Python Stand-in: lint a cloud-config file

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.

Order of execution and idempotency

cloud-init groups modules into stages (early boot, configuration, final). Most things in #cloud-config run once per instance, while bootcmd runs on every boot. A fresh Droplet created from a snapshot of a cloud-init machine may or may not re-run user data depending on the instance ID, which is another reason to keep first-boot scripts idempotent (safe to run twice): use apt-get install -y, mkdir -p, and ln -sf.

Python Stand-in: render user data from a template

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.

Generating user data from a template is exactly what Terraform's templatefile() function does; it keeps every server consistent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must the first line of a cloud-config user data file be?

    Without the #cloud-config header cloud-init does not treat the text as a cloud-config document.
  2. 2. Which is safe to put in user data?

    User data is readable on the Droplet and via metadata. Keep secrets out; fetch them at runtime.
  3. 3. Where do you look to see why your runcmd commands failed?

    That file records the output of the commands cloud-init ran, along with errors.
  4. 4. Which module runs on every boot rather than only once?

    bootcmd runs early on every boot; runcmd runs once per instance.

Summary

  • Cloud-init applies configuration at first boot; give it user data as #cloud-config YAML or a script.
  • Common modules: users, packages, write_files, runcmd; keep data under 64 KiB and free of secrets.
  • Debug with cloud-init status --long and /var/log/cloud-init-output.log.
  • Template your user data and keep commands idempotent.

Next: VPC and Private Networking