Sub topic 4
Creating and inspecting custom resources
This chapter assumes you can use kubectl apply and kubectl get, and that you have a cluster where you can install a CRD (kind or minikube is fine). It uses the WebApp CRD from the previous chapter, saved as webapp-crd.yaml.
Register the type
A custom resource can't exist until the API server knows its type. Apply the CRD and wait until it is established:
kubectl apply -f webapp-crd.yaml
kubectl wait --for=condition=Established crd/webapps.example.com --timeout=30s
kubectl api-resources --api-group=example.comThe last command lists webapps with kind WebApp and NAMESPACED set to true. From now on the API server serves /apis/example.com/v1/namespaces/<ns>/webapps, and kubectl treats webapps like any built-in resource.
Create an instance
A custom resource (CR) is an instance of that type. Save this as hello.yaml:
apiVersion: example.com/v1
kind: WebApp
metadata:
name: hello
namespace: default
spec:
image: nginx:1.27This manifest leaves out replicas on purpose. Apply it and read the object back:
kubectl apply -f hello.yaml
kubectl get webapps
kubectl get webapp hello -o yamlThe YAML output shows spec.replicas: 1. The API server filled in the schema default when it stored the object. You can use the singular name (webapp) or the plural (webapps) interchangeably.
Inspect the details
kubectl describe webapp hello shows metadata, spec, status and events. The status block is empty at this point. The CRD enables the status subresource, but nothing is writing to it yet.
Because the schema is part of the API, kubectl can document it:
kubectl explain webapp.spec
kubectl explain webapp.spec.replicasWhat the API server rejects
The schema is enforced on every write. Try an object with no image:
kubectl apply -f - <<'EOF'
apiVersion: example.com/v1
kind: WebApp
metadata:
name: bad
spec:
replicas: -1
EOFThe request fails with errors such as spec.image: Required value and spec.replicas: Invalid value: -1. Nothing is stored.
Nothing happens yet
Run kubectl get deployments. There is no hello Deployment. A custom resource is only stored data. The API server validates it, persists it in etcd and serves it, but it doesn't act on it. Creating Deployments from WebApp objects is the job of a controller, which later chapters build.
Delete the object with kubectl delete webapp hello. Deleting the CRD removes every custom resource of that type, so do that deliberately.
Exercise
You apply a WebApp with spec.image set and no spec.replicas. What value does kubectl get webapp <name> -o yaml show for replicas, and why does it show that value even though no controller exists?
Show answer
It shows replicas: 1. Defaulting is part of structural schema handling in the API server. The server applies the default when it admits the object, before storing it, so no controller is needed.