Skip to content

alirezarezvani/claude-skills / engineering/skills/kubernetes-operator

kubernetes-operator

Verified

Use when building a Kubernetes operator or CRD (controller-runtime, kubebuilder, operator-sdk, KOPF), before writing the controller. Validates CRDs with crd_validator.py, lints reconcile loops with reconcile_lint.py and scores OperatorHub capability level.

FileKindSize
SKILL.mdskill md10.7 KB
assets/crd_template.yamlconfig2.6 KB
assets/reconcile_skeleton.goscript4.0 KB
references/crd_design.mdmarkdown6.8 KB
references/operator_pattern.mdmarkdown7.0 KB
references/reconcile_loop.mdmarkdown7.1 KB
references/tooling_landscape.mdmarkdown7.5 KB
scripts/crd_validator.pyexecutablescript5.8 KB
scripts/operator_capability_audit.pyexecutablescript5.8 KB
scripts/reconcile_lint.pyexecutablescript6.3 KB

scripts/crd_validator.py

View on GitHub
#!/usr/bin/env python3
"""Validate a Kubernetes CRD YAML against operator-pattern best practices.

Checks for status subresource, structural schema, conditions support, printer
columns, version policy, and other operator-grade design rules. Stdlib-only —
parses YAML via a minimal embedded reader (no PyYAML dependency).
"""
import argparse
import json
import os
import re
import sys

CHECKS = [
    ("status_subresource", "Each version must declare subresources.status (otherwise status updates loop spec reconciles)"),
    ("storage_version", "Exactly one version must be storage:true"),
    ("served_version", "At least one version must be served:true"),
    ("schema_present", "Each version must declare schema.openAPIV3Schema"),
    ("schema_typed", "Schema must declare 'type: object' at root (no x-kubernetes-preserve-unknown-fields at root)"),
    ("conditions_array", "Schema should declare a conditions array under status (for metav1.Conditions)"),
    ("printer_columns", "additionalPrinterColumns should include Age and a status indicator"),
    ("scope", "scope should be Namespaced unless cluster-scoped is justified"),
    ("singular_listkind", "names.singular and names.listKind must be declared"),
]


def _load_yaml_minimal(path):
    """Yield top-level YAML documents from a multi-doc file as text blocks.

    Stdlib-only — splits on '---' separators. We grep relevant fields with
    regex rather than fully parse. Crude but enough for the structural
    checks below; a full YAML parser would be the upgrade path."""
    with open(path, "r", encoding="utf-8", errors="replace") as f:
        text = f.read()
    docs = re.split(r"^---\s*$", text, flags=re.MULTILINE)
    return [d for d in docs if d.strip()]


def _is_crd_doc(doc):
    return bool(re.search(r"^kind:\s*CustomResourceDefinition\s*$", doc, re.MULTILINE))


def _check_one(doc, path):
    findings = []
    has_status_sub = bool(re.search(r"subresources:\s*\n\s*status:\s*\{?\s*\}?", doc))
    if not has_status_sub:
        findings.append(("FAIL", "status_subresource", "no subresources.status block found"))
    storage_count = len(re.findall(r"storage:\s*true\b", doc))
    if storage_count != 1:
        findings.append(("FAIL", "storage_version", f"expected exactly 1 storage:true, found {storage_count}"))
    served_count = len(re.findall(r"served:\s*true\b", doc))
    if served_count < 1:
        findings.append(("FAIL", "served_version", "no served:true version"))
    if "openAPIV3Schema" not in doc:
        findings.append(("FAIL", "schema_present", "no openAPIV3Schema declared"))
    if re.search(r"x-kubernetes-preserve-unknown-fields:\s*true", doc):
        findings.append(("WARN", "schema_typed", "x-kubernetes-preserve-unknown-fields: true present (defeats validation)"))
    if "conditions" not in doc.lower():
        findings.append(("WARN", "conditions_array", "no conditions array referenced (Karpathy: declare an explicit shape)"))
    if "additionalPrinterColumns" not in doc:
        findings.append(("WARN", "printer_columns", "no additionalPrinterColumns (kubectl get UX is poor)"))
    elif not re.search(r"name:\s*Age\b", doc):
        findings.append(("WARN", "printer_columns", "additionalPrinterColumns missing Age column"))
    if not re.search(r"^\s*scope:\s*\w+", doc, re.MULTILINE):
        findings.append(("WARN", "scope", "scope not explicitly set"))
    if not re.search(r"^\s*singular:\s*[\w<]", doc, re.MULTILINE):
        findings.append(("WARN", "singular_listkind", "names.singular not declared"))
    if not re.search(r"^\s*listKind:\s*[\w<]", doc, re.MULTILINE):
        findings.append(("WARN", "singular_listkind", "names.listKind not declared"))
    return findings


def _walk_yaml_files(root):
    if os.path.isfile(root):
        yield root
        return
    for r, _, files in os.walk(root):
        for f in files:
            if f.endswith((".yaml", ".yml")):
                yield os.path.join(r, f)


def audit(target):
    results = []
    for path in _walk_yaml_files(target):
        for doc in _load_yaml_minimal(path):
            if not _is_crd_doc(doc):
                continue
            kind_match = re.search(r"kind:\s*(\w+)\s*$", doc, re.MULTILINE)
            crd_kind = kind_match.group(1) if kind_match else "?"
            name_match = re.search(r"^\s+name:\s*([\w.\-]+)\s*$", doc, re.MULTILINE)
            crd_name = name_match.group(1) if name_match else os.path.basename(path)
            findings = _check_one(doc, path)
            results.append({"path": path, "name": crd_name, "kind": crd_kind, "findings": findings})
    return results


def render_text(results):
    if not results:
        print("No CRD documents found.")
        return 0
    fails = sum(1 for r in results for f in r["findings"] if f[0] == "FAIL")
    warns = sum(1 for r in results for f in r["findings"] if f[0] == "WARN")
    print(f"CRD Validator — {len(results)} CRD(s) inspected, {fails} FAIL, {warns} WARN")
    print("")
    for r in results:
        print(f"== {r['name']}  ({r['path']})")
        if not r["findings"]:
            print("   PASS: all checks green")
            continue
        for level, key, msg in r["findings"]:
            print(f"   [{level}] {key}: {msg}")
        print("")
    return 1 if fails else 0


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--crd", required=True, help="Path to a CRD YAML file or a directory of YAMLs")
    ap.add_argument("--format", choices=["text", "json"], default="text")
    args = ap.parse_args()

    if not os.path.exists(args.crd):
        print(f"ERROR: not found: {args.crd}", file=sys.stderr)
        return 2
    results = audit(args.crd)
    if args.format == "json":
        print(json.dumps(results, indent=2))
        return 0
    return render_text(results)


if __name__ == "__main__":
    sys.exit(main())
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 322kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall