Skip to content
CNPE · Chapter 10 of 22 Day 8: Crossplane – an API that does something

Day 8: Crossplane – an API that does something

Goal: Build a platform API Datenbank with Crossplane: a team writes five lines of YAML and gets PostgreSQL with credentials, storage and a Service. Crossplane keeps everything in the desired state, teams get rights, and a CEL rule protects against a change that cannot work · Duration: approx. 75 min · Prerequisite: Day 7

Briefing

  • The CRD from Day 7 stores wishes but does not fulfil them. Crossplane closes the gap: you describe the API with a CompositeResourceDefinition (XRD), and in a Composition which objects are created for each instance. Crossplane is the controller for it.
Term Meaning
XRD Schema of the new API (becomes a CRD internally)
XR (Composite Resource) One instance, e.g. Datenbank shopdb
Composition Blueprint: which objects, how the fields are transferred
Function Program that executes the Composition; here function-patch-and-transform
Provider Connects external systems (cloud, Helm, …) – not needed today
  • Crossplane 2 sets new defaults: XRs are namespaced by default (they live in the team’s namespace), and a Composition may create any Kubernetes resource – StatefulSets, Secrets, Services – without a provider.
  • The exam names Crossplane explicitly. Without a cloud, the course uses Kubernetes objects; the pattern is the same as for an RDS database at a cloud provider.

Drill 1: Crossplane and the function

# on cp1
mkdir -p ~/cnpe/tag08 && cd ~/cnpe/tag08
helm repo add crossplane-stable https://charts.crossplane.io/stable
helm repo update
helm install crossplane crossplane-stable/crossplane --version 2.5.0 -n crossplane-system --create-namespace \
  --set priorityClassName=plattform-kritisch
k -n crossplane-system rollout status deploy/crossplane --timeout=300s
k -n crossplane-system get pods
# Function as a package: Crossplane pulls the image and starts it as a Deployment
cat > funktion.yaml <<'EOF'
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.11.3
EOF
k apply -f funktion.yaml
k wait --for=condition=Healthy function/function-patch-and-transform --timeout=300s
k get functions

Expected (abridged):

STATUS: deployed
deployment "crossplane" successfully rolled out
NAME                                       READY   STATUS    RESTARTS   AGE
crossplane-77fc464b5d-9ldkj                1/1     Running   0          35s
crossplane-rbac-manager-5d478df655-n2t48   1/1     Running   0          35s
function.pkg.crossplane.io/function-patch-and-transform created
function.pkg.crossplane.io/function-patch-and-transform condition met
NAME                           INSTALLED   HEALTHY   PACKAGE                                                                      AGE
function-patch-and-transform   True        True      xpkg.crossplane.io/crossplane-contrib/function-patch-and-transform:v0.11.3   19s

Save your progress? Sign up for free

Drill 2: The API

# on cp1
cat > xrd-datenbank.yaml <<'EOF'
apiVersion: apiextensions.crossplane.io/v2
kind: CompositeResourceDefinition
metadata:
  name: datenbanken.plattform.lab
spec:
  scope: Namespaced                      # instances in the team's namespace
  group: plattform.lab
  names:
    kind: Datenbank
    plural: datenbanken
  versions:
  - name: v1alpha1
    served: true
    referenceable: true                  # Compositions may refer to this version
    additionalPrinterColumns:
    - {name: Groesse, type: string, jsonPath: .spec.groesse}
    - {name: Adresse, type: string, jsonPath: .status.adresse}
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              groesse:
                description: S = 1 GiB Speicher, M = 5 GiB
                type: string
                enum: [S, M]
                default: S
          status:                        # filled by the Composition
            type: object
            properties:
              adresse:
                description: Hostname des Datenbank-Service im Namespace
                type: string
              bereit:
                type: integer
EOF
k apply -f xrd-datenbank.yaml
k wait --for=condition=Established xrd/datenbanken.plattform.lab --timeout=120s
k api-resources --api-group=plattform.lab

Expected:

compositeresourcedefinition.apiextensions.crossplane.io/datenbanken.plattform.lab created
compositeresourcedefinition.apiextensions.crossplane.io/datenbanken.plattform.lab condition met
NAME          SHORTNAMES   APIVERSION               NAMESPACED   KIND
datenbanken                plattform.lab/v1alpha1   true         Datenbank
umgebungen    umg          plattform.lab/v1beta1    true         Umgebung

Save your progress? Sign up for free

Drill 3: The blueprint

Three objects per database: a Secret with credentials, a StatefulSet with PostgreSQL 18 and a volume, a Service. Patches transfer fields from the XR into the objects (FromCompositeFieldPath) and back into the status (ToCompositeFieldPath).

# on cp1
cat > composition-datenbank.yaml <<'EOF'
apiVersion: apiextensions.crossplane.io/v1
kind: Composition
metadata:
  name: datenbank-postgres
spec:
  compositeTypeRef:                      # for which API
    apiVersion: plattform.lab/v1alpha1
    kind: Datenbank
  mode: Pipeline                         # steps with functions
  pipeline:
  - step: postgres
    functionRef:
      name: function-patch-and-transform
    input:
      apiVersion: pt.fn.crossplane.io/v1beta1
      kind: Resources
      resources:
      - name: zugang
        base:
          apiVersion: v1
          kind: Secret
          stringData:
            username: app
        patches:
        # Name: <xr>-zugang (transform Format)
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: metadata.name, transforms: [{type: string, string: {type: Format, fmt: "%s-zugang"}}]}
        # Password: the UID of the XR – stable and unique (lab only, see Enterprise Note)
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.uid, toFieldPath: stringData.password}
        readinessChecks:
        - {type: None}                   # a Secret is "ready" immediately
      - name: statefulset
        base:
          apiVersion: apps/v1
          kind: StatefulSet
          spec:
            replicas: 1
            template:
              spec:
                containers:
                - name: postgres
                  image: postgres:18-alpine
                  ports: [{containerPort: 5432}]
                  env:
                  - {name: POSTGRES_USER, valueFrom: {secretKeyRef: {key: username}}}
                  - {name: POSTGRES_PASSWORD, valueFrom: {secretKeyRef: {key: password}}}
                  - {name: PGDATA, value: /var/lib/postgresql/data/pgdata}
                  resources:
                    requests: {cpu: 100m, memory: 128Mi}
                    limits: {cpu: 500m, memory: 512Mi}
                  volumeMounts: [{name: daten, mountPath: /var/lib/postgresql/data}]
            volumeClaimTemplates:
            - metadata: {name: daten}
              spec:
                accessModes: [ReadWriteOnce]
                resources: {requests: {storage: 1Gi}}
        patches:
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: metadata.name}
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: spec.serviceName}
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: "spec.selector.matchLabels[plattform.lab/datenbank]"}
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: "spec.template.metadata.labels[plattform.lab/datenbank]"}
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: "spec.template.spec.containers[0].env[0].valueFrom.secretKeyRef.name", transforms: [{type: string, string: {type: Format, fmt: "%s-zugang"}}]}
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: "spec.template.spec.containers[0].env[1].valueFrom.secretKeyRef.name", transforms: [{type: string, string: {type: Format, fmt: "%s-zugang"}}]}
        # Size → storage (transform map)
        - type: FromCompositeFieldPath
          fromFieldPath: spec.groesse
          toFieldPath: "spec.volumeClaimTemplates[0].spec.resources.requests.storage"
          transforms:
          - type: map
            map: {S: 1Gi, M: 5Gi}
        # ready pods back into the status of the XR
        - {type: ToCompositeFieldPath, fromFieldPath: status.readyReplicas, toFieldPath: status.bereit}
        readinessChecks:
        - {type: NonEmpty, fieldPath: status.readyReplicas}   # missing as long as no pod is ready
      - name: service
        base:
          apiVersion: v1
          kind: Service
          spec:
            ports: [{port: 5432}]
        patches:
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: metadata.name}
        - {type: FromCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: "spec.selector[plattform.lab/datenbank]"}
        - {type: ToCompositeFieldPath, fromFieldPath: metadata.name, toFieldPath: status.adresse}
        readinessChecks:
        - {type: NonEmpty, fieldPath: spec.clusterIP}
EOF
# Crossplane may create Deployments on its own – StatefulSets, Secrets, Services only with this role
cat > rbac-crossplane.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: crossplane-darf-datenbanken
  labels:
    rbac.crossplane.io/aggregate-to-crossplane: "true"   # merge into Crossplane's role
