Skip to main content

Infrastructure as code · Beginner · 16 min

Set up a new cloud server on first boot with cloud-init user data

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · cloud-init 26.2

You 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.

On this page

Setting up a new server by hand means logging in as root, adding a user, copying a key, locking SSH down and installing packages, in the right order, every time. cloud-init does that work for you. It ships with Ubuntu Server and almost every cloud image, and on the very first boot it reads a file you hand to the provider, called user data, and applies it before you ever log in.

In this tutorial you write that file once and check it on your own machine before any server sees it. By the end, ~/cloud-init-demo/user-data.yaml will:

  • create a deploy user that can only log in with your SSH key and can use sudo
  • refuse SSH logins as root and with passwords
  • update the package lists, upgrade what is installed, and add ufw, unattended-upgrades and jq
  • write a config file owned by deploy and an SSH rule owned by root, each with its own permissions
  • run a few commands once, on first boot only, including turning on the firewall

You validate it with cloud-init schema, preview exactly what a server will receive with cloud-init devel render, then paste the same file into AWS, Hetzner or DigitalOcean. If you would rather do the setup by hand over SSH, follow the initial server setup tutorial instead; this one replaces those steps with a file.

Step 1 · Install cloud-init on the machine you write on

Every command up to the "Paste the file" step runs on your own Ubuntu 26.04 machine, not on a new server. Install cloud-init there so you can use its checker, and make a folder for this tutorial:

Bash
sudo apt update
sudo apt install -y cloud-init
cloud-init --version
mkdir -p ~/cloud-init-demo
cd ~/cloud-init-demo

Installing the package on a desktop or WSL does not change how that machine boots in any way you will notice: with no cloud to talk to, it finds nothing to do.

You also need the public half of your SSH key, because it goes into the file. Check that it exists:

Bash
ls -l ~/.ssh/id_ed25519.pub

If it is missing, create one as shown in log in to a server with SSH keys. If your key lives on another computer, copy its .pub file to ~/.ssh/id_ed25519.pub here. Only the public key goes into user data; the private key never leaves your computer.

Check it worked

cloud-init --version prints something like /usr/bin/cloud-init 26.2-0ubuntu1~26.04.2, and ls lists ~/.ssh/id_ed25519.pub. A 26.x version is what this tutorial assumes; older versions accept the same file but may report errors with different wording.

Step 2 · Start the file with a key-only sudo user

A cloud-init file is YAML. The #cloud-config line tells cloud-init that the file is configuration, not a shell script. The line above it, ## template: jinja, lets you drop per-server values into the file later; you will use it in the "Write files" step.

Write the start of the file. The cat inside the heredoc puts your real public key into the file, so there is nothing to paste by hand:

Bash
cd ~/cloud-init-demo
cat > user-data.yaml <<YAML
## template: jinja
#cloud-config
users:
  - name: deploy
    gecos: Deploy user
    groups: [sudo]
    shell: /bin/bash
    lock_passwd: true
    sudo: "ALL=(ALL) NOPASSWD:ALL"
    ssh_authorized_keys:
      - $(cat ~/.ssh/id_ed25519.pub)

disable_root: true
ssh_pwauth: false
YAML

