Skip to content

Instantly share code, notes, and snippets.

@gdamjan
Last active February 16, 2023 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdamjan/7f5b31e2a4e1666da57372c9f684f341 to your computer and use it in GitHub Desktop.
Save gdamjan/7f5b31e2a4e1666da57372c9f684f341 to your computer and use it in GitHub Desktop.
kernel postinstall script to update systemd-boot on debian/ubuntu
#!/bin/bash
#
# /etc/kernel/postinst.d/zz-update-systemd-boot
# 0755 root:root
#
# This is a simple kernel hook to populate the systemd-boot entries
# whenever kernels are added or removed.
#
set -euo pipefail
ESP=/boot/efi # bootctl --print-esp-path
MACHINE=/ubuntu # FIXME: use the machine-id ?
ESP_MACHINE=${ESP}${MACHINE}
ESP_LOADER_ENTRIES=$ESP/loader/entries
CMDLINE=`< /etc/kernel/cmdline`
# List of kernels
KERNELS=()
FIND="find /boot -maxdepth 1 -name 'vmlinuz-*' -type f -print0 | sort -rz"
while IFS= read -r -u3 -d $'\0' LINE; do
KERNEL=$(basename "${LINE}")
KERNELS+=("${KERNEL:8}")
done 3< <(eval "${FIND}")
# There has to be at least one kernel.
if [ ${#KERNELS[@]} -lt 1 ]; then
echo -e "\e[2msystemd-boot\e[0m \e[1;31mNo kernels found.\e[0m"
exit 1
fi
mkdir -p $ESP_MACHINE
# Copy the latest kernel files to a consistent place so we can keep
# using the same loader configuration.
LATEST="${KERNELS[@]:0:1}"
echo -e "\e[2msystemd-boot\e[0m \e[1;32m${LATEST}\e[0m"
for FILE in initrd.img vmlinuz; do
cp "/boot/${FILE}-${LATEST}" "$ESP_MACHINE/${FILE}"
cat <<- EOF > $ESP_LOADER_ENTRIES/ubuntu.conf
title Ubuntu ${LATEST}
linux $MACHINE/vmlinuz
initrd $MACHINE/initrd.img
options $CMDLINE
EOF
done
# Success!
exit 0
@gdamjan
Copy link
Author

gdamjan commented Feb 16, 2023

Tested on Ubuntu 22.04 on a Scaleway instance. To migrate from Grub to systemd-boot I did this:

  1. shutdown instance
  2. make a snapshot image
  3. power-on
  4. apt purge grub* && apt autoremove --purge
  5. bootctl install
  6. create /etc/kernel/cmdline - just a plain file, mostly a copy paste from /proc/cmdline except any initrd= or BOOT= or similar. mine is just root=PARTUUID=c1789075-d188-466c-b2a8-af2a999514f9 ro console=tty1 console=ttyS0 panic=-1
  7. create /etc/kernel/postinst.d/zz-update-systemd-boot (see above, root:root, chmod 0755)
  8. run it: /etc/kernel/postinst.d/zz-update-systemd-boot
  9. reboot
  10. if all is good that's it
    • if all is not good, restore from the snapshot that you took at 2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment