Skip to content

Instantly share code, notes, and snippets.

@gallexme
Forked from lheckemann/0-nixos-tmpfs.md
Last active July 11, 2023 12:26
Show Gist options
  • Save gallexme/77508a68d87d3c27117bb5920843c9de to your computer and use it in GitHub Desktop.
Save gallexme/77508a68d87d3c27117bb5920843c9de 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 '{ pkgs, modulesPath, lib, ... }: {
imports = [
"${modulesPath}/installer/cd-dvd/installation-cd-graphical-calamares-gnome.nix"
];
# use the latest Linux kernel
boot.kernelPackages = pkgs.linuxPackages_latest;
fileSystems."/" = {
device = "none";
fsType = "tmpfs";
};
boot.loader.grub.enable = false;
# Needed for https://github.com/NixOS/nixpkgs/issues/58959
boot.supportedFilesystems = lib.mkForce [ "btrfs" "reiserfs" "vfat" "f2fs" "xfs" "ntfs" "cifs" ];
} ' -A config.system.build.toplevel)
nix copy $system --to /tmp/new-root-tmpfs --no-require-sigs --extra-experimental-features nix-command
ln -s $system /tmp/new-root-tmpfs/system
mkdir -p /tmp/new-root-tmpfs/etc
[[ $(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