nix-config/modules/backup.nix

102 lines
2.8 KiB
Nix

{ config, lib, pkgs, ... }:
let
cfg = config.services.backup;
in
{
options.services.backup = {
enable = lib.mkEnableOption "backup" // {
default = config.services.postgresql.enable;
};
paths = lib.mkOption {
type = with lib.types; listOf str;
default = [];
description = "Extra paths to include in backup.";
};
exclude = lib.mkOption {
type = with lib.types; listOf str;
default = [];
description = "Extra paths to exclude in backup.";
};
};
config = {
services = {
postgresqlBackup = {
inherit (config.services.postgresql) enable;
backupAll = true;
compression = "zstd";
compressionLevel = 9;
pgdumpOptions = "--create --clean";
startAt = "*-*-* 04:00:00";
};
restic.backups =
let
commonOpts = {
extraBackupArgs = [
"--exclude-file=${pkgs.writeText "restic-exclude-file" (lib.concatMapStrings (x: x + "\n") cfg.exclude)}"
];
initialize = true;
passwordFile = config.sops.secrets."restic/password".path;
paths = cfg.paths
++ lib.optionals config.services.postgresql.enable [ "/var/backup/postgresql/" ];
pruneOpts = [
"--group-by host"
"--keep-daily 7"
"--keep-weekly 4"
"--keep-monthly 12"
];
timerConfig = {
OnCalendar = "*-*-* 04:30:00";
RandomizedDelaySec = "5m";
};
};
in
lib.mkIf cfg.enable {
server8 = commonOpts // {
repositoryFile = config.sops.secrets."restic/repository/server8".path;
};
offsite = commonOpts // {
repository = "sftp://offsite/${config.networking.hostName}";
};
};
};
sops.secrets = lib.mkIf cfg.enable {
"restic/offsite/private" = {
mode = "400";
owner = "root";
path = "/root/.ssh/id_offsite-backup";
sopsFile = ./backup.yaml;
};
"restic/offsite/public" = {
mode = "400";
owner = "root";
path = "/root/.ssh/id_offsite-backup.pub";
sopsFile = ./backup.yaml;
};
"restic/offsite/ssh-config" = {
mode = "400";
owner = "root";
path = "/root/.ssh/config";
sopsFile = ./backup.yaml;
};
};
system.activationScripts.linkResticSSHConfigIntoVirtioFS = lib.mkIf cfg.enable ''
echo "Linking restic ssh config..."
mkdir -m700 -p /home/root/.ssh/
ln -fs {,/home}/root/.ssh/id_offsite-backup
ln -fs {,/home}/root/.ssh/id_offsite-backup.pub
ln -fs {,/home}/root/.ssh/config
'';
systemd.timers = lib.mkIf config.services.postgresqlBackup.enable {
postgresqlBackup.timerConfig.RandomizedDelaySec = "5m";
};
};
}