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
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: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:

kind: CustomResourceDefinition
  annotations: v0.10.0
  creationTimestamp: null
    kind: Example
    listKind: ExampleList
    plural: examples
    singular: example
  scope: Cluster
  - 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
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