Day 3: CEL Expressions
Goal: Convert, concatenate and branch values and catch missing fields. You learn to read the error messages of the static check before a team ever gets to see them. · Duration: approx. 60 min · Prerequisite: Day 2
Briefing
- Everything between
${and}is CEL (Common Expression Language), the same language Kubernetes uses for validation rules. CEL is type-safe, has no loops and is guaranteed to terminate. - You can read
schema.spec(fields of the instance),schema.metadata(name, namespace, labels) and every other object of the RGD via itsid. - When the RGD is created, kro checks every expression against the real schema of the target kind (static analysis): Does the field exist? Does the type match? Is the syntax valid?
- If the check fails, the RGD becomes
Inactive. Existing instances keep running with the last valid version.
| Expression | Result |
|---|---|
${string(schema.spec.maxNotes)} |
Number as text |
${a ? "x" : "y"} |
Branch |
${schema.spec.?tags.orValue([])} |
Field, or a fallback value if it is missing |
${liste.join(",")} |
List as text |
"${a} in ${b}" |
Several expressions in one text |
Drill 1: A Type Error
mkdir -p ~/kro-lab/tag03
cd ~/kro-lab/tag03
cp ../tag02/settings-rgd.yaml .Open settings-rgd.yaml in the editor
(nano settings-rgd.yaml) and add a line at the end of the
data: block:
data:
team: ${schema.spec.team}
logLevel: ${schema.spec.logLevel}
maxNotes: ${schema.spec.maxNotes}
kubectl apply -f settings-rgd.yaml
kubectl get rgd notes-settingsExpected:
resourcegraphdefinition.kro.run/notes-settings configured
NAME APIVERSION KIND STATE READY AGE
notes-settings v1alpha1 NotesSettings Inactive False 38s
The condition GraphAccepted gives the reason:
kubectl get rgd notes-settings \
-o jsonpath='{.status.conditions[?(@.type=="GraphAccepted")].message}{"\n"}'Expected:
failed to validate resource "config": type mismatch in resource "config" at path
"data.maxNotes": expression "schema.spec.maxNotes" returns type "int" but expected
"string": type kind mismatch: got "int", expected "string"
Values in a ConfigMap are always text; maxNotes is a
number. kro detected this without a single instance noticing
anything:
kubectl -n app get nsetExpected:
NAME TEAM LOG STATE
blau team-blau debug ACTIVE
Fix the line in the editor:
maxNotes: ${string(schema.spec.maxNotes)}
kubectl apply -f settings-rgd.yaml
kubectl get rgd notes-settingsExpected: STATE Active, READY
True.
Save your progress? Sign up for free
Drill 2: Branching, and the Colon
readOnly should appear as a word in the ConfigMap.
Add:
mode: ${schema.spec.readOnly ? "lesen" : "lesen+schreiben"}
kubectl apply -f settings-rgd.yamlExpected:
error: error parsing settings-rgd.yaml: error converting YAML to JSON: yaml: line 46:
mapping values are not allowed in this context
This isn’t a kro error but YAML: a colon followed by a space starts a
new key. Expressions containing : belong in single
quotes:
mode: '${schema.spec.readOnly ? "lesen" : "lesen+schreiben"}'
kubectl apply -f settings-rgd.yaml
kubectl get rgd notes-settingsExpected: STATE Active.
Save your progress? Sign up for free
Drill 3: Missing Fields
tags is not a required field and has no default.
Add:
tags: ${schema.spec.tags.join(",")}
kubectl apply -f settings-rgd.yaml
kubectl get rgd notes-settingsExpected:
NAME APIVERSION KIND STATE READY AGE
notes-settings v1alpha1 NotesSettings Active True 4m
The static check is satisfied, because it knows the type. Whether the
field is set in an instance, it cannot know. Create an instance without
tags:
cat > gruen.yaml <<'EOF'
apiVersion: lab.example.com/v1alpha1
kind: NotesSettings
metadata:
name: gruen
namespace: app
spec:
team: team-gruen
EOF
kubectl apply -f gruen.yaml
kubectl -n app get nset gruenExpected:
notessettings.lab.example.com/gruen created
NAME TEAM LOG STATE
gruen team-gruen info IN_PROGRESS
kubectl -n app get nset gruen \
-o jsonpath='{.status.conditions[?(@.type=="ResourcesReady")].message}{"\n"}'Expected:
waiting for unresolved resource: apply "config": resolve: node "config": eval
"schema.spec.tags.join(\",\")" at "data.tags": eval "schema.spec.tags.join(\",\")":
no such key: tags (data pending) (executor: node not ready)
kro waits for tags to show up, and that never happens.
So you read a field without a default with the optional
operator ? and provide a fallback value with
orValue:
tags: ${schema.spec.?tags.orValue([]).join(",")}
kubectl apply -f settings-rgd.yaml
kubectl -n app get nset gruenExpected:
NAME TEAM LOG STATE
gruen team-gruen info ACTIVE
The same pattern applies to nested fields. Add:
owner: ${schema.spec.?owner.?email.orValue("niemand")}
Save your progress? Sign up for free
Drill 4: Building Texts
kro joins several expressions in one value into a text, as long as each individual expression returns a text. Add:
summary: "${schema.spec.team} in ${schema.metadata.namespace}"
hint: "Platzhalter wie ${HOME} bleiben stehen"
kubectl apply -f settings-rgd.yaml
kubectl get rgd notes-settings \
-o jsonpath='{.status.conditions[?(@.type=="GraphAccepted")].message}{"\n"}'Expected:
failed to build dependency graph: failed to extract dependencies: references unknown
identifiers: [HOME]
kro takes ${HOME} for an expression and looks for an
object with the id HOME. For a literal
${…}, for example in a shell command, you wrap the text in
a CEL string:
hint: 'Platzhalter wie ${"${HOME}"} bleiben stehen'
The outer expression returns the string ${HOME}, and
that stays as it is.
kubectl apply -f settings-rgd.yaml
kubectl get rgd notes-settings
kubectl -n app get configmap blau-settings -o yaml | grep -A9 '^data:'Expected:
NAME APIVERSION KIND STATE READY AGE
notes-settings v1alpha1 NotesSettings Active True 5m
data:
hint: Platzhalter wie ${HOME} bleiben stehen
logLevel: debug
maxNotes: "100"
mode: lesen+schreiben
owner: [email protected]
summary: team-blau in app
tags: ""
team: team-blau
kind: ConfigMap
Save your progress? Sign up for free
Drill 5: Three Typical Errors
You provoke the three most common messages of the static check. Change one line each time, apply, read the message and undo the change again.
Typo in the field name:
team: ${schema.spec.teem}
failed to validate resource "config": failed to compile template expression
"schema.spec.teem" at path "data.team": ERROR: <input>:1:12: undefined field 'teem'
| schema.spec.teem
| ...........^
Unknown API version: apiVersion: v2
instead of v1 for the ConfigMap
failed to build resource "config": failed to get schema for resource config: cannot
resolve group version "v2": schema not found
Cycle: If two objects point at each other, kro reports (you’ll see this on Day 4):
failed to build dependency graph: graph contains a cycle: service -> deployment ->
service
You read the exact wording each time with the jsonpath
command from Drill 1.
Save your progress? Sign up for free
Checkpoint
kubectl get rgd notes-settingsExpected: STATE Active, READY
True.
kubectl -n app get nsetExpected:
NAME TEAM LOG STATE
blau team-blau debug ACTIVE
gruen team-gruen info ACTIVE
diff settings-rgd.yaml ~/kro-lab/code/loesung/tag03/settings-rgd.yamlExpected: no output.
Challenge
Set the tags intern and beta on
blau and turn on readOnly. What is in
tags and mode of the ConfigMap afterwards?
Note: A merge patch with two
fields.
Solution
kubectl -n app patch nset blau --type merge \
-p '{"spec":{"tags":["intern","beta"],"readOnly":true}}'
kubectl -n app get configmap blau-settings -o jsonpath='{.data.tags} | {.data.mode}{"\n"}'Expected:
notessettings.lab.example.com/blau patched
intern,beta | lesen
Clean up:
kubectl -n app delete nset gruenSave your progress? Sign up for free
Enterprise Note
- Errors early: Static analysis is kro’s biggest
advantage over text templates. A typo shows up at
kubectl applyof the RGD, not when the twentieth team rolls out. - Use optional deliberately:
?turns off the check for that field. Use it for fields that may be missing, and always provide a sensible fallback withorValue. - CEL libraries: kro ships functions for hashes,
JSON, random values, URLs, regex, quantities and semver. The list is
under “CEL Libraries” on
kro.run. You’ll use some of them from Day 6 on.