clan-core/pkgs/clan-cli/clan_cli/facts/upload.py

59 lines
1.7 KiB
Python
Raw Normal View History

2023-09-14 11:49:20 +00:00
import argparse
import importlib
2023-10-03 10:50:47 +00:00
import logging
from pathlib import Path
from tempfile import TemporaryDirectory
2023-09-14 11:49:20 +00:00
2024-01-12 16:01:46 +00:00
from ..cmd import Log, run
from ..completions import add_dynamic_completer, complete_machines
from ..machines.machines import Machine
from ..nix import nix_shell
2023-09-14 11:49:20 +00:00
2023-10-03 10:50:47 +00:00
log = logging.getLogger(__name__)
2023-09-14 11:49:20 +00:00
def upload_secrets(machine: Machine) -> None:
secret_facts_module = importlib.import_module(machine.secret_facts_module)
secret_facts_store = secret_facts_module.SecretStore(machine=machine)
if secret_facts_store.update_check():
log.info("Secrets already up to date")
return
with TemporaryDirectory() as tempdir:
secret_facts_store.upload(Path(tempdir))
host = machine.target_host
ssh_cmd = host.ssh_cmd()
run(
nix_shell(
["nixpkgs#rsync"],
[
"rsync",
"-e",
" ".join(["ssh"] + ssh_cmd[2:]),
"-az",
"--delete",
"--chown=root:root",
"--chmod=D700,F600",
f"{tempdir!s}/",
f"{host.user}@{host.host}:{machine.secrets_upload_directory}/",
],
),
log=Log.BOTH,
)
2023-09-14 11:49:20 +00:00
def upload_command(args: argparse.Namespace) -> None:
machine = Machine(name=args.machine, flake=args.flake)
upload_secrets(machine)
2023-09-14 11:49:20 +00:00
def register_upload_parser(parser: argparse.ArgumentParser) -> None:
machines_parser = parser.add_argument(
2023-09-14 11:49:20 +00:00
"machine",
help="The machine to upload secrets to",
)
add_dynamic_completer(machines_parser, complete_machines)
2023-09-14 11:49:20 +00:00
parser.set_defaults(func=upload_command)