Helm Named Template & _helpers.tpl Refactor Prompt
Refactor a sprawling Helm chart into reusable named templates in _helpers.tpl, eliminating duplicated label blocks, name truncation, and copy-pasted selectors across manifests.
- Target user
- Chart maintainers cleaning up an organically-grown Helm chart
- Difficulty
- Intermediate
- Tools
- Claude, Cursor
The prompt
You are a senior Helm chart maintainer who has untangled charts where every template hand-rolled its own labels and 63-char name truncation, then drifted out of sync.
I will provide:
- The current chart's templates/ directory and any existing _helpers.tpl
- Chart name, release naming expectations, and label conventions
- Whether the chart ships subcharts or is published to a registry
Your job:
1. **Inventory duplication** — scan every template and list repeated blocks: `metadata.labels`, `spec.selector.matchLabels`, fullname/name construction, and image string assembly. Mark which differ subtly (a drift bug waiting to happen).
2. **Define the canonical helpers** — author `chart.name`, `chart.fullname`, `chart.chart`, `chart.labels`, and `chart.selectorLabels` named templates using `define`/`template`/`include`. Use `trunc 63 | trimSuffix "-"` on names and `include` (not `template`) so output can be piped to `nindent`.
3. **Separate selector vs full labels** — selectorLabels must be immutable and a subset; full labels add `helm.sh/chart`, `app.kubernetes.io/version`, and `managed-by`. Explain why mutating selectorLabels breaks Deployment upgrades.
4. **Rewrite manifests** — replace inline blocks with `{{- include "chart.labels" . | nindent 4 }}` and equivalents, keeping indentation correct.
5. **Override hooks** — add a values key (e.g. `commonLabels`) merged into the labels helper so users can inject labels without forking.
6. **Verify** — run `helm template` and `helm lint` and diff rendered output against the pre-refactor render to prove zero behavioral change.
Output as: (a) the full `_helpers.tpl`, (b) before/after for two representative manifests, (c) the `helm template` diff command to prove parity.
Do not change any `spec.selector.matchLabels` values in a way that alters an already-deployed Deployment — that field is immutable and forces a delete/recreate.