rules:
- apiGroups: [apps]
  resources: [statefulsets]
  verbs: ["*"]
- apiGroups: [""]
  resources: [secrets, services]
  verbs: ["*"]
EOF
k apply -f composition-datenbank.yaml -f rbac-crossplane.yaml

Expected:

composition.apiextensions.crossplane.io/datenbank-postgres created
clusterrole.rbac.authorization.k8s.io/crossplane-darf-datenbanken created

Two things in this blueprint come from failed attempts while building the course:

  • Without readinessChecks: [{type: None}] on the Secret, the database never becomes Ready – for a Secret, Crossplane does not know how to recognise readiness (Unready resources: zugang).
  • type: MatchInteger on status.readyReplicas fails with not a (int64) number. NonEmpty works because the field is missing as long as no pod is ready.

Save your progress? Sign up for free

Drill 4: A team places an order

# on cp1
cat > shopdb.yaml <<'EOF'
apiVersion: plattform.lab/v1alpha1
kind: Datenbank
metadata:
  name: shopdb
  namespace: team-green
spec:
  groesse: S
EOF
k apply -f shopdb.yaml
sleep 60
k -n team-green get datenbank
k -n team-green get statefulset,svc,secret,pvc -o name | grep -E 'shopdb'

Expected:

datenbank.plattform.lab/shopdb created
NAME     GROESSE   ADRESSE   SYNCED   READY   RESPONSIVE   COMPOSITION          AGE
shopdb   S         shopdb    True     True    True         datenbank-postgres   61s
statefulset.apps/shopdb
service/shopdb
secret/shopdb-zugang
persistentvolumeclaim/daten-shopdb-0

Does the database work?

# on cp1
PW=$(k -n team-green get secret shopdb-zugang -o jsonpath='{.data.password}' | base64 -d)
# pod with psql; without -i, read the output from the logs afterwards
k -n team-green run psql --restart=Never --image=postgres:18-alpine --env=PGPASSWORD=$PW \
  --command -- psql -h shopdb -U app -d app -tc 'select version();'
k -n team-green wait --for=jsonpath='{.status.phase}'=Succeeded pod/psql --timeout=60s
k -n team-green logs psql
k -n team-green delete pod psql

Expected:

pod/psql created
pod/psql condition met
 PostgreSQL 18.7 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
pod "psql" deleted from team-green namespace

With run --rm -i the output often does not arrive here: psql is done before kubectl attaches to the pod. The detour via wait and logs is reliable.

Save your progress? Sign up for free

Drill 5: Crossplane keeps the desired state

# on cp1
k -n team-green delete svc shopdb
# Crossplane reconciles regularly (by default about once a minute)
sleep 70
k -n team-green get svc shopdb

Expected:

service "shopdb" deleted from team-green namespace
NAME     TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
shopdb   ClusterIP   10.102.97.149   <none>        5432/TCP   70s

Save your progress? Sign up for free

Drill 6: Rights for the teams

Crossplane’s RBAC manager creates roles for the new API – but for Crossplane’s own roles, not for edit:

# on cp1
k auth can-i create datenbanken.plattform.lab -n team-green --as=bob --as-group=team-green-devs
k get clusterrole crossplane:composite:datenbanken.plattform.lab:aggregate-to-edit -o jsonpath='{.metadata.labels}{"\n"}'

Expected:

no
{"rbac.crossplane.io/aggregate-to-admin":"true","rbac.crossplane.io/aggregate-to-edit":"true","rbac.crossplane.io/aggregate-to-ns-admin":"true","rbac.crossplane.io/aggregate-to-ns-edit":"true"}

As on Day 7, you merge the API into edit yourself:

# on cp1
cat > rolle-datenbank.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: plattform-datenbanken-edit
  labels:
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
- apiGroups: [plattform.lab]
  resources: [datenbanken]
  verbs: [get, list, watch, create, update, patch, delete]
EOF
k apply -f rolle-datenbank.yaml
k auth can-i create datenbanken.plattform.lab -n team-green --as=bob --as-group=team-green-devs

Expected:

clusterrole.rbac.authorization.k8s.io/plattform-datenbanken-edit created
yes

Save your progress? Sign up for free

Exercise: What belongs to what?

Time limit: 5 minutes. For shopdb, show all created objects with kind and name – without knowing what they are called.

Solution

# on cp1
# the XR lists its objects in spec.crossplane.resourceRefs
k -n team-green get datenbank shopdb -o jsonpath='{range .spec.crossplane.resourceRefs[*]}{.kind}/{.name}{"\n"}{end}'

Expected:

StatefulSet/shopdb
Secret/shopdb-zugang
Service/shopdb

The PVC is missing from the list: it belongs to the StatefulSet, not to Crossplane. If the team deletes the database, it stays (the StatefulSet default) – data is not lost by accident.

Save your progress? Sign up for free

Challenge

Time limit: 10 minutes. Team Green changes shopdb to groesse: M. What happens, and how do you prevent it already at submission time?

Solution

# on cp1
k -n team-green patch datenbank shopdb --type=merge -p '{"spec":{"groesse":"M"}}'
sleep 30
k -n team-green get datenbank shopdb
k -n team-green get events --field-selector involvedObject.name=shopdb --sort-by=.lastTimestamp | tail -2 | cut -c1-160

Expected:

datenbank.plattform.lab/shopdb patched
NAME     GROESSE   ADRESSE   SYNCED   READY   RESPONSIVE   COMPOSITION          AGE
shopdb   M         shopdb    False    True    True         datenbank-postgres   4m19s
31s   Warning   ComposeResources   datenbank/shopdb   cannot apply composed resource "statefulset": StatefulSet.apps "shopdb" is invalid: spec.volumeClaimTemplates: Invalid value: …
31s   Normal    ComposeResources   datenbank/shopdb   Composed resource "statefulset" is not yet valid

The change is accepted but never applied: the volumeClaimTemplates of a StatefulSet are immutable. The database keeps running but permanently shows SYNCED False. Better: make the field immutable in the API – a CEL rule with oldSelf:

# on cp1
k -n team-green patch datenbank shopdb --type=merge -p '{"spec":{"groesse":"S"}}'
yq -i '.spec.versions[0].schema.openAPIV3Schema.properties.spec.properties.groesse.x-kubernetes-validations =
  [{"rule": "self == oldSelf", "message": "groesse ist nach dem Anlegen unveraenderlich"}]' xrd-datenbank.yaml
k apply -f xrd-datenbank.yaml
sleep 10
k -n team-green patch datenbank shopdb --type=merge -p '{"spec":{"groesse":"M"}}'

Expected:

datenbank.plattform.lab/shopdb patched
compositeresourcedefinition.apiextensions.crossplane.io/datenbanken.plattform.lab configured
The Datenbank "shopdb" is invalid: spec.groesse: Invalid value: "M": groesse ist nach dem Anlegen unveraenderlich

Save your progress? Sign up for free

Checkpoint

# on cp1
k get xrd datenbanken.plattform.lab -o jsonpath='{.status.conditions[?(@.type=="Established")].status}{"\n"}'
k -n team-green get datenbank shopdb -o jsonpath='{.status.adresse} {.status.bereit}{"\n"}'
k -n team-green get datenbank shopdb -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}{"\n"}'
k auth can-i create datenbanken.plattform.lab -n team-green --as=bob --as-group=team-green-devs

Expected:

True
shopdb 1
True
yes

Interview Note

  • What distinguishes an XRD from a CRD? The XRD creates a CRD and links it to Crossplane’s controller, which creates and reconciles real resources through Compositions.
  • Why not Helm charts per team? A chart is installed once; a platform API is continuously reconciled, constrained by RBAC and schema, and reports status back.
  • What happens if a team deletes a created object? Crossplane recreates it on the next reconciliation – the XR is the source of truth.

Enterprise Note

  • Don’t derive passwords from the UID: generate them randomly (e.g. function-go-templating with a stored result, External Secrets with OpenBao) and deliver them via connectionDetails.
  • For real databases, compose an operator (CloudNativePG Cluster) instead of a StatefulSet – backups, failover and upgrades come with it.
  • Version Compositions (CompositionRevision) and release new revisions only for new XRs (compositionUpdatePolicy: Manual).
  • Roll out XRDs, Compositions and Functions via GitOps (Argo CD); teams order via pull request.

Contents

More