Skip to content

Instantly share code, notes, and snippets.

@lheckemann
Created May 27, 2020 07:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lheckemann/d07efcbef2a2232b6dee2045a80c89aa to your computer and use it in GitHub Desktop.
Save lheckemann/d07efcbef2a2232b6dee2045a80c89aa to your computer and use it in GitHub Desktop.

Boot into temporary NixOS system from any systemd system with nix installed

This builds a NixOS system, copies it into a tmpfs, then instructs systemd to shut down the main system and switch into the new one (without replacing the kernel).

#!/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