archive2022

My checklist for a new headless Raspberry Pi

The steps every new Pi gets: a user and SSH set up before the first boot, key-only logins, a service user, one venv per project, a systemd unit for the Python script, and a size limit for the journal.

All my Pis run without a screen, and each one does one job: read sensors, run the MQTT broker, or record a camera. The setup steps are the same every time, so I keep them in one list. The Raspberry Pi OS release of 4 April 2022 removed the default pi user, which changed the first steps, so I rewrote the list this week.

Before the first boot

There is no pi / raspberry login anymore. You create the user before the first boot (Raspberry Pi announcement).

The simple way is Raspberry Pi Imager. In its advanced options (the gear icon, or Ctrl+Shift+X) set the hostname, the user name and password, SSH, and Wi-Fi if the Pi has no cable. Imager writes all of it to the card.

With another flashing tool, two files on the boot partition do the same job. userconf.txt holds one line, username:encrypted-password, and an empty file called ssh turns on the SSH server:

echo "admin:$(echo 'a-long-password' | openssl passwd -6 -stdin)" > /media/$USER/boot/userconf.txt
touch /media/$USER/boot/ssh

Pick a user name other than pi. Scanners on the internet try pi first.

SSH with keys only

From the laptop, copy the public key and check that key login works:

ssh-copy-id admin@sensorpi.local
ssh admin@sensorpi.local

Then turn off password logins in /etc/ssh/sshd_config:

PasswordAuthentication no
PermitRootLogin no

Run sudo systemctl reload ssh, and keep this session open while you test a new login from a second terminal. If something is wrong, the open session lets you fix it.

Then bring the system up to date:

sudo apt update && sudo apt full-upgrade

Port 22 is never forwarded from the router to a Pi. From outside I connect through WireGuard.

A user for services

Programs that run all the time get their own system user, not my login user:

sudo useradd --system --create-home --home-dir /opt/sensor sensor
sudo usermod -aG gpio,i2c sensor

The groups give access to the GPIO pins and the I2C bus, so the service does not need root. Add dialout for a serial port and video for the camera.

Old scripts often assume the pi user. When I moved projects to a new card, this search found it in systemd units, cron jobs, backup scripts and an Ansible inventory:

grep -rn -E '/home/pi|User=pi|\bpi@' .

Systems that already run keep their pi user after the update. The release also ships a rename-user tool for them. I did not need it, because I move each Pi to a fresh card anyway.

One virtual environment per project

sudo pip3 install is fine for one project. With a few projects it breaks: two of them need different versions of a library, or pip replaces a file that apt installed. So each project gets its own venv, owned by the service user:

sudo apt install -y python3-venv
sudo -u sensor mkdir -p /opt/sensor/logger
cd /opt/sensor/logger
sudo -u sensor python3 -m venv .venv
sudo -u sensor .venv/bin/pip install -r requirements.txt

Nothing gets activated. Scripts, cron jobs and units call the venv’s Python by its full path.

On the 32-bit OS, pip already uses piwheels (see /etc/pip.conf). It has pre-built wheels for the Pi, so numpy and similar packages do not compile for an hour. piwheels builds for the Python that comes with the OS, 3.9 on Bullseye, so a self-built Python does not get these wheels. On the 64-bit OS, pip uses the aarch64 wheels from PyPI, and most big packages have them.

Some wheels need a shared library from apt. An ImportError that names a .so file usually means one is missing, and the package page on piwheels lists what to install. For numpy it is often:

sudo apt install -y libatlas-base-dev

Hardware libraries that come with the OS, such as python3-gpiozero, I install with apt. A venv created with python3 -m venv --system-site-packages .venv can import them.

The script as a systemd service

/etc/systemd/system/sensor-logger.service:

[Unit]
Description=Sensor logger (MQTT)
Wants=network-online.target
After=network-online.target

[Service]
User=sensor
WorkingDirectory=/opt/sensor/logger
ExecStart=/opt/sensor/logger/.venv/bin/python -u main.py
EnvironmentFile=/etc/sensor-logger.env
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
sudo chmod 600 /etc/sensor-logger.env
sudo systemctl daemon-reload
sudo systemctl enable --now sensor-logger
journalctl -u sensor-logger -f

What each part is for:

  • -u turns off Python’s output buffering. Without it, print() lines reach the journal late and in big blocks, and the script looks stuck.
  • EnvironmentFile keeps the MQTT password out of the unit file and out of the code. Only root can read it.
  • RestartSec=5 stops a broken script from restarting in a tight loop.
  • Restart=on-failure does nothing when the script exits with code 0. A script that catches an error and exits normally stays dead. Exit with a non-zero code on errors, or use Restart=always.
  • network-online.target does not mean that Wi-Fi works yet. The script still has to retry its connection.

Many guides start scripts from /etc/rc.local or a @reboot cron line instead. That gives no restart after a crash and no easy way to read the logs. For a job that runs every few minutes and exits, cron is still fine.

The two mistakes I make most: editing the unit and forgetting sudo systemctl daemon-reload, and writing ~ in a path. systemd does not expand ~.

Keep the journal small

A Pi that runs for months can collect a journal of several hundred megabytes, and it writes to the SD card all the time. A drop-in file sets a limit:

sudo mkdir -p /etc/systemd/journald.conf.d
sudo tee /etc/systemd/journald.conf.d/size.conf <<'CONF'
[Journal]
SystemMaxUse=100M
SystemMaxFileSize=20M
MaxRetentionSec=1month
CONF
sudo systemctl restart systemd-journald

That is for the server Pi, where I want logs from before a crash. Sensor nodes keep the journal in RAM only, because their data goes out over MQTT anyway:

[Journal]
Storage=volatile
RuntimeMaxUse=30M

Raspberry Pi OS also runs rsyslog, which writes the same messages again to /var/log/syslog. If you only read the journal, sudo systemctl disable --now rsyslog stops the double writes. Often one noisy program causes most of the writes, and this finds it:

journalctl --since today | awk '{print $5}' | sed 's/\[.*//' | sort | uniq -c | sort -rn | head

Fixing that one program helps more than any journald setting.