What each part does:

  • lock_passwd: true means deploy has no password at all, so nobody can guess one. The only way in is your key.
  • sudo: "ALL=(ALL) NOPASSWD:ALL" follows from that. With no password, a normal sudo would ask for one and the user could never type it, so sudo is allowed without one. Anyone holding your private key can become root, so protect that key with a passphrase.
  • Listing your own user replaces the image's default one. Ubuntu images normally create a user called ubuntu. Because users: does not include default, that user is not created and deploy is the only way in.
  • disable_root: true (also cloud-init's default) does not leave root's key out. cloud-init still writes the provider's key to root's authorized_keys, but with a forced command in front of it, so a key login as root only prints a "Please login as the user ... rather than the user root" message and ends the session. ssh_pwauth: false turns off SSH password logins for everyone.

The provider still asks you for an SSH key when you create a server. That key goes to the default user, which this file removes, so your key here is the one that counts.

Now make a small sample of the instance data that a cloud gives cloud-init on boot. The checker needs it because the file is a template:

Bash
cat > sample-instance-data.json <<'JSON'
{
  "v1": {
    "cloud_name": "hetzner",
    "local_hostname": "web-1",
    "instance_id": "demo-0001"
  }
}
JSON
cloud-init schema --config-file user-data.yaml --instance-data sample-instance-data.json

On a cloud server, cloud-init builds this data itself, from the provider's metadata service, with many more keys. The three here are enough for this file.

Check it worked

cloud-init schema prints Valid schema user-data.yaml. grep -c ssh-ed25519 user-data.yaml prints 1, which shows your key went into the file and not the literal text $(cat ...).

Step 3 · Update, upgrade and install packages

A fresh image is days or weeks old, so the first thing a server should do is take the security updates published since. Append the package settings:

Bash
cd ~/cloud-init-demo
cat >> user-data.yaml <<'YAML'

package_update: true
package_upgrade: true
packages:
  - ufw
  - unattended-upgrades
  - jq
YAML
cloud-init schema --config-file user-data.yaml --instance-data sample-instance-data.json

package_update runs apt update, package_upgrade upgrades everything already installed, and packages installs the list. The heredoc marker is in quotes this time (<<'YAML'), so the shell copies the text exactly and does not try to expand anything in it.

The downloads happen on the server, over the provider's network, not over your own connection. If you work on prepaid mobile data, that matters: the file you send is a few hundred bytes, while a first-boot upgrade can pull down a few hundred megabytes, and none of it comes out of your bundle.

An upgrade sometimes includes a new kernel, which only takes effect after a reboot. The last step shows how to check for that once you are logged in.

Check it worked

cloud-init schema still prints Valid schema user-data.yaml, and tail -n 7 user-data.yaml shows the three package keys at the end of the file.

Step 4 · Write files with owners and permissions

write_files creates files with exactly the content, owner and mode you give. Add two: an SSH rule owned by root, and an app config owned by deploy:

Bash
cd ~/cloud-init-demo
cat >> user-data.yaml <<'YAML'

write_files:
  - path: /etc/ssh/sshd_config.d/10-no-root-login.conf
    owner: root:root
    permissions: "0644"
    content: |
      # Written by cloud-init on first boot.
      PermitRootLogin no
  - path: /srv/app/app.conf
    owner: deploy:deploy
    permissions: "0640"
    defer: true
    content: |
      # Written by cloud-init on first boot.
      host = {{ v1.local_hostname }}
      cloud = {{ v1.cloud_name }}
YAML
cloud-init schema --config-file user-data.yaml --instance-data sample-instance-data.json

Three details are worth knowing:

  • The SSH rule's name starts with 10-. For most settings, OpenSSH keeps the first value it reads, and it reads the files in /etc/ssh/sshd_config.d/ in name order. A low number means your rule is read before anything a provider or package adds later. disable_root only turns a root key login into a message and a closed session; PermitRootLogin no makes SSH refuse root before any session starts.
  • defer: true on the app config. cloud-init writes files early in boot, before it creates users. Without defer, the owner deploy:deploy would not exist yet and the write would fail. Deferred files are written in the final stage, after users and packages.
  • {{ v1.local_hostname }} is filled in on the server, from that server's own instance data. One file can then serve many servers, and each gets its own hostname in its config.

Never put passwords, API tokens or private keys in user data. Any program on the server can usually read it back from the provider's metadata service, and it is stored on disk under /var/lib/cloud. Fetch secrets after boot from a secret store instead.

Check it worked

cloud-init schema prints Valid schema user-data.yaml. Run grep -n 'defer: true' user-data.yaml and you see one match, under /srv/app/app.conf.

Step 5 · Run setup commands once and validate the whole file

runcmd holds commands that run once, on the first boot of each new server. Rebooting the server later does not run them again.

Order matters in the firewall lines: SSH must be allowed before ufw is enabled, or the server would block your only way in.

Append the commands and a closing message:

Bash
cd ~/cloud-init-demo
cat >> user-data.yaml <<'YAML'

runcmd:
  - [systemctl, restart, ssh]
  - [ufw, allow, OpenSSH]
  - [ufw, --force, enable]
  - [install, -d, -o, deploy, -g, deploy, -m, "0750", /srv/app/data]

final_message: "First boot finished after $UPTIME seconds"
YAML
cloud-init schema --config-file user-data.yaml --instance-data sample-instance-data.json

Each command is a list, which cloud-init runs without a shell, so there are no quoting surprises. systemctl restart ssh makes sure the SSH server has read the new root rule. --force stops ufw waiting for a yes/no answer that nobody is there to give. $UPTIME in final_message is filled in by cloud-init, not by your shell.

When each part runs

cloud-init works through five stages on first boot, and knowing them explains why defer and the command order matter:

  1. Detect: works out which cloud it is running on.
  2. Local: reads local data and sets up the network configuration.
  3. Network: with the network up, fetches your user data, writes the non-deferred files and creates users and SSH keys.
  4. Config: runs configuration modules. runcmd is saved as a script here but does not run yet.
  5. Final: installs packages, writes deferred files, then runs your runcmd script, so ufw is installed before the commands that use it.

See a mistake caught

Make a broken copy to see what an error looks like. runcmd must be a list, so a plain string is wrong:

Bash
cat > broken.yaml <<'YAML'
#cloud-config
package_update: true
runcmd: ufw enable
YAML
cloud-init schema --config-file broken.yaml

Check it worked

For user-data.yaml, cloud-init schema prints Valid schema user-data.yaml. For broken.yaml, it prints Invalid user-data broken.yaml and an error naming runcmd, something like runcmd: 'ufw enable' is not of type 'array', and exits with an error. Delete the broken copy with rm broken.yaml.

Step 6 · Preview exactly what a server will get

The schema check tells you the file is well formed. cloud-init devel render shows you the file with the template values filled in, which is what cloud-init on the server will act on:

Bash
cd ~/cloud-init-demo
cloud-init devel render --instance-data sample-instance-data.json user-data.yaml > rendered.yaml
grep -n -A 3 'path: /srv/app/app.conf' rendered.yaml
grep -nE 'host = |cloud = ' rendered.yaml

Read rendered.yaml from top to bottom once. It is short, and reading it is how you catch things no checker can: a key for the wrong person, a package name with a typo, a file in the wrong place.

If you misspell a variable, for example {{ v1.local_hostnme }}, rendering still succeeds but the value comes out as a marker such as CI_MISSING_JINJA_VAR/local_hostnme. Search for that marker before you use a file:

Bash
if grep -n CI_MISSING_JINJA_VAR rendered.yaml; then echo "fix the variables listed above"; else echo "no missing variables"; fi

Check it worked

The first grep shows the app config entry, and the second prints host = web-1 and cloud = hetzner, the values from your sample data. The ## template: jinja line is gone from rendered.yaml, which now starts with #cloud-config. The last command prints no missing variables.

Step 7 · Paste the file into your provider's user data field

Read this before you create anything: a server bills from the moment it exists, until you delete it. Check your provider's current prices and any free credit on your account first.

Every major provider has a user data field in its create-server form, sometimes called "cloud config" or "initialization script". Paste the whole of user-data.yaml there, including the ## template: jinja line. Send the template, not rendered.yaml: cloud-init on the server fills in that server's real hostname. Choose an Ubuntu 26.04 image.

From the command line, each provider takes the file directly. Replace the values in angle brackets with your own choices (image, size, Region or location):

Bash
# AWS (the CLI base64-encodes the file for you)
aws ec2 run-instances --image-id <ubuntu-26.04-ami-id> --instance-type <type> \
  --security-group-ids <group-that-allows-ssh> --user-data file://user-data.yaml

# Hetzner Cloud
hcloud server create --name web-1 --type <type> --image <ubuntu-26.04-image> \
  --location <location> --user-data-from-file user-data.yaml

# DigitalOcean
doctl compute droplet create web-1 --image <ubuntu-26.04-image> --size <size> \
  --region <region> --user-data-file user-data.yaml

Make sure the provider's own firewall, if it has one (a security group on AWS), allows SSH on port 22 from your address. ufw on the server is a second layer, not a replacement.

AWS limits user data to 16 KB. This file is well under that, but if yours grows large, move the bulk into packages or a script the server downloads.

Check it worked

The provider's server list shows the new server as running, with a public IPv4 address and the Ubuntu 26.04 image. Note the address; you need it in the next step.

Step 8 · Log in and read what cloud-init did

Give the server a minute or two, then log in as deploy from the machine that holds your private key. Replace <server-ip> with the address from the last step:

Bash
ssh deploy@<server-ip>

On the server, wait for cloud-init to finish and see its result:

Bash
cloud-init status --wait --long

Then read the two logs. /var/log/cloud-init-output.log holds the output of the package installs and your runcmd commands; /var/log/cloud-init.log is cloud-init's own detailed log:

Bash
sudo tail -n 20 /var/log/cloud-init-output.log
sudo grep -nE 'WARNING|ERROR' /var/log/cloud-init.log

Ask cloud-init what it knows about this server, check the file it wrote, and validate the user data the server actually received:

Bash
cloud-init query v1.local_hostname
cloud-init query --format 'Running on {{ v1.cloud_name }}'
sudo cat /srv/app/app.conf
sudo cloud-init schema --system
sudo ufw status

From your own machine, in a second terminal, confirm that root is refused:

Bash
ssh root@<server-ip>

Finally, back on the server, see whether the upgrade needs a reboot:

Bash
if [ -f /var/run/reboot-required ]; then sudo reboot; else echo "no reboot needed"; fi

cloud-init will not run runcmd again after that reboot, or any later one. To try a changed file, create a new server with it rather than editing this one. On a throwaway server only, sudo cloud-init clean --logs --reboot wipes cloud-init's record and makes it run as if on first boot; it re-creates users and rewrites files, so never run it on a server you care about.

When you are finished, delete the server so it stops billing: aws ec2 terminate-instances --instance-ids <instance-id>, hcloud server delete web-1, or doctl compute droplet delete web-1, or the delete button in the provider's console. On your own machine, remove the demo folder once you have copied user-data.yaml somewhere you keep:

Bash
rm -rf ~/cloud-init-demo

Check it worked

After the dots that --wait prints, the first line of cloud-init status reads status: done, and further down errors: [] and recoverable_errors: {} show nothing went wrong. If extended_status reads degraded done, the run finished but logged warnings worth reading. The last line of the output log reads something like First boot finished after 74.31 seconds. The grep for warnings and errors ideally prints nothing; some clouds log harmless WARNING lines on a clean boot, so read any line it does print, especially ones that name a module from your file (users, write_files, runcmd). cloud-init query v1.local_hostname prints the server's hostname, and app.conf shows the same name next to host =. cloud-init schema --system reports the user data as valid, ufw status shows Status: active with OpenSSH ALLOW Anywhere, and the ssh root@ attempt fails with Permission denied (publickey).

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.