common.nix/modules/nixos-upgrade.nix

75 lines
2 KiB
Nix
Raw Permalink Normal View History

2024-05-23 20:08:11 +03:00
{ config
, lib
, pkgs
, ...
}:
let
2024-03-29 22:36:02 +02:00
cfg = config.system.autoUpgrade;
updateScript = pkgs.writeShellApplication {
name = "update";
2024-05-23 20:08:11 +03:00
runtimeInputs = with pkgs; [ git nix ];
2024-03-29 22:36:02 +02:00
text = ''
cd ${cfg.flake}
git pull
nix flake update --commit-lock-file
2024-08-27 19:14:46 +03:00
${lib.optionalString (cfg.extraCommands != null) "${cfg.extraCommands}"}
2024-03-29 22:36:02 +02:00
git push
'';
};
2024-05-23 20:08:11 +03:00
in
{
2024-03-29 22:36:02 +02:00
options.system.autoUpgrade = {
# TODO: make sure system.autoUpgrade.flake is a local folder
2024-03-29 22:36:02 +02:00
updateFlake = lib.mkOption {
default = false;
description = "Update lockfile of the flake.";
example = true;
};
extraCommands = lib.mkOption {
type = lib.types.nullOr lib.types.str;
2024-08-27 19:14:46 +03:00
default = null;
description = "Extra commands to run during upgrade";
2024-03-29 22:36:02 +02:00
};
failureNotification = {
enable = lib.mkOption {
default = false;
description = "Enable ntfy notification on upgrade failure.";
example = true;
2024-03-29 22:36:02 +02:00
};
ntfyUrlFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
description = "Environment file containing NTFY_URL";
example = "/etc/secrets/failureNotification.env";
2024-03-29 22:36:02 +02:00
};
};
};
config.systemd.services = lib.mkIf cfg.enable {
nixos-upgrade.serviceConfig.ExecStartPre =
lib.mkIf cfg.updateFlake
2024-05-23 20:08:11 +03:00
(lib.getExe updateScript);
2024-03-29 22:36:02 +02:00
2024-03-30 20:39:30 +02:00
nixos-upgrade-failure = lib.mkIf cfg.failureNotification.enable {
2024-05-23 20:08:11 +03:00
path = with pkgs; [ "/run/wrappers" "/run/current-system/sw" curl ];
2024-03-29 22:36:02 +02:00
script = ''
journalctl _SYSTEMD_INVOCATION_ID=`systemctl show --value -p InvocationID nixos-upgrade.service` > /tmp/upgrade-failure.txt
curl -T /tmp/upgrade-failure.txt -H "Filename: failure-logs.txt" -H "Title: Nixos auto upgrade failed for $(hostname)" $NTFY_URL
rm /tmp/upgrade-failure.txt
'';
serviceConfig = {
User = "root";
EnvironmentFile = cfg.failureNotification.ntfyUrlFile;
};
};
2024-05-23 20:08:11 +03:00
nixos-upgrade.onFailure = lib.mkIf cfg.failureNotification.enable [ "nixos-upgrade-failure.service" ];
2024-03-29 22:36:02 +02:00
};
}