#!/usr/bin/env python3 """Fill Kyndryl CI's placeholders in each component's kubernetes/ folder, for a kustomize deploy by hand. The folders keep the placeholders, so they stay what the agent CI expects (and what check_agents.py checks). This writes a filled-in copy per component to build///, ready for `kubectl apply -k`: / the folder name /: (agent.yaml version, or the MCP server's) the profile's port the profile's repo the MCP server's name Keys never land in a file. secretnames.yaml (an empty Secret) is left out of the build, so a deploy cannot wipe the Secret you created by hand, and an MCP server's inline MCP_REGISTRATION_API_KEY placeholder is removed, so the server reads the key from its -secrets Secret instead. namespace.yaml is left out too: the namespace is shared with other agents, so the build must neither relabel it nor let `kubectl delete -k` remove it. Create a missing namespace with `kubectl create namespace` first. Usage: python3 scripts/render_k8s.py deploy/crucible-kab-dev.yaml [component ...] Then: kubectl --context diff -k build// # what would change kubectl --context apply -k build// Needs PyYAML. """ from __future__ import annotations import argparse import re import shutil import sys from pathlib import Path import yaml ROOT = Path(__file__).resolve().parents[1] INLINE_KEY = "" def _agent_version(folder: Path) -> str: match = re.search(r'^version:\s*"?([^"\s#]+)', (folder / "agent.yaml").read_text(), re.M) if not match or match.group(1) == "DEV": raise SystemExit(f"{folder.name}: set a released version in agent.yaml before deploying (found DEV or none)") return match.group(1) def _mcp_version(name: str) -> str: definition = ROOT / "mcp-servers" / f"{name}.server.yaml" return str(yaml.safe_load(definition.read_text())["version"]) def _merge_config(path: Path, extra: dict) -> None: doc = yaml.safe_load(path.read_text()) doc.setdefault("data", {}).update({k: str(v) for k, v in (extra or {}).items()}) path.write_text(yaml.safe_dump(doc, sort_keys=False)) def _drop_inline_key(path: Path) -> None: doc = yaml.safe_load(path.read_text()) for container in doc["spec"]["template"]["spec"]["containers"]: env = [e for e in container.get("env") or [] if e.get("value") != INLINE_KEY] if env: container["env"] = env else: container.pop("env", None) path.write_text(yaml.safe_dump(doc, sort_keys=False)) # Left out of every build: an empty Secret would wipe the one created by hand, and the namespace is shared -- # kustomize would relabel it as this component's, and `kubectl delete -k` would delete it with everything in it. LEFT_OUT = ("secretnames.yaml", "namespace.yaml") def _without_shared_resources(path: Path) -> None: doc = yaml.safe_load(path.read_text()) doc["resources"] = [r for r in doc.get("resources", []) if r not in LEFT_OUT] path.write_text(yaml.safe_dump(doc, sort_keys=False)) # Agents live in ///: sub-agents/ or individual-agents/, then one folder per Feature. PATTERNS = ("sub-agents", "individual-agents") def _agent_folder(name: str) -> Path: found = [d for pattern in PATTERNS for d in (ROOT / pattern).glob(f"*/{name}") if (d / "agent.yaml").is_file()] if len(found) != 1: raise SystemExit(f"{name}: expected one agent folder under {' or '.join(PATTERNS)}, found {len(found)}") return found[0] def render(kind: str, name: str, spec: dict, profile: dict, out: Path) -> Path: source = _agent_folder(name) if kind == "agent" else ROOT / "mcp-servers" / name version = _agent_version(source) if kind == "agent" else _mcp_version(name) values = { "": name, "": name, "": name, "": f"{profile['registry']}/{name}:{version}", "": str(spec["port"]), "": spec.get("repo", profile["repo"]), } target = out / name if target.exists(): shutil.rmtree(target) shutil.copytree(source / "kubernetes", target) for f in target.glob("*.yaml"): text = f.read_text() for marker, value in values.items(): text = text.replace(marker, value) f.write_text(text) if kind == "mcp": _drop_inline_key(target / "deployment.yaml") _merge_config(target / "configmap.yaml", spec.get("config")) _without_shared_resources(target / "kustomization.yaml") left = sorted({m for f in target.glob("*.yaml") for m in re.findall(r"", f.read_text())}) if left: raise SystemExit(f"{name}: placeholders left unfilled: {', '.join(left)}") return target def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("profile", type=Path, help="deploy/.yaml") parser.add_argument("components", nargs="*", help="only these agents or MCP servers (default: all)") args = parser.parse_args(argv) profile = yaml.safe_load(args.profile.read_text()) out = ROOT / "build" / args.profile.stem wanted = set(args.components) rendered = [] for kind, section in (("agent", "agents"), ("mcp", "mcp_servers")): for name, spec in (profile.get(section) or {}).items(): if not wanted or name in wanted: rendered.append(render(kind, name, spec, profile, out)) if not rendered: print("nothing rendered: no component matched", file=sys.stderr) return 1 for path in rendered: print(f"{path.relative_to(ROOT)}") print(f"\nReview: kubectl --context {profile['context']} diff -k ") print(f"Deploy: kubectl --context {profile['context']} apply -k ") return 0 if __name__ == "__main__": raise SystemExit(main())