Raspberry Pis are pretty useful for doing different "headless" things on the home network. Their first-time setup is quite manual and not very quick when you want to spin up a fresh image on an sd card to experiment with something. You have to attach a keyboard and answer the setup questions manually.
How can I automate getting an image up and running?
In the past, I had relied on inserting a systemd service with a script that can configure the Pi once it has booted, but that wasn't fully skipping the manual first-boot steps.
There is a neat unattended script framework called pi-boot-script which seems to aim to setup the RPi completely for runtime services. But I really just want the RPi up and running so I can access it from the network without having to attach a keyboard and do lots of manual data entry.
Turns out the RPi OS already has framework for first-run customisation in place. It seems to be used by the Imager product. And it's actually pretty straightforward and focuses on the key setup parts.
It works by creating a simple config
custom.toml file in the boot partition and when the
RPi goes through its first boot setup, it picks it up and applies the settings from that file
including things like hostname, the main user and enable SSH.
Which is all you need to get a headless RPi running on the network without having to attach a keyboard. From there you can access through ssh and deploy what you want in a more flexible way.
First-boot custom.toml Sample
# Raspberry Pi First Boot Setup
hostname = "rpihost"
name = "piuser"
password = "fill this out"
password_encrypted = false
enabled = true
authorized_keys = [ "ssh-rsa Abc....== user@hint" ]
# this seems to broken in RPi's "init_config" and it sets "-k" instead of "-p"
# password_authentication = true
country = "gb"
# ssid = ""
# password = ""
# password_encrypted = false
# hidden = false
keymap = "gb"
timezone = "Europe/London"
Few notes about the config file:
- System/User/SSH and Locale seem to be the minimum for getting an RPi to run
- Wlan obviously needed if it's not going to be connected to ethernet, otherwise optional
- password_authentication is currently broken and ignored. First boot config will always set up the RPi for Key-authentication, it's a small bug that will likely be fixed easily.
- password_encrypted should be set to
trueif you're providing the password hash, not a plaintext password
- authorized_keys is an array of authorized keys. Copy yours from ~/.ssh/id_rsa.pub file
once you're done setting up the file, mount your sd-card's boot partition and copy the file there
mkdir -v /mnt/rpi-boot
mount -v /dev/**sdb1** /mnt/rpi-boot
cp -v custom.toml /mnt/rpi-boot
umount /mnt/rpi-boot && rmdir /mnt/rpi-boot
that's it - insert your sd card into the RPi and give it a couple of minutes to expand the filesystem and set itself up, then you can ssh into it.