This document is for a preview version of Crossplane.

This document applies to Crossplane v2.0-preview and not to the latest release v1.19.

Don't use Crossplane v2.0-preview in production.

This guide shows how to create a new kind of custom resource named App. When a user calls the custom resource API to create an App, Crossplane creates a Deployment and a Service.

Crossplane calls this composition. The App is composed of the Deployment and the Service.

Tip
The guide shows how to configure composition using YAML, templated YAML, Python, and KCL. You can pick your preferred language.

An App custom resource looks like this:

 1apiVersion: example.crossplane.io/v1
 2kind: App
 3metadata:
 4  namespace: default
 5  name: my-app
 6spec:
 7  image: nginx
 8status:
 9  replicas: 2  # Copied from the Deployment's status
10  address: 10.0.0.1  # Copied from the Service's status

The App is the custom API Crossplane users use to configure an app.

When users create an App Crossplane creates this Deployment and Service:

 1---
 2apiVersion: apps/v1
 3kind: Deployment
 4metadata:
 5  namespace: default
 6  name: my-app-dhj3a
 7  labels:
 8    example.crossplane.io/app: my-app  # Copied from the App's name
 9spec:
10  replicas: 2
11  selector:
12    matchLabels:
13      example.crossplane.io/app: my-app  # Copied from the App's name
14  template:
15    metadata:
16      labels:
17        example.crossplane.io/app: my-app  # Copied from the App's name
18    spec:
19      containers:
20      - name: app
21        image: nginx  # Copied from the App's spec
22        ports:
23        - containerPort: 80
24---
25apiVersion: v1
26kind: Service
27metadata:
28  namespace: default
29  name: my-app-03mda
30  labels:
31    example.crossplane.io/app: my-app  # Copied from the App's name
32spec:
33  selector:
34    example.crossplane.io/app: my-app  # Copied from the App's name
35  ports:
36  - protocol: TCP
37    port: 8080
38    targetPort: 80

Crossplane builds on Kubernetes, so users can use kubectl or any other tool from the Kubernetes ecosystem to work with apps.

Tip
Kubernetes custom resources are just JSON REST APIs, so users can use any tool that supports REST APIs to work with apps.

Prerequisites

This guide requires:

Create the custom resource

Follow these steps to create a new kind of custom resource using Crossplane:

  1. Define the schema of the App custom resource
  2. Install the function you want to use to configure how Crossplane composes apps
  3. Configure how Crossplane composes apps

After you complete these steps you can use the new App custom resource.

Define the schema

Crossplane calls a custom resource that’s powered by composition a composite resource, or XR.

Note

Kubernetes calls user-defined API resources custom resources.

Crossplane calls user-defined API resources that use composition composite resources.

A composite resource is a kind of custom resource.

Create this composite resource definition (XRD) to define the schema of the new App composite resource (XR).

 1apiVersion: apiextensions.crossplane.io/v2alpha1
 2kind: CompositeResourceDefinition
 3metadata:
 4  name: apps.example.crossplane.io
 5spec:
 6  scope: Namespaced
 7  group: example.crossplane.io
 8  names:
 9    kind: App
10    plural: apps
11  versions:
12  - name: v1
13    served: true
14    referenceable: true
15    schema:
16     openAPIV3Schema:
17       type: object
18       properties:
19        spec:
20          type: object
21          properties:
22            image:
23              description: The app's OCI container image.
24              type: string
25          required:
26          - image
27        status:
28          type: object
29          properties:
30            replicas:
31              description: The number of available app replicas.
32              type: integer
33            address:
34              description: The app's IP address.
35              type: string

Save the XRD as xrd.yaml and apply it:

1kubectl apply -f xrd.yaml

Check that Crossplane has established the XRD:

1kubectl get -f xrd.yaml
2NAME                         ESTABLISHED   OFFERED   AGE
3apps.example.crossplane.io   True                    21s

Now that Crossplane has established the XRD, Kubernetes is serving API requests for the new App XR.

Crossplane now knows it’s responsible for the new App XR, but it doesn’t know what to do when you create or update one. You tell Crossplane what to do by installing a function and configuring a composition.

Install the function

You can use different composition functions to configure what Crossplane does when someone creates or updates a composite resource (XR). Composition functions are like configuration language plugins.

Pick what language to use to configure how Crossplane turns an App XR into a Deployment and a Service.

YAML is a good choice for small, static compositions. It doesn’t support loops or conditionals.

Create this composition function to install YAML support:

1apiVersion: pkg.crossplane.io/v1
2kind: Function
3metadata:
4  name: crossplane-contrib-function-patch-and-transform
5spec:
6  package: xpkg.crossplane.io/crossplane-contrib/function-patch-and-transform:v0.8.2

Save the function as fn.yaml and apply it:

1kubectl apply -f fn.yaml

Check that Crossplane installed the function:

1kubectl get -f fn.yaml
2NAME                                              INSTALLED   HEALTHY   PACKAGE                                                                     AGE
3crossplane-contrib-function-patch-and-transform   True        True      xpkg.crossplane.io/crossplane-contrib/function-patch-and-transform:v0.8.2   10s

Templated YAML is a good choice if you’re used to writing Helm charts.

Create this composition function to install templated YAML support:

1apiVersion: pkg.crossplane.io/v1
2kind: Function
3metadata:
4  name: crossplane-contrib-function-go-templating
5spec:
6  package: xpkg.crossplane.io/crossplane-contrib/function-go-templating:v0.9.2

Save the function as fn.yaml and apply it:

1kubectl apply -f fn.yaml

Check that Crossplane installed the function:

1kubectl get -f fn.yaml
2NAME                                        INSTALLED   HEALTHY   PACKAGE                                                               AGE
3crossplane-contrib-function-go-templating   True        True      xpkg.crossplane.io/crossplane-contrib/function-go-templating:v0.9.2   9s

Python is a good choice for compositions with dynamic logic. You can use the full Python standard library.

Create this composition function to install Python support:

1apiVersion: pkg.crossplane.io/v1
2kind: Function
3metadata:
4  name: crossplane-contrib-function-python
5spec:
6  package: xpkg.crossplane.io/crossplane-contrib/function-python:v0.1.0

Save the function as fn.yaml and apply it:

1kubectl apply -f fn.yaml

Check that Crossplane installed the function:

1kubectl get -f fn.yaml
2NAME                                 INSTALLED   HEALTHY   PACKAGE                                                        AGE
3crossplane-contrib-function-python   True        True      xpkg.crossplane.io/crossplane-contrib/function-python:v0.1.0   12s

KCL is a good choice for compositions with dynamic logic. It’s fast and sandboxed.

Create this composition function to install KCL support:

1apiVersion: pkg.crossplane.io/v1
2kind: Function
3metadata:
4  name: crossplane-contrib-function-kcl
5spec:
6  package: xpkg.crossplane.io/crossplane-contrib/function-kcl:v0.11.2

Save the function as fn.yaml and apply it:

1kubectl apply -f fn.yaml

Check that Crossplane installed the function:

1kubectl get -f fn.yaml
2NAME                              INSTALLED   HEALTHY   PACKAGE                                                      AGE
3crossplane-contrib-function-kcl   True        True      xpkg.crossplane.io/crossplane-contrib/function-kcl:v0.11.2   6s

Configure the composition

A composition tells Crossplane what functions to call when you create or update a composite resource (XR).

Create a composition to tell Crossplane what to do when you create or update an App XR.

Create this composition to use YAML to configure Crossplane:

 1apiVersion: apiextensions.crossplane.io/v1
 2kind: Composition
 3metadata:
 4  name: app-yaml
 5spec:
 6  compositeTypeRef:
 7    apiVersion: example.crossplane.io/v1
 8    kind: App
 9  mode: Pipeline
10  pipeline:
11  - step: create-deployment-and-service
12    functionRef:
13      name: crossplane-contrib-function-patch-and-transform
14    input:
15      apiVersion: pt.fn.crossplane.io/v1beta1
16      kind: Resources
17      resources:
18      - name: deployment
19        base:
20          apiVersion: apps/v1
21          kind: Deployment
22          spec:
23            replicas: 2
24            template:
25              spec:
26                containers:
27                - name: app
28                  ports:
29                  - containerPort: 80
30        patches:
31        - type: FromCompositeFieldPath
32          fromFieldPath: metadata.name
33          toFieldPath: metadata.labels[example.crossplane.io/app]
34        - type: FromCompositeFieldPath
35          fromFieldPath: metadata.name
36          toFieldPath: spec.selector.matchLabels[example.crossplane.io/app]
37        - type: FromCompositeFieldPath
38          fromFieldPath: metadata.name
39          toFieldPath: spec.template.metadata.labels[example.crossplane.io/app]
40        - type: FromCompositeFieldPath
41          fromFieldPath: spec.image
42          toFieldPath: spec.template.spec.containers[0].image
43        - type: ToCompositeFieldPath
44          fromFieldPath: status.availableReplicas
45          toFieldPath: status.replicas
46        readinessChecks:
47        - type: MatchCondition
48          matchCondition:
49            type: Available
50            status: "True"
51      - name: service
52        base:
53          apiVersion: v1
54          kind: Service
55          spec:
56            ports:
57            - protocol: TCP
58              port: 8080
59              targetPort: 80
60        patches:
61        - type: FromCompositeFieldPath
62          fromFieldPath: metadata.name
63          toFieldPath: metadata.labels[example.crossplane.io/app]
64        - type: FromCompositeFieldPath
65          fromFieldPath: metadata.name
66          toFieldPath: spec.selector[example.crossplane.io/app]
67        - type: ToCompositeFieldPath
68          fromFieldPath: spec.clusterIP
69          toFieldPath: status.address
70        readinessChecks:
71        - type: NonEmpty
72          fieldPath: spec.clusterIP

Create this composition to use templated YAML to configure Crossplane:

 1apiVersion: apiextensions.crossplane.io/v1
 2kind: Composition
 3metadata:
 4  name: app-templated-yaml
 5spec:
 6  compositeTypeRef:
 7    apiVersion: example.crossplane.io/v1
 8    kind: App
 9  mode: Pipeline
10  pipeline:
11  - step: create-deployment-and-service
12    functionRef:
13      name: crossplane-contrib-function-go-templating
14    input:
15      apiVersion: gotemplating.fn.crossplane.io/v1beta1
16      kind: GoTemplate
17      source: Inline
18      inline:
19        template: |
20          ---
21          apiVersion: apps/v1
22          kind: Deployment
23          metadata:
24            annotations:
25              gotemplating.fn.crossplane.io/composition-resource-name: deployment
26              {{ if eq (.observed.resources.deployment | getResourceCondition "Available").Status "True" }}
27              gotemplating.fn.crossplane.io/ready: "True"
28              {{ end }}
29            labels:
30              example.crossplane.io/app: {{ .observed.composite.resource.metadata.name }}
31          spec:
32            replicas: 2
33            selector:
34              matchLabels:
35                example.crossplane.io/app: {{ .observed.composite.resource.metadata.name }}
36            template:
37              metadata:
38                labels:
39                  example.crossplane.io/app: {{ .observed.composite.resource.metadata.name }}
40              spec:
41                containers:
42                - name: app
43                  image: {{ .observed.composite.resource.spec.image }}
44                  ports:
45                  - containerPort: 80
46          ---
47          apiVersion: v1
48          kind: Service
49          metadata:
50            annotations:
51              gotemplating.fn.crossplane.io/composition-resource-name: service
52              {{ if (get (getComposedResource . "service").spec "clusterIP") }}
53              gotemplating.fn.crossplane.io/ready: "True"
54              {{ end }}
55            labels:
56              example.crossplane.io/app: {{ .observed.composite.resource.metadata.name }}
57          spec:
58            selector:
59              example.crossplane.io/app: {{ .observed.composite.resource.metadata.name }}
60            ports:
61            - protocol: TCP
62              port: 8080
63              targetPort: 80
64          ---
65          apiVersion: example.crossplane.io/v1
66          kind: App
67          status:
68            replicas: {{ get (getComposedResource . "deployment").status "availableReplicas" | default 0 }}
69            address: {{ get (getComposedResource . "service").spec "clusterIP" | default "" | quote }}          

Create this composition to use Python to configure Crossplane:

 1apiVersion: apiextensions.crossplane.io/v1
 2kind: Composition
 3metadata:
 4  name: app-python
 5spec:
 6  compositeTypeRef:
 7    apiVersion: example.crossplane.io/v1
 8    kind: App
 9  mode: Pipeline
10  pipeline:
11  - step: create-deployment-and-service
12    functionRef:
13      name: crossplane-contrib-function-python
14    input:
15      apiVersion: python.fn.crossplane.io/v1beta1
16      kind: Script
17      script: |
18        def compose(req, rsp):
19            observed_xr = req.observed.composite.resource
20
21            rsp.desired.resources["deployment"].resource.update({
22                "apiVersion": "apps/v1",
23                "kind": "Deployment",
24                "metadata": {
25                  "labels": {"example.crossplane.io/app": observed_xr["metadata"]["name"]},
26                },
27                "spec": {
28                    "replicas": 2,
29                    "selector": {"matchLabels": {"example.crossplane.io/app": observed_xr["metadata"]["name"]}},
30                    "template": {
31                      "metadata": {
32                        "labels": {"example.crossplane.io/app": observed_xr["metadata"]["name"]},
33                      },
34                      "spec": {
35                        "containers": [{
36                          "name": "app",
37                          "image": observed_xr["spec"]["image"],
38                          "ports": [{"containerPort": 80}]
39                        }],
40                      },
41                    },
42                },
43            })
44
45            observed_deployment = req.observed.resources["deployment"].resource
46            if "status" in observed_deployment:
47              if "availableReplicas" in observed_deployment["status"]:
48                rsp.desired.composite.resource.get_or_create_struct("status")["replicas"] = observed_deployment["status"]["availableReplicas"]
49              if "conditions" in observed_deployment["status"]:
50                for condition in observed_deployment["status"]["conditions"]:
51                  if condition["type"] == "Available" and condition["status"] == "True":
52                    rsp.desired.resources["deployment"].ready = True
53
54            rsp.desired.resources["service"].resource.update({
55                "apiVersion": "v1",
56                "kind": "Service",
57                "metadata": {
58                  "labels": {"example.crossplane.io/app": observed_xr["metadata"]["name"]},
59                },
60                "spec": {
61                  "selector": {"example.crossplane.io/app": observed_xr["metadata"]["name"]},
62                  "ports": [{"protocol": "TCP", "port": 8080, "targetPort": 80}],
63                },
64            })
65
66            observed_service = req.observed.resources["service"].resource
67            if "spec" in observed_service and "clusterIP" in observed_service["spec"]:
68              rsp.desired.composite.resource.get_or_create_struct("status")["address"] = observed_service["spec"]["clusterIP"]
69              rsp.desired.resources["service"].ready = True        
Tip

You can write your own function in Python.

It’s a good idea to write your own function for larger configurations. When you write your own function you can write multiple files of Python. You don’t embed the Python in YAML, so it’s easier to use a Python IDE.

Read the guide to writing a composition function in Python.

Create this composition to use KCL to configure Crossplane:

 1apiVersion: apiextensions.crossplane.io/v1
 2kind: Composition
 3metadata:
 4  name: app-kcl
 5spec:
 6  compositeTypeRef:
 7    apiVersion: example.crossplane.io/v1
 8    kind: App
 9  mode: Pipeline
10  pipeline:
11  - step: create-deployment-and-service
12    functionRef:
13      name: crossplane-contrib-function-kcl
14    input:
15      apiVersion: krm.kcl.dev/v1alpha1
16      kind: KCLInput
17      spec:
18        source: |
19          observed_xr = option("params").oxr
20
21          _desired_deployment = {
22            apiVersion = "apps/v1"
23            kind = "Deployment"
24            metadata = {
25              annotations = {
26                "krm.kcl.dev/composition-resource-name" = "deployment"
27              }
28              labels = {"example.crossplane.io/app" = observed_xr.metadata.name}
29            }
30            spec = {
31              replicas = 2
32              selector.matchLabels = {"example.crossplane.io/app" = observed_xr.metadata.name}
33              template = {
34                metadata.labels = {"example.crossplane.io/app" = observed_xr.metadata.name}
35                spec.containers = [{
36                  name = "app"
37                  image = observed_xr.spec.image
38                  ports = [{containerPort = 80}]
39                }]
40              }
41            }
42          }
43
44          observed_deployment = option("params").ocds["deployment"]?.Resource
45          if any_true([c.type == "Available" and c.status == "True" for c in observed_deployment?.status?.conditions or []]):
46            _desired_deployment.metadata.annotations["krm.kcl.dev/ready"] = "True"
47
48          _desired_service = {
49            apiVersion = "v1"
50            kind = "Service"
51            metadata = {
52              annotations = {
53                "krm.kcl.dev/composition-resource-name" = "service"
54              }
55              labels = {"example.crossplane.io/app" = observed_xr.metadata.name}
56            }
57            spec = {
58              selector = {"example.crossplane.io/app" = observed_xr.metadata.name}
59              ports = [{protocol = "TCP", port = 8080, targetPort = 80}]
60            }
61          }
62
63          observed_service = option("params").ocds["service"]?.Resource
64          if observed_service?.spec?.clusterIP:
65            _desired_service.metadata.annotations["krm.kcl.dev/ready"] = "True"
66            
67          _desired_xr = {
68            **option("params").dxr
69
70            status.address = observed_service?.spec?.clusterIP or ""
71            status.replicas = observed_deployment?.status?.availableReplicas or 0
72          }
73
74          items = [_desired_deployment, _desired_service, _desired_xr]          

Save the composition as composition.yaml and apply it:

1kubectl apply -f composition.yaml
Note

A composition can include multiple functions.

Functions can change the results of earlier functions in the pipeline. Crossplane uses the result returned by the last function.

Use the custom resource

Crossplane now understands App custom resources.

Create an App:

1apiVersion: example.crossplane.io/v1
2kind: App
3metadata:
4  namespace: default
5  name: my-app
6spec:
7  image: nginx

Save the App as app.yaml and apply it:

1kubectl apply -f app.yaml

Check that the App is ready:

1kubectl get -f app.yaml
2NAME     SYNCED   READY   COMPOSITION   AGE
3my-app   True     True    app-yaml      56s
Note

The COMPOSITION column shows what composition the App is using.

You can create multiple compositions for each kind of XR. Read the XR page to learn how to select which composition Crossplane uses.

Check that Crossplane created a Deployment and a Service:

1kubectl get deploy,service -l example.crossplane.io/app=my-app
2NAME                           READY   UP-TO-DATE   AVAILABLE   AGE
3deployment.apps/my-app-2r2rk   2/2     2            2           11m
4
5NAME                   TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
6service/my-app-xfkzg   ClusterIP   10.96.148.56   <none>        8080/TCP   11m
Tip
Use kubectl edit -f app.yaml to edit the App’s image. Crossplane updates the Deployment’s image to match.

Delete the App.

1kubectl delete -f app.yaml

When you delete the App, Crossplane deletes the Deployment and Service.

Next steps

Managed resources (MRs) are ready-made Kubernetes custom resources.

Crossplane has an extensive library of managed resources you can use to manage almost any cloud provider, or cloud native software.

Get started with managed resources to learn more about them.

You can use MRs with composition. Try updating your App composition to include an MR.