From bc50c5d3c209e5b365755f76d1cf188b665ecd60 Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Wed, 30 Sep 2026 12:53:10 +0200 Subject: tweak(server): add hostname change preSwitchCheck --- nixos/profiles/server/default.nix | 1 + nixos/profiles/server/detect-hostname-change.nix | 50 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 nixos/profiles/server/detect-hostname-change.nix (limited to 'nixos') diff --git a/nixos/profiles/server/default.nix b/nixos/profiles/server/default.nix index 07dcd4b..6e744a6 100644 --- a/nixos/profiles/server/default.nix +++ b/nixos/profiles/server/default.nix @@ -3,6 +3,7 @@ { imports = [ ../common + ./detect-hostname-change.nix ]; services = { diff --git a/nixos/profiles/server/detect-hostname-change.nix b/nixos/profiles/server/detect-hostname-change.nix new file mode 100644 index 0000000..c745493 --- /dev/null +++ b/nixos/profiles/server/detect-hostname-change.nix @@ -0,0 +1,50 @@ +# Protection against deploying system closures to the wrong host. +# (copied from https://github.com/nix-community/srvos) +{ + config, + lib, + ... +}: +{ + config = lib.mkIf (config.networking.hostName != "") { + system.preSwitchChecks.detectHostnameChange = '' + detectHostnameChange() { + local actual + actual="$(< /proc/sys/kernel/hostname)" + + # Ignore if the system is getting installed + # https://github.com/nix-community/nixos-images/blob/2fc023e024c0a5e8e98ae94363dbf2962da10886/nix/installer.nix#L12-L13 + if [[ ! -e /run/booted-system || "$actual" == "nixos-installer" ]]; then + return + fi + + desired="${config.networking.hostName}" + + if [[ "$actual" = "$desired" ]]; then + return + fi + + # Useful for automation + if [[ "''${EXPECTED_HOSTNAME:-}" = "$desired" ]]; then + return + fi + + log() { + echo "$*" >&2 + } + + log "WARNING: machine hostname change detected from '$actual' to '$desired'" + log + log "Are you deploying on the right host?" + log + log "Type YES to continue:" + read -r reply + if [[ $reply != YES ]]; then + echo "aborting" + exit 1 + fi + } + detectHostnameChange + ''; + }; +} -- cgit v1.3.1