add flake app to reboot vms on servers

This commit is contained in:
Pim Kunis 2024-01-23 21:36:29 +01:00
parent d9bf4d3094
commit e57f80df82

View file

@ -36,6 +36,7 @@
let let
system = "x86_64-linux"; system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
lib = pkgs.lib;
pkgs-unstable = nixpkgs-unstable.legacyPackages.${system}; pkgs-unstable = nixpkgs-unstable.legacyPackages.${system};
machines = import ./nixos/machines; machines = import ./nixos/machines;
# TODO: Maybe use mergeAttrLists # TODO: Maybe use mergeAttrLists
@ -102,5 +103,56 @@
checks = builtins.mapAttrs checks = builtins.mapAttrs
(system: deployLib: deployLib.deployChecks self.deploy) (system: deployLib: deployLib.deployChecks self.deploy)
deploy-rs.lib; deploy-rs.lib;
apps.${system} =
let
hostNames = builtins.concatStringsSep " " (builtins.map (host: "\"${host.config.networking.fqdn}\"") (builtins.attrValues self.nixosConfigurations));
in
{
reboot-all-vms =
let
reboot-all-vms = pkgs.writeScriptBin "reboot-all-vms" ''
hostNames=(${hostNames})
for hostName in ''${hostNames[@]}; do
units=$(${pkgs.openssh}/bin/ssh root@$hostName systemctl list-units --all)
microvmUnits=$(${pkgs.coreutils}/bin/echo "$units" | ${pkgs.gnugrep}/bin/grep 'microvm@.*\.service' | ${pkgs.gawkInteractive}/bin/awk '{print $1}')
if [ -n "$microvmUnits" ]; then
for microvmUnit in "$microvmUnits"; do
${pkgs.coreutils}/bin/echo "Restarting $microvmUnit on $hostName"
${pkgs.openssh}/bin/ssh root@$hostName systemctl restart "$microvmUnit"
done
fi
done
'';
in
{
type = "app";
program = "${reboot-all-vms}/bin/reboot-all-vms";
};
reboot-vm =
let
reboot-vm = pkgs.writeScriptBin "reboot-vm" ''
if [ -z "$1" ]; then
${pkgs.coreutils}/bin/echo "Please provide a VM name!"
exit 1
fi
hostNames=(${hostNames})
unitName="microvm@$1.service"
for hostName in ''${hostNames[@]}; do
units=$(${pkgs.openssh}/bin/ssh root@$hostName systemctl list-units --all)
if [[ "''${units[@]}" =~ "$unitName" ]]; then
${pkgs.coreutils}/bin/echo "Restarting $unitName on $hostName"
${pkgs.openssh}/bin/ssh root@$hostName systemctl restart "$unitName"
fi
done
'';
in
{
type = "app";
program = "${reboot-vm}/bin/reboot-vm";
};
};
}; };
} }