Missing default value in nested field of kubernetes custom resource

12/29/2021

I have a Custom Resource Definition which has nested fields with default values (some boilerplate omitted for brevity):

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
spec:
  scope: Namespaced
  group: thismatters.stackoverflow
  names:
    kind: BadDefault
  versions:
  - name: v1alpha
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              regularThing:
                type: integer
                default: 6
              shouldDefault:
                type: object
                properties:
                  nestedThing:
                    type: integer
                    default: 12

Whenever I create a resource of this kind without specifying the shouldDefault object:

apiVersion: thismatters.stackoverflow/v1alpha
kind: BadDefault
metadata:
  name: blank-demo
spec: 
  regularThing: 7

The default value for .shouldDefault.nestedThing doesn't appear when the resource is described:

apiVersion: thismatters.stackoverflow/v1alpha
kind: BadDefault
metadata:
  name: blank-demo
spec: 
  regularThing: 7

If I update the resource with this manifest:

apiVersion: thismatters.stackoverflow/v1alpha
kind: BadDefault
metadata:
  name: blank-demo
spec: 
  regularThing: 7
  shouldDefault: {}

Then the nested field default value is populated when described:

apiVersion: thismatters.stackoverflow/v1alpha
kind: BadDefault
metadata:
  name: blank-demo
spec: 
  regularThing: 7
  shouldDefault:
    nestedThing: 12

Is there anything I can do in the CRD to remove the need for the shouldDefault: {} line in the resource manifest and have the default values populate in the nested fields?

My cluster is on Kubernetes version 1.19.

-- Thismatters
kubernetes
kubernetes-custom-resources

1 Answer

12/31/2021

Adding a default property to the shouldDefault object fixes this:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
spec:
  scope: Namespaced
  group: thismatters.stackoverflow
  names:
    kind: BadDefault
  versions:
  - name: v1alpha
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              regularThing:
                type: integer
                default: 6
              shouldDefault:
                type: object
                default: {}   #  <-- this was added
                properties:
                  nestedThing:
                    type: integer
                    default: 12
-- Thismatters
Source: StackOverflow