Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{ lib, pkgs, config, ... }:
let
cfg = config.services.nixos-rollback;
get-system-generation = pkgs.writeShellScriptBin "get-system-generation" ''
#!${pkgs.stdenv.shell}
set -euo pipefail
/var/run/current-system/sw/bin/nix-env --list-generations --profile /nix/var/nix/profiles/system | ${pkgs.gnugrep}/bin/grep current | ${pkgs.gawk}/bin/awk '{print $1}'
'';
stop-nixos-rollback = pkgs.writeShellScriptBin "stop-nixos-rollback" ''
#!${pkgs.stdenv.shell}
set -euo pipefail
ROLLBACK_FILE=${cfg.path}
CURRENT_GENERATION=$(${get-system-generation}/bin/get-system-generation)
echo Setting "$ROLLBACK_FILE" to "$CURRENT_GENERATION".
echo "$CURRENT_GENERATION" > "$ROLLBACK_FILE"
'';
in
{
options.services.nixos-rollback = {
enable = lib.mkEnableOption "nixos-rollback";
path = lib.mkOption {
type = lib.types.path;
default = "/nix/var/nix/rollback-generation";
description = "Path to the desired rollback generation";
};
};
config = lib.mkIf cfg.enable {
environment.systemPackages = [
get-system-generation
stop-nixos-rollback
];
systemd.services.nixos-rollback = {
path = [ get-system-generation stop-nixos-rollback ];
script = ''
if [ ! -f ${cfg.path} ]; then
echo Rollback file "${cfg.path}" does not exist.
stop-nixos-rollback
fi;
if [[ $(get-system-generation) > $(cat ${cfg.path}) ]]; then
/var/run/current-system/sw/bin/nixos-rebuild switch --rollback
fi;
'';
};
systemd.timers.nixos-rollback = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "15 min";
OnUnitInactiveSec = "15 min";
};
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.