I am setting up multiple Raspberry Pi's in one go, flashing the cards and customizing as much as I can in /boot before actually booting the RPI's for the first time. One thing I haven't figured out how to do is to assign a unique hostname via a /boot modification. Anyone have that solved?
2 Answers
I assume you can only read the fat32 boot partition when configuring the SD-Card in a card reader attached to another non Unix computer (MS Windows, Apple Mac) before booting it in the RasPi. The hostname is defined on the ext4 root partition in the file /etc/hostname
containing the name. On the running Raspberry Pi you can just create this file in the boot directory and have a symlink to it:
rpi ~$ sudo bash -c 'echo myhost > /boot/hostname'
rpi ~$ sudo ln -s /boot/hostname /etc/hostname
You also have to do the same with the /etc/hosts
file because it also contains the hostname.
Now you can set the hostname in the fat32 boot partition. You have to do it only one time for the image and then clone it for your work.
In the 'modern' Raspberry Pi Imager using the cog wheel in the first screen allows you to set some presets including the hostname but also wifi configuration, default user name, whether SSH is enabled or not, very useful!
If you select a new hostname, this will create a file on the 'bootfs' partition of your SD card after writing.
So if you do not want to use the Raspberry Pi Imager, you can also do this manually. Create a file called firstrun.sh
and add this, for changing the hostname to jackfruit.local
:
#!/bin/bash
set +e
CURRENT_HOSTNAME=`cat /etc/hostname | tr -d " \t\n\r"`
if [ -f /usr/lib/raspberrypi-sys-mods/imager_custom ]; then
/usr/lib/raspberrypi-sys-mods/imager_custom set_hostname jackfruit
else
echo jackfruit >/etc/hostname
sed -i "s/127.0.1.1.*$CURRENT_HOSTNAME/127.0.1.1\tjackfruit/g" /etc/hosts
fi
rm -f /boot/firstrun.sh
sed -i 's| systemd.run.*||g' /boot/cmdline.txt
exit 0
and modify cmdline.txt
to add systemd.run=/boot/firstrun.sh
, for my 'headless raspbian' it currently looks like the below:
console=serial0,115200 console=tty1 root=PARTUUID=544c6228-02 rootfstype=ext4 fsck.repair=yes rootwait quiet init=/usr/lib/raspberrypi-sys-mods/firstboot systemd.run=/boot/firstrun.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target%
/boot
? It is relatively easy to do it in the root partition's/etc