infra/tasks.py

252 lines
6.8 KiB
Python
Raw Normal View History

2021-10-21 11:09:52 +02:00
#!/usr/bin/env python3
2021-10-24 01:04:22 +02:00
import json
2023-01-16 09:37:38 +10:00
import os
2022-12-31 07:24:17 +01:00
import subprocess
import sys
2023-03-12 15:02:16 +10:00
from pathlib import Path
2023-05-13 21:32:00 +10:00
from tempfile import TemporaryDirectory
from typing import List
2022-12-31 07:24:17 +01:00
from deploykit import DeployGroup, DeployHost
from invoke import task
2021-10-21 11:09:52 +02:00
2023-03-12 15:02:16 +10:00
ROOT = Path(__file__).parent.resolve()
os.chdir(ROOT)
2021-10-21 11:09:52 +02:00
2023-03-17 13:36:07 +10:00
2023-03-12 15:02:16 +10:00
# Deploy to all hosts in parallel
2021-10-21 11:09:52 +02:00
def deploy_nixos(hosts: List[DeployHost]) -> None:
g = DeployGroup(hosts)
2022-01-15 13:38:30 +01:00
2021-10-21 11:09:52 +02:00
def deploy(h: DeployHost) -> None:
2023-07-17 09:37:43 +10:00
if "darwin" in h.host:
# don't use sudo for darwin-rebuild
command = "darwin-rebuild"
else:
command = "sudo nixos-rebuild"
res = h.run_local(
["nix", "flake", "archive", "--to", f"ssh://{h.host}", "--json"],
stdout=subprocess.PIPE,
)
data = json.loads(res.stdout)
path = data["path"]
2021-10-21 11:09:52 +02:00
hostname = h.host.replace(".nix-community.org", "")
h.run(
f"{command} switch --option accept-flake-config true --flake {path}#{hostname}"
)
2022-01-15 13:38:30 +01:00
2021-10-21 11:09:52 +02:00
g.run_function(deploy)
2022-10-25 09:55:14 +02:00
@task
def update_sops_files(c):
"""
Update all sops yaml and json files according to .sops.yaml rules
"""
c.run(
"""
find . \
-type f \
2022-11-17 08:57:22 +10:00
\( -iname '*.enc.json' -o -iname 'secrets.yaml' \) \
-exec sops updatekeys --yes {} \;
2022-10-25 09:55:14 +02:00
"""
)
2022-12-31 07:24:17 +01:00
2022-12-30 20:51:58 +01:00
@task
2023-05-13 21:32:00 +10:00
def print_keys(c, flake_attr: str) -> None:
2022-12-30 20:51:58 +01:00
"""
2023-05-13 21:32:00 +10:00
Decrypt host private key, print ssh and age public keys. Use inv print-keys --flake-attr build01
2022-12-30 20:51:58 +01:00
"""
2023-05-13 21:32:00 +10:00
with TemporaryDirectory() as tmpdir:
decrypt_host_key(flake_attr, tmpdir)
key = f"{tmpdir}/etc/ssh/ssh_host_ed25519_key"
pubkey = subprocess.run(
["ssh-keygen", "-y", "-f", f"{key}"],
stdout=subprocess.PIPE,
text=True,
check=True,
)
print("###### Public keys ######")
print(pubkey.stdout)
print("###### Age keys ######")
subprocess.run(
["ssh-to-age"],
input=pubkey.stdout,
check=True,
text=True,
)
2022-12-30 20:51:58 +01:00
2022-10-25 09:55:14 +02:00
2023-03-15 10:50:57 +10:00
@task
def update_terraform(c):
"""
Update terraform devshell flake
"""
2023-05-19 23:51:43 +10:00
c.run(
"""
2023-03-15 10:50:57 +10:00
system="$(nix eval --impure --raw --expr 'builtins.currentSystem')"
2023-05-19 23:51:43 +10:00
oldShell="$(nix build --no-link --print-out-paths ".#devShells.${system}.terraform")"
oldRev="$(nix flake metadata --json | jq -r '.locks.nodes."tf-pkgs".locked.rev')"
newRev="$(nix flake metadata --json | jq -r '.locks.nodes.nixpkgs.locked.rev')"
sed -i "s|${oldRev}|${newRev}|" flake.nix
nix flake lock --update-input tf-pkgs --commit-lock-file
newShell="$(nix build --no-link --print-out-paths ".#devShells.${system}.terraform")"
2023-03-15 10:50:57 +10:00
commit="$(git log --pretty=format:%B -1)"
2023-05-19 23:51:43 +10:00
diff="$(nix store diff-closures "${oldShell}" "${newShell}" | awk -F ',' '/terraform/ && /→/ {print $1}')"
git commit --all --amend -m "${commit}" -m "Terraform updates:" -m "${diff}"
2023-03-15 10:50:57 +10:00
"""
2023-05-19 23:51:43 +10:00
)
2023-03-15 10:50:57 +10:00
@task
def mkdocs(c):
"""
Serve docs (mkdoc serve)
"""
c.run("nix develop .#mkdocs -c mkdocs serve")
2021-10-24 01:04:22 +02:00
def get_hosts(hosts: str) -> List[DeployHost]:
2021-10-21 11:09:52 +02:00
if hosts == "":
2023-05-20 09:27:25 +10:00
res = subprocess.run(
["nix", "flake", "show", "--json", "--all-systems"],
check=True,
text=True,
stdout=subprocess.PIPE,
)
data = json.loads(res.stdout)
systems = data["nixosConfigurations"]
return [DeployHost(f"{n}.nix-community.org") for n in systems]
2021-10-21 11:09:52 +02:00
2023-07-17 09:37:43 +10:00
if "darwin" in hosts:
return [
2023-07-17 09:37:43 +10:00
DeployHost(f"{h}.nix-community.org", user="hetzner")
for h in hosts.split(",")
]
return [DeployHost(f"{h}.nix-community.org") for h in hosts.split(",")]
2021-10-21 11:09:52 +02:00
@task
2022-01-15 13:38:30 +01:00
def deploy(c, hosts=""):
2021-10-21 11:09:52 +02:00
"""
2023-01-07 07:37:07 +10:00
Deploy to all servers. Use inv deploy --hosts build01 to deploy to a single server
2021-10-21 11:09:52 +02:00
"""
deploy_nixos(get_hosts(hosts))
2023-05-13 21:32:00 +10:00
def decrypt_host_key(flake_attr, tmpdir):
def opener(path, flags):
return os.open(path, flags, 0o400)
t = Path(tmpdir)
t.mkdir(parents=True, exist_ok=True)
t.chmod(0o755)
host_key = t / "etc/ssh/ssh_host_ed25519_key"
host_key.parent.mkdir(parents=True, exist_ok=True)
with open(host_key, "w", opener=opener) as fh:
subprocess.run(
[
"sops",
"--extract",
'["ssh_host_ed25519_key"]',
"--decrypt",
2023-05-18 13:24:26 +10:00
f"{ROOT}/hosts/{flake_attr}/secrets.yaml",
2023-05-13 21:32:00 +10:00
],
check=True,
stdout=fh,
)
@task
2023-05-13 21:32:00 +10:00
def install(c, flake_attr: str, hostname: str) -> None:
"""
2023-05-13 21:32:00 +10:00
Decrypt host private key, install with nixos-anywhere. Use inv install --flake-attr build01 --hostname build01.nix-community.org
"""
2023-05-13 21:32:00 +10:00
ask = input(f"Install {hostname} with {flake_attr}? [y/N] ")
if ask != "y":
return
with TemporaryDirectory() as tmpdir:
decrypt_host_key(flake_attr, tmpdir)
flags = "--debug --no-reboot --option accept-flake-config true"
c.run(
f"nix run github:numtide/nixos-anywhere -- {hostname} --extra-files {tmpdir} --flake .#{flake_attr} {flags}",
echo=True,
)
@task
def build_local(c, hosts=""):
"""
2023-01-07 07:37:07 +10:00
Build all servers. Use inv build-local --hosts build01 to build a single server
"""
g = DeployGroup(get_hosts(hosts))
def build_local(h: DeployHost) -> None:
hostname = h.host.replace(".nix-community.org", "")
h.run_local(
[
"nixos-rebuild",
"build",
"--option",
"accept-flake-config",
"true",
"--flake",
f".#{hostname}",
]
)
g.run_function(build_local)
2021-10-21 11:09:52 +02:00
def wait_for_port(host: str, port: int, shutdown: bool = False) -> None:
2022-12-31 07:24:17 +01:00
import socket
import time
2021-10-21 11:09:52 +02:00
while True:
try:
with socket.create_connection((host, port), timeout=1):
if shutdown:
time.sleep(1)
sys.stdout.write(".")
sys.stdout.flush()
else:
break
2022-12-31 07:24:17 +01:00
except OSError:
2021-10-21 11:09:52 +02:00
if shutdown:
break
else:
time.sleep(0.01)
sys.stdout.write(".")
sys.stdout.flush()
@task
def reboot(c, hosts=""):
"""
Reboot hosts. example usage: inv reboot --hosts build01,build02
"""
2021-10-24 01:31:40 +02:00
for h in get_hosts(hosts):
h.run("sudo reboot &")
2021-10-21 11:09:52 +02:00
print(f"Wait for {h.host} to shutdown", end="")
sys.stdout.flush()
wait_for_port(h.host, h.port, shutdown=True)
print("")
print(f"Wait for {h.host} to start", end="")
sys.stdout.flush()
wait_for_port(h.host, h.port)
print("")
@task
def cleanup_gcroots(c, hosts=""):
g = DeployGroup(get_hosts(hosts))
g.run("sudo find /nix/var/nix/gcroots/auto -type s -delete")
g.run("sudo systemctl restart nix-gc")