aboutsummaryrefslogtreecommitdiff
path: root/infra/deploy.nix
blob: c8280083be738b97ff3f75e13cea02c12a08c9b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
{
  perSystem =
    { lib, pkgs, ... }:
    {
      apps.infra-deploy =
        let
          hosts = builtins.attrNames (
            lib.attrsets.filterAttrs (_: type: type == "directory") (builtins.readDir ./hosts)
          );

          bin = pkgs.writeShellApplication {
            name = "deploy";
            runtimeInputs = [
              # keep-sorted start
              pkgs.fzf
              pkgs.git
              pkgs.inetutils
              pkgs.nixos-rebuild
              # keep-sorted end
            ];
            text = ''
              selected=("$@")

              if [ "''${#selected[@]}" -eq 0 ]; then
                readarray -t selected < <(printf '%s\n' ${lib.escapeShellArgs hosts} | fzf --multi)
              fi

              if [ "''${#selected[@]}" -eq 0 ]; then
                echo "error: no host selected" >&2
                exit 1
              fi

              if [ "''${#selected[@]}" -eq 1 ] && [ "''${selected[0]}" = "all" ]; then
                selected=(${lib.escapeShellArgs hosts})
              fi

              rootdir="$(git rev-parse --show-toplevel)"

              for host in "''${selected[@]}"; do
                target=()
                if [ "$host" != "$(hostname)" ]; then
                  target=(--target-host "deploy@$host")
                fi

                echo "info: deploying $host"
                nixos-rebuild switch \
                  --no-reexec \
                  --use-substitutes \
                  --sudo \
                  --flake "$rootdir#$host" \
                  "''${target[@]}"
              done
            '';
          };
        in
        {
          type = "app";
          program = "${bin}/bin/deploy";
          meta.description = "deploy the nixos configurations to the given hosts";
        };
    };
}