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
deployuser that can only log in with your SSH key and can usesudo - refuse SSH logins as root and with passwords
- update the package lists, upgrade what is installed, and add
ufw,unattended-upgradesandjq - write a config file owned by
deployand 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:
sudo apt update
sudo apt install -y cloud-init
cloud-init --version
mkdir -p ~/cloud-init-demo
cd ~/cloud-init-demoInstalling 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:
ls -l ~/.ssh/id_ed25519.pubIf 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:
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
YAMLWhat each part does:
lock_passwd: truemeansdeployhas 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 normalsudowould ask for one and the user could never type it, sosudois 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. Becauseusers:does not includedefault, that user is not created anddeployis 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'sauthorized_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: falseturns 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:
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.jsonOn 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:
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.jsonpackage_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:
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.jsonThree 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_rootonly turns a root key login into a message and a closed session;PermitRootLogin nomakes SSH refuse root before any session starts. defer: trueon the app config. cloud-init writes files early in boot, before it creates users. Withoutdefer, the ownerdeploy:deploywould 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:
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.jsonEach 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:
- Detect: works out which cloud it is running on.
- Local: reads local data and sets up the network configuration.
- Network: with the network up, fetches your user data, writes the non-deferred files and creates users and SSH keys.
- Config: runs configuration modules.
runcmdis saved as a script here but does not run yet. - Final: installs packages, writes deferred files, then runs your
runcmdscript, soufwis 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:
cat > broken.yaml <<'YAML'
#cloud-config
package_update: true
runcmd: ufw enable
YAML
cloud-init schema --config-file broken.yamlCheck 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:
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.yamlRead 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:
if grep -n CI_MISSING_JINJA_VAR rendered.yaml; then echo "fix the variables listed above"; else echo "no missing variables"; fiCheck 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):
# 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.yamlMake 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:
ssh deploy@<server-ip>On the server, wait for cloud-init to finish and see its result:
cloud-init status --wait --longThen 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:
sudo tail -n 20 /var/log/cloud-init-output.log
sudo grep -nE 'WARNING|ERROR' /var/log/cloud-init.logAsk cloud-init what it knows about this server, check the file it wrote, and validate the user data the server actually received:
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 statusFrom your own machine, in a second terminal, confirm that root is refused:
ssh root@<server-ip>Finally, back on the server, see whether the upgrade needs a reboot:
if [ -f /var/run/reboot-required ]; then sudo reboot; else echo "no reboot needed"; ficloud-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:
rm -rf ~/cloud-init-demoCheck 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
- Launch a server from code with the same kind of file, filled in by OpenTofu: launch the Relay web server with OpenTofu and cloud-init.
- Go further on the SSH side of this file: harden SSH on Ubuntu 26.04.
- Learn the firewall rules beyond SSH: set up a UFW firewall on Ubuntu 26.04.
Related tutorials
- Write your first Pulumi program in TypeScriptYou will install the Pulumi CLI, keep state in a local folder, declare resources in a TypeScript program, preview and apply it, read its outputs, change it and watch the diff, then destroy and remove the stack.
- Use Terraform workspaces for separate environments, and know when not toYou will run one Terraform configuration as separate dev and staging workspaces with per-environment settings, find where each workspace keeps its state, guard every apply with a workspace check, and compare the result with a directory per environment.
- Test Ansible roles with ansible-lint and MoleculeYou will clean up a role until ansible-lint passes its production profile, then add a Molecule scenario that applies the role, proves a second run changes nothing and checks the result with a verify playbook.
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