#!/usr/bin/env python3 """Create/refresh the cloud-fallback Secret in a cluster, out of band. The credential is read from this process's environment and handed to kubectl on stdin. It is never placed in a command line, an argument, a URL, a log line, or a shell variable, and it is never written to the GitOps repo. python3 scripts/apply_cloud_secret.py ~/.kube/rocinante-admin.yaml """ from __future__ import annotations import base64 import json import os import subprocess import sys NAMESPACE = "forgeway" SECRET = "forgeway-cloud" def main() -> int: if len(sys.argv) != 2: return print(__doc__) or 2 kubeconfig = os.path.expanduser(sys.argv[1]) key = os.environ.get("OPENAI_API_KEY", "") if not key: print("OPENAI_API_KEY is not present in this environment", file=sys.stderr) return 1 env = {**os.environ, "KUBECONFIG": kubeconfig} subprocess.run( ["kubectl", "create", "namespace", NAMESPACE, "--dry-run=client", "-o", "json"], env=env, check=True, capture_output=True, ) ns = subprocess.run( ["kubectl", "get", "namespace", NAMESPACE], env=env, capture_output=True, ) if ns.returncode != 0: subprocess.run(["kubectl", "create", "namespace", NAMESPACE], env=env, check=True) manifest = { "apiVersion": "v1", "kind": "Secret", "metadata": { "name": SECRET, "namespace": NAMESPACE, "annotations": { # Argo does not manage this object; it is applied out of band so # the credential never reaches the repo. "argocd.argoproj.io/sync-options": "Prune=false", }, }, "type": "Opaque", "data": {"OPENAI_API_KEY": base64.b64encode(key.encode()).decode()}, } proc = subprocess.run( ["kubectl", "apply", "-f", "-"], env=env, input=json.dumps(manifest).encode(), capture_output=True, ) sys.stdout.write(proc.stdout.decode()) sys.stderr.write(proc.stderr.decode()) if proc.returncode == 0: print(f"ok: {NAMESPACE}/{SECRET} applied (value not shown)") return proc.returncode if __name__ == "__main__": raise SystemExit(main())