Skip to content

Instantly share code, notes, and snippets.

Last active December 29, 2020 17:01
What would you like to do?
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
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