nix-configs/secrets/deploy-secrets.py
2025-07-23 14:24:23 +02:00

51 lines
1.7 KiB
Python

#!/usr/bin/env python
import subprocess
import sys
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("flake")
parser.add_argument("-f", "--force", action='store_true')
args = parser.parse_args()
NIX_OUTPUT_JSON_PATH = subprocess.run(["nix", "build", f"{args.flake}.config.xyno.secret-output", "--no-link")
HOSTNAME = subprocess.run(["nix", "eval", f"{args.flake}.config.networking.hostName", "--raw"])
nix_output_json
with open(NIX_OUTPUT_JSON_PATH, "r") as f:
nix_output_json = json.load(f)
def run_ssh(command):
return subprocess.run("ssh", HOSTNAME, command)
def check_tpm():
return run_ssh("systemd-analyze has-tpm2").returncode == 0
def push_secret(secret_name, secret_content):
if !args.force && secret_name in run_ssh("systemd-creds list"):
print(f"[INFO] secret {secret_name} exists on target, skipping")
print(f"[INFO] run with --force to skip")
return
command
if secret_content["random"] != null:
command = f"openssl rand -hex {secret_content["random"]} | systemd-creds encrypt - {secret_name}"
else if secret_content["ageFile"] != null:
secret_output = subprocess.run(["rage", "-d", secret_content["ageFile"]])
command = f"echo '{secret_output}' | systemd-creds encrypt - {secret_name}"
else if secret_content["command"] != null:
secret_output = subprocess.run(["sh", "-c", secret_content["command"]])
command = f"echo '{secret_output}' | systemd-creds encrypt - {secret_name}"
else:
print(f"[ERROR] no secret content set for {secret_name}: {secret_content}")
return
run_ssh(command)
for secret_name, secret_content in nix_output_json:
push_secret(secret_name,secret_content)