TExcelTAD

XRDs & Compositions

This lesson builds the platform API from Self-Service Infrastructure: a namespaced Database that a team creates with two fields, and a Composition that turns it into a CloudNativePG cluster for the local track (the same operator the Capstone uses for linkly's database). The cloud variant would compose RDS managed resources instead; the team's YAML wouldn't change. All files here are samples for a cluster with Crossplane v2 and CloudNativePG; the logic is modelled in Python and checked with yq at the end.

The XRD: your API

yaml
apiVersion: apiextensions.crossplane.io/v2
kind: CompositeResourceDefinition
metadata:
  name: databases.platform.acme.io        # <plural>.<group>
spec:
  scope: Namespaced                        # the v2 default; teams create Databases in their own namespace
  group: platform.acme.io
  names:
    kind: Database
    plural: databases
  versions:
    - name: v1alpha1
      served: true
      referenceable: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                size:
                  type: string
                  enum: [s, m, l]
                  description: s = 1 instance/5Gi, m = 2/20Gi, l = 3/100Gi
                tier:
                  type: string
                  enum: [critical, standard, experimental]
                  default: standard
              required: [size]
            status:
              type: object
              properties:
                connectionSecret:
                  type: string

Crossplane turns this into a CRD, so kubectl explain database.spec works, the API server validates size against the enum before Crossplane ever sees the object, and RBAC can grant teams create on databases.platform.acme.io and nothing else.

The Composition: the implementation

A Composition is a pipeline of functions. The first step here uses function-patch-and-transform to render resources from a base template plus patches; a second step uses function-auto-ready to mark the XR ready when its composed resources are:

yaml
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
  name: database-cnpg
spec:
  compositeTypeRef:
    apiVersion: platform.acme.io/v1alpha1
    kind: Database
  mode: Pipeline
  pipeline:
    - step: render
      functionRef:
        name: function-patch-and-transform
      input:
        apiVersion: pt.fn.crossplane.io/v1beta1
        kind: Resources
        resources:
          - name: cluster
            base:
              apiVersion: postgresql.cnpg.io/v1
              kind: Cluster
              spec:
                instances: 1
                storage: {size: 5Gi}
                bootstrap: {initdb: {database: app, owner: app}}
            patches:
              - type: FromCompositeFieldPath
                fromFieldPath: spec.size
                toFieldPath: spec.instances
                transforms:
                  - type: map
                    map: {s: 1, m: 2, l: 3}
              - type: FromCompositeFieldPath
                fromFieldPath: spec.size
                toFieldPath: spec.storage.size
                transforms:
                  - type: map
                    map: {s: 5Gi, m: 20Gi, l: 100Gi}
              - type: FromCompositeFieldPath
                fromFieldPath: metadata.name
                toFieldPath: metadata.name
              - type: ToCompositeFieldPath
                fromFieldPath: metadata.name
                toFieldPath: status.connectionSecret
                transforms:
                  - type: string
                    string: {type: Format, fmt: "%s-app"}
    - step: ready
      functionRef:
        name: function-auto-ready

The functions are installed as packages:

yaml
apiVersion: pkg.crossplane.io/v1
kind: Function
metadata:
  name: function-patch-and-transform
spec:
  package: xpkg.crossplane.io/crossplane-contrib/function-patch-and-transform:v0.8.2

A team's request, and what they get back (sample session):

yaml
apiVersion: platform.acme.io/v1alpha1
kind: Database
metadata:
  name: shortlinks
  namespace: team-growth
spec:
  size: m
bash
$ kubectl get databases -n team-growth          # sample output
NAME         SYNCED   READY   COMPOSITION     AGE
shortlinks   True     True    database-cnpg   3m
$ kubectl get database shortlinks -n team-growth -o jsonpath='{.status.connectionSecret}'
shortlinks-app

CloudNativePG creates the shortlinks-app Secret with the application user's credentials; the status field tells the team where it is. In v2, composed resources land in the XR's namespace, so the team's workloads can mount the Secret directly. Crossplane's service account needs RBAC to manage CloudNativePG Cluster objects, since they aren't Crossplane resources.

Before applying, crossplane render xr.yaml composition.yaml functions.yaml (crossplane composition render from CLI v2.3 on, which keeps the old name as an alias) runs the pipeline locally (it starts the function containers with Docker) and prints the composed resources: the Crossplane equivalent of helm template.

Patch and transform, modelled

What function-patch-and-transform does with that input, as a small model: copy the base, read values from the XR, transform them and write them into the composed resource (and back into the XR's status):

python · try it yourself
import copy

XR = {"apiVersion": "platform.acme.io/v1alpha1", "kind": "Database",
      "metadata": {"name": "shortlinks", "namespace": "team-growth"},
      "spec": {"size": "m", "tier": "standard"}, "status": {}}

RESOURCES = [{
    "name": "cluster",
    "base": {"apiVersion": "postgresql.cnpg.io/v1", "kind": "Cluster", "metadata": {},
             "spec": {"instances": 1, "storage": {"size": "5Gi"},
                      "bootstrap": {"initdb": {"database": "app", "owner": "app"}}}},
    "patches": [
        {"type": "FromCompositeFieldPath", "from": "spec.size", "to": "spec.instances",
         "transforms": [{"type": "map", "map": {"s": 1, "m": 2, "l": 3}}]},
        {"type": "FromCompositeFieldPath", "from": "spec.size", "to": "spec.storage.size",
         "transforms": [{"type": "map", "map": {"s": "5Gi", "m": "20Gi", "l": "100Gi"}}]},
        {"type": "FromCompositeFieldPath", "from": "metadata.name", "to": "metadata.name"},
        {"type": "ToCompositeFieldPath", "from": "metadata.name", "to": "status.connectionSecret",
         "transforms": [{"type": "format", "fmt": "%s-app"}]},
    ],
}]

def get(obj, path):
    for p in path.split("."):
        obj = obj[p]
    return obj

def put(obj, path, value):
    *parents, last = path.split(".")
    for p in parents:
        obj = obj.setdefault(p, {})
    obj[last] = value

def transform(value, transforms):
    for t in transforms:
        if t["type"] == "map":
            if value not in t["map"]:
                raise ValueError(f"map transform: no entry for {value!r}")
            value = t["map"][value]
        elif t["type"] == "format":
            value = t["fmt"] % value
    return value

def compose(xr):
    composed = []
    for r in RESOURCES:
        obj = copy.deepcopy(r["base"])
        obj["metadata"]["namespace"] = xr["metadata"]["namespace"]   # v2: same namespace as the XR
        for p in r["patches"]:
            if p["type"] == "FromCompositeFieldPath":
                put(obj, p["to"], transform(get(xr, p["from"]), p.get("transforms", [])))
        for p in r["patches"]:
            if p["type"] == "ToCompositeFieldPath":
                put(xr, p["to"], transform(get(obj, p["from"]), p.get("transforms", [])))
        composed.append(obj)
    return composed

for obj in compose(XR):
    print(obj["kind"], obj["metadata"], obj["spec"]["instances"], obj["spec"]["storage"])
print("XR status:", XR["status"])
try:
    compose({**XR, "spec": {"size": "xl"}})
except ValueError as e:
    print("size xl:", e)
Cluster {'namespace': 'team-growth', 'name': 'shortlinks'} 2 {'size': '20Gi'}
XR status: {'connectionSecret': 'shortlinks-app'}
size xl: map transform: no entry for 'xl'

In a real cluster the xl case never reaches the function: the XRD's enum makes the API server reject it. But the model points at a real risk: the enum in the XRD and the map in the Composition are two lists that must agree. Add xl to the XRD and forget the Composition, and every xl Database fails to compose.

Checking the XRD against the Composition

That consistency check is easy to automate in the platform repository's CI. The session writes both files (trimmed to the relevant parts) and compares the enum with every map transform that reads spec.size:

bash · try it yourself
cat > xrd.yaml <<'EOF'
apiVersion: apiextensions.crossplane.io/v2
kind: CompositeResourceDefinition
metadata: {name: databases.platform.acme.io}
spec:
  scope: Namespaced
  group: platform.acme.io
  names: {kind: Database, plural: databases}
  versions:
    - name: v1alpha1
      served: true
      referenceable: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                size: {type: string, enum: [s, m, l, xl]}
EOF
cat > composition.yaml <<'EOF'
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata: {name: database-cnpg}
spec:
  compositeTypeRef: {apiVersion: platform.acme.io/v1alpha1, kind: Database}
  mode: Pipeline
  pipeline:
    - step: render
      functionRef: {name: function-patch-and-transform}
      input:
        apiVersion: pt.fn.crossplane.io/v1beta1
        kind: Resources
        resources:
          - name: cluster
            base: {apiVersion: postgresql.cnpg.io/v1, kind: Cluster}
            patches:
              - {type: FromCompositeFieldPath, fromFieldPath: spec.size, toFieldPath: spec.instances,
                 transforms: [{type: map, map: {s: 1, m: 2, l: 3, xl: 3}}]}
              - {type: FromCompositeFieldPath, fromFieldPath: spec.size, toFieldPath: spec.storage.size,
                 transforms: [{type: map, map: {s: 5Gi, m: 20Gi, l: 100Gi}}]}
EOF
yq '.spec.versions[0].schema.openAPIV3Schema.properties.spec.properties.size.enum[]' xrd.yaml | sort > enum.txt
echo "XRD enum: $(paste -sd ' ' enum.txt)"
yq -o=json '.spec.pipeline[].input.resources[] | .name as $r | .patches[]
    | select(.fromFieldPath == "spec.size") | {"res": $r, "to": .toFieldPath, "keys": (.transforms[0].map | keys)}' \
    composition.yaml | jq -c '.' | while read -r p; do
  to=$(jq -r '.to' <<< "$p")
  jq -r '.keys[]' <<< "$p" | sort > keys.txt
  gaps=$(comm -23 enum.txt keys.txt | paste -sd ' ')
  if [ -n "$gaps" ]; then echo "MISSING $to: no mapping for: $gaps"; else echo "ok      $to"; fi
done
XRD enum: l m s xl
ok      spec.instances
MISSING spec.storage.size: no mapping for: xl

The storage map has no xl entry: caught in the pull request, not by a team whose database never becomes ready.

Composition functions beyond patch-and-transform

Function Write the logic in Good for
function-patch-and-transform YAML patches (as above) simple field mapping
function-go-templating Go templates producing YAML loops, conditionals; familiar to Helm users
function-kcl, function-cue KCL or CUE typed configuration languages
function-python, your own SDK function (Go, Python) real code, unit-testable complex logic, calling external APIs
function-auto-ready nothing marks the XR ready when composed resources are

Test yourself

What does the XRD define?

  1. How resources are created
  2. The platform's API: a new kind with a schema, served by the API server
  3. The cloud credentials
  4. The function packages

In Crossplane v2, how are Compositions written?

  1. Native patches directly in spec.resources
  2. As a pipeline of composition functions (mode: Pipeline)
  3. In HCL
  4. As Helm charts only

Why did the session's check fail?

  1. The XRD is invalid YAML
  2. The XRD allows xl, but the storage map transform has no xl entry
  3. The Composition uses the wrong apiVersion
  4. CloudNativePG doesn't support 3 instances