Skip to content

Instantly share code, notes, and snippets.

@lheckemann
Last active July 11, 2023 11:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lheckemann/d9224a10ba0e0bf528dadede41e5763d to your computer and use it in GitHub Desktop.
Save lheckemann/d9224a10ba0e0bf528dadede41e5763d to your computer and use it in GitHub Desktop.
NixOS: switch-root to tmpfs

Build a NixOS config, copy it to a tmpfs, and enter it, shutting the running userspace (but not the kernel) down. This can be useful e.g. for repartitioning the system or switching it to a new zfs pool, without the need for extra installation media, and is a little faster than most other volatile system methods (e.g. kexec, classic USB or CD installer), since the store is in RAM and uncompressed right from the get-go. It also copies the SSH host keys from the building system to maintain the chain of trust in a remote system.

#!/usr/bin/env bash
set -exuo pipefail
mkdir -p /tmp/new-root-tmpfs
findmnt /tmp/new-root-tmpfs || mount -t tmpfs tmpfs /tmp/new-root-tmpfs
system=$(nix-build '<nixpkgs/nixos>' --arg configuration '{lib, ...}:
let ifExists = p: lib.optional (lib.pathExists p) p; in {
boot.supportedFilesystems = ["zfs"];
services.openssh.enable = true;
networking.hostId = "23234242";
networking.hostName = "nixos-tmpfs";
networking.wireless.enable = true;
networking.wireless.networks.ssid.psk = "password";
fileSystems."/" = {
device = "none";
fsType = "tmpfs";
};
boot.loader.grub.enable = false;
users.users.root.openssh.authorizedKeys.keyFiles =
ifExists /etc/ssh/authorized_keys.d/root
++ ifExists /root/.ssh/authorized_keys;
}' -A config.system.build.toplevel)
nix copy $system --to /tmp/new-root-tmpfs --no-require-sigs
ln -s $system /tmp/new-root-tmpfs/system
mkdir -p /tmp/new-root-tmpfs/etc
rsync /etc/ssh/*host* /tmp/new-root-tmpfs/etc/ssh/
[[ $(read -p "Switch into the tmpfs system? ") = y ]] && systemctl switch-root /tmp/new-root-tmpfs /system/init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment