aboutsummaryrefslogtreecommitdiff
path: root/nixos/profiles/server/detect-hostname-change.nix
blob: c745493ecef36b0b404b95f9d35f1b90e8f8cd19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
    '';
  };
}