|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Sync rules from config/rbac/role.yaml into the Helm ClusterRole template. |
| 3 | +
|
| 4 | +The Helm template must contain: |
| 5 | + # GENERATED RULES BEGIN |
| 6 | + ... |
| 7 | + # GENERATED RULES END |
| 8 | +markers inside its ClusterRole rules section. Everything between the markers |
| 9 | +is replaced with the rules from config/rbac/role.yaml (indented by two spaces). |
| 10 | +""" |
| 11 | +import re |
| 12 | +import sys |
| 13 | + |
| 14 | +ROLE_YAML = "config/rbac/role.yaml" |
| 15 | +HELM_RBAC = "helm/temporal-worker-controller/templates/rbac.yaml" |
| 16 | +BEGIN_MARKER = " # GENERATED RULES BEGIN" |
| 17 | +END_MARKER = " # GENERATED RULES END" |
| 18 | + |
| 19 | + |
| 20 | +def extract_rules_text(path): |
| 21 | + with open(path) as f: |
| 22 | + content = f.read() |
| 23 | + idx = content.find("\nrules:\n") |
| 24 | + if idx == -1: |
| 25 | + print(f"ERROR: 'rules:' not found in {path}", file=sys.stderr) |
| 26 | + sys.exit(1) |
| 27 | + rules_body = content[idx + len("\nrules:\n"):] |
| 28 | + # Indent lines relative to the `rules:` key in the Helm template. |
| 29 | + # controller-gen emits two indentation levels: |
| 30 | + # col 0: outer list items (e.g. "- apiGroups:") → add 2 spaces |
| 31 | + # col 2: inner list values (e.g. " - events") → add 4 spaces |
| 32 | + # col 2: mapping keys (e.g. " resources:") → add 2 spaces |
| 33 | + # The extra indent on inner list values matches the style used by the |
| 34 | + # hand-authored rules in the Helm template. |
| 35 | + lines = rules_body.splitlines(keepends=True) |
| 36 | + result = [] |
| 37 | + for line in lines: |
| 38 | + if not line.strip(): |
| 39 | + result.append(line) |
| 40 | + elif line.startswith(" - "): |
| 41 | + result.append(" " + line) # inner list value: 2 global + 2 extra |
| 42 | + else: |
| 43 | + result.append(" " + line) # outer list item or mapping key: 2 global |
| 44 | + return "".join(result) |
| 45 | + |
| 46 | + |
| 47 | +def update_helm(path, rules_text): |
| 48 | + with open(path) as f: |
| 49 | + content = f.read() |
| 50 | + pattern = re.compile( |
| 51 | + r"(" + re.escape(BEGIN_MARKER) + r"[^\n]*\n)(.*?)(" + re.escape(END_MARKER) + r")", |
| 52 | + re.DOTALL, |
| 53 | + ) |
| 54 | + if not pattern.search(content): |
| 55 | + print(f"ERROR: markers not found in {path}", file=sys.stderr) |
| 56 | + sys.exit(1) |
| 57 | + updated = pattern.sub(r"\g<1>" + rules_text + r"\g<3>", content) |
| 58 | + with open(path, "w") as f: |
| 59 | + f.write(updated) |
| 60 | + print(f"Synced RBAC rules from {ROLE_YAML} → {HELM_RBAC}") |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + rules = extract_rules_text(ROLE_YAML) |
| 65 | + update_helm(HELM_RBAC, rules) |
0 commit comments