Customizing Output Fields with operator-sdk and additionalPrinterColumns

Kubernetes Operator-SDK CustomResourceDefinition additionalPrinterColumns get fields

2 min read | by Jordi Prats

When writing a custom Kubernetes operator using operator-sdk we might want to change the fields are show when running kubectl get:

$ kubectl get example NAME AGE demo 4h20m 

To do so, we'll need to add the additionalPrinterColumns field the the CustomResourceDefinition, but since we are using operator-sdk to take care of this, we'll need to use some annotations in the resource definition file.

The annotation we'll need to use is +kubebuilder:printcolumn, on which we'll need specify it's name, json-path and description:

//+kubebuilder:object:root=true //+kubebuilder:subresource:status //+kubebuilder:resource:scope=Cluster //+kubebuilder:printcolumn:name="ID",type="integer",JSONPath=".spec.exampleID",description="example ID" // example is the Schema for the examples API type Example struct {  metav1.TypeMeta `json:",inline"`  metav1.ObjectMeta `json:"metadata,omitempty"`  Spec ExampleSpec `json:"spec"`  Status ExampleStatus `json:"status,omitempty"` } 

This annotations is going to make operator-sdk to add it as an additionalPrinterColumns in the CRD definition:

--- apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata:  annotations:  controller-gen.kubebuilder.io/version: v0.10.0  creationTimestamp: null  name: examples.pet2cattle.com spec:  group: pet2cattle.com  names:  kind: Example  listKind: ExampleList  plural: examples  singular: example  scope: Cluster  versions:  - additionalPrinterColumns:  - description: Example ID  jsonPath: .spec.exampleID  name: ID  type: integer (...) 

Once ready, we'll need to install the new definition into the cluster:

make install 

Once applied, we'll be able to see the custom fields using kubectl get as usual:

$ kubectl get example NAME ID demo 1234 

We can check what other options we can use in the kubebuilder documentation on CRD generation and on controller-gen.


Posted on 15/05/2023