12

Is it possible to change the host name before the first boot? I've tried changing the name in /etc/hostname, but then the Pi doesn't boot properly. Is there something else that needs to be done?

This is intended for a Raspberry Pi running Raspbian/Raspberry Pi OS (lite) that is headless and connected by Ethernet. I'd like to be able to connect to the Raspberry Pi using ssh. (I have verified that if I don't change the host name I am able connect with ssh.)

jtpalmer
  • 138
  • 1
  • 7
  • "then the Pi doesn't boot properly." -> This shouldn't happen, methinks, but oh well. Have a look at man 5 hostname and the suggestion about using systemd-firstboot (then read man systemd-firstboot); the idea is that you mount the root filesystem somewhere (with systemd available) and use that to tweak the image without having to run the system in it. If it works out, please leave an answer of your own! – goldilocks Aug 30 '20 at 16:43
  • 2
    You need to change /etc/hostname and /etc/hosts. – Dougie Aug 30 '20 at 17:37

4 Answers4

8

If someone is still looking in this thread, you are now able to change the hostname (among other initial settings) from the Pi Imager before writing your boot drive.

To enable Pi Imager advanced settings before writing; press ctrl + shift + X while the Pi Imager is open.

This will bring the advanced menu where you are able to set up Hostname, SSH, Overscan, WiFi, Password, timezone etc.

These features came with the release of Pi Imager v1.6: Pi Imager v1.6 news

MrWorldWide
  • 181
  • 1
  • 1
7

To translate the script from Milliways in his answer, change the name in /etc/hostname as you already have done and add or change the entry 127.0.1.1 raspberrypi in /etc/hosts to the new hostname.

Ingo
  • 42,107
  • 20
  • 85
  • 197
1

It is certainly possible on a Linux computer (which can be a Pi)

The following code fragment is from one of my scripts; depending on how you implement this paths etc would need to be set.

CURRENT_HOSTNAME=$(cat /etc/hostname)

if [ $NEW_HOSTNAME = $CURRENT_HOSTNAME ]; then echo "Name already set" else echo "Setting Name" $NEW_HOSTNAME echo $NEW_HOSTNAME > /etc/hostname sed -i "/127.0.1.1/s/$CURRENT_HOSTNAME/$NEW_HOSTNAME/" /etc/hosts fi

You are unlikely to find any existing code, but if I wanted to do this I would loop mount the image and edit it.

Milliways
  • 59,890
  • 31
  • 101
  • 209
0

I saw this answer on insidedarkweb and thought I'd post it here. I ended up not needing to configure raspberry pi nodes prior to boot since I am running a configuration script afterwards anwyas.

Use a soft symlink to configure the SD card (for command line, otherwise use the GUI from the answer above):

rpi ~$ sudo bash -c 'echo <desired hostname> /boot/hostname'
rpi ~$ sudo ln -s /boot/hostname /etc/hostname

rpi ~$ sudo bash -c 'echo '127.0.0.1 <desired hosname>' >> /boot/hostname' rpi ~$ sudo ln -s /boot/hosts /etc/hosts

gtree
  • 101