TExcelTAD

Rendering a Golden Path

Every scaffolding tool, from Backstage's fetch:template to Copier and cookiecutter, does the same three things: validate the inputs, render a directory of files with those inputs, and hand the result to something that publishes it. This lesson builds the first two, first as a model, then for real with a skeleton chart that Helm and kubeconform check.

Inputs are a schema

A golden path's inputs are a contract. Backstage describes them with JSON Schema in the template's parameters; Copier with copier.yml questions. Whatever the tool, validate before rendering: a bad service name caught in the form costs nothing, one caught by the Kubernetes API after the repo exists costs an afternoon.

python · try it yourself
import re

SCHEMA = {
    "name":   {"type": str, "required": True, "pattern": r"^[a-z][a-z0-9-]{1,28}[a-z0-9]
quot;}, "owner": {"type": str, "required": True, "enum": ["team-growth", "team-links", "team-platform"]}, "port": {"type": int, "default": 8080, "min": 1024, "max": 65535}, "tier": {"type": str, "default": "standard", "enum": ["critical", "standard", "experimental"]}, } def validate(answers): values, errors = {}, [] for key, rule in SCHEMA.items(): if key not in answers: if rule.get("required"): errors.append(f"{key}: required") else: values[key] = rule["default"] continue v = answers[key] if not isinstance(v, rule["type"]): errors.append(f"{key}: must be {rule['type'].__name__}") continue if "pattern" in rule and not re.match(rule["pattern"], v): errors.append(f"{key}: {v!r} must match {rule['pattern']}") if "enum" in rule and v not in rule["enum"]: errors.append(f"{key}: {v!r} is not one of {rule['enum']}") if "min" in rule and not rule["min"] <= v <= rule["max"]: errors.append(f"{key}: {v} outside {rule['min']}..{rule['max']}") values[key] = v unknown = sorted(set(answers) - set(SCHEMA)) errors += [f"{k}: unknown input" for k in unknown] return values, errors for answers in [ {"name": "shortlinks", "owner": "team-growth"}, {"name": "Short_Links", "owner": "growth", "port": 80, "colour": "blue"}, ]: values, errors = validate(answers) print("answers:", answers) print(" ->", errors if errors else values)
answers: {'name': 'shortlinks', 'owner': 'team-growth'}
  -> {'name': 'shortlinks', 'owner': 'team-growth', 'port': 8080, 'tier': 'standard'}
answers: {'name': 'Short_Links', 'owner': 'growth', 'port': 80, 'colour': 'blue'}
  -> ["name: 'Short_Links' must match ^[a-z][a-z0-9-]{1,28}[a-z0-9]
quot;, "owner: 'growth' is not one of ['team-growth', 'team-links', 'team-platform']", 'port: 80 outside 1024..65535', 'colour: unknown input']

The name pattern is the rule that matters most: service names become DNS labels (Kubernetes object names, hostnames), repository names and metric labels, so restrict them to lowercase letters, digits and hyphens, short enough for every system they end up in.

Rendering a directory

The renderer walks the skeleton, replaces placeholders, and can rename files whose names contain placeholders (chart/${{ values.name }}/). Backstage's fetch:template uses Nunjucks with ${{ values.name }} placeholders, so this course's skeletons use the same syntax. A tiny renderer in Python, with one filter and one conditional:

python · try it yourself
import re

SKELETON = {
    "catalog-info.yaml": """apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: ${{ values.name }}
  title: ${{ values.name | title }}
spec:
  type: service
  owner: ${{ values.owner }}
  lifecycle: ${{ values.lifecycle }}
""",
    "chart/${{ values.name }}/values.yaml": """replicaCount: ${{ values.replicas }}
service:
  port: ${{ values.port }}
{% if values.tier == "critical" %}podDisruptionBudget:
  minAvailable: 2
{% endif %}""",
}

FILTERS = {"title": lambda s: s.replace("-", " ").title(), "upper": str.upper}

def render(text, values):
    def cond(m):
        key, want, body = m.group(1), m.group(2), m.group(3)
        return body if str(values[key]) == want else ""
    text = re.sub(r'\{% if values\.(\w+) == "([^"]*)" %\}(.*?)\{% endif %\}', cond, text, flags=re.S)
    def sub(m):
        v = str(values[m.group(1)])
        for f in [f.strip() for f in m.group(2).split("|") if f.strip()]:
            v = FILTERS[f](v)
        return v
    return re.sub(r"\$\{\{ values\.(\w+)((?:\s*\|\s*\w+)*) \}\}", sub, text)

values = {"name": "short-links", "owner": "team-growth", "lifecycle": "experimental",
          "replicas": 2, "port": 8080, "tier": "critical"}
for path, text in SKELETON.items():
    print(f"--- {render(path, values)}")
    print(render(text, values), end="")
--- catalog-info.yaml
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: short-links
  title: Short Links
spec:
  type: service
  owner: team-growth
  lifecycle: experimental
--- chart/short-links/values.yaml
replicaCount: 2
service:
  port: 8080
podDisruptionBudget:
  minAvailable: 2

Real template engines add loops, includes, whitespace control and escaping, but the core idea fits on a screen. Two things to notice:

  • Two template languages in one file. A Helm chart inside a golden path contains {{ .Values.x }} for Helm and ${{ values.x }} for the scaffolder. Backstage's ${{ }} delimiter leaves Helm's plain {{ }} alone. GitHub Actions workflows are the opposite case: their ${{ github.sha }} expressions use the same delimiter, so in a Backstage skeleton you wrap them in {% raw %}…{% endraw %}. With Copier or cookiecutter (Jinja2, {{ }}) it's Helm files that need care: mark them "copy without rendering" or escape the braces.
  • Rendering happens once. After scaffolding, the files belong to the team. Changes to the template reach them only through an update process (next lessons).

The real thing: render a skeleton chart and check it

The session below has a small golden-path skeleton: a catalog file and a Helm chart whose values come from the service's inputs. A 6-line render.sh turns service.yaml into sed expressions with yq -o=props and renders every file, including file and directory names. Then the platform's checks run on the result: Helm lint, Helm template and kubeconform.

bash · try it yourself
mkdir -p skeleton/'chart/${{ values.name }}'/templates
cat > skeleton/catalog-info.yaml <<'EOF'
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: ${{ values.name }}
spec:
  type: service
  owner: ${{ values.owner }}
  lifecycle: production
EOF
cat > 'skeleton/chart/${{ values.name }}/Chart.yaml' <<'EOF'
apiVersion: v2
name: ${{ values.name }}
version: 0.1.0
appVersion: "0.1.0"
EOF
cat > 'skeleton/chart/${{ values.name }}/values.yaml' <<'EOF'
image: ghcr.io/acme/${{ values.name }}
replicaCount: ${{ values.replicas }}
port: ${{ values.port }}
EOF
cat > 'skeleton/chart/${{ values.name }}/templates/deployment.yaml' <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Chart.Name }}
  labels: {app.kubernetes.io/name: {{ .Chart.Name }}, team: ${{ values.owner }}}
spec:
  replicas: {{ .Values.replicaCount }}
  selector: {matchLabels: {app.kubernetes.io/name: {{ .Chart.Name }}}}
  template:
    metadata:
      labels: {app.kubernetes.io/name: {{ .Chart.Name }}, team: ${{ values.owner }}}
    spec:
      containers:
        - name: app
          image: "{{ .Values.image }}:{{ .Chart.AppVersion }}"
          ports: [{name: http, containerPort: {{ .Values.port }}}]
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 128Mi}
EOF
cat > render.sh <<'EOF'
#!/bin/bash
# usage: render.sh <skeleton-dir> <values.yaml> <out-dir>
set -euo pipefail
yq -o=props "$2" | sed -E 's/^([^ ]+) = (.*)$/s|\\$\\{\\{ values.\1 \\}\\}|\2|g/' > /tmp/render.sed
(cd "$1" && find . -type f) | sort | while read -r f; do
  out="$3/$(echo "$f" | sed -E -f /tmp/render.sed)"
  mkdir -p "$(dirname "$out")" && sed -E -f /tmp/render.sed "$1/$f" > "$out"
done
EOF
chmod +x render.sh
printf 'name: shortlinks\nowner: team-growth\nreplicas: 2\nport: 8080\n' > service.yaml
./render.sh skeleton service.yaml out
tree --noreport out
grep -rn '\${{' out || echo "no placeholders left"
helm lint out/chart/shortlinks | tail -1
helm template shortlinks out/chart/shortlinks | kubeconform -strict -summary
helm template shortlinks out/chart/shortlinks | yq '.metadata.labels, .spec.replicas'
out
├── catalog-info.yaml
└── chart
    └── shortlinks
        ├── Chart.yaml
        ├── templates
        │   └── deployment.yaml
        └── values.yaml
no placeholders left
1 chart(s) linted, 0 chart(s) failed
Summary: 1 resource found parsing stdin - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0
{app.kubernetes.io/name: shortlinks, team: team-growth}
2

The check grep -rn '\${{' is cheap insurance: a typo in a placeholder (${{ values.ownr }}) is not an error for sed, it just stays in the output. Template engines often do something similar: unless configured to fail, they render an undefined value as an empty string. So the template's own CI must render it with sample inputs and validate the result. You will build that CI in the Mini Project.

Note: this sed renderer is a teaching tool. It breaks on values containing |, & or newlines and has no conditionals or loops. Real golden paths use Backstage's Nunjucks, Copier or cookiecutter (Jinja2), or a small Go program with text/template.

Test yourself

Why do Backstage templates use ${{ values.name }} rather than {{ values.name }}?

  1. It is faster
  2. So scaffolder placeholders don't collide with the {{ }} syntax of the Helm templates inside the skeleton
  3. JSON Schema requires it
  4. Nunjucks has no other syntax

Why should a golden path's input name be restricted to lowercase letters, digits and hyphens?

  1. Style
  2. It becomes a DNS label: Kubernetes object names, hostnames, repository names and metric labels
  3. YAML requires it
  4. Backstage can't display uppercase

What does the template's own CI need to do?

  1. Nothing; templates are static
  2. Render it with sample inputs and validate the output (no leftover placeholders, lint, kubeconform, build)
  3. Only check YAML syntax of the skeleton
  4. Publish it to the catalog