CustomResource Spec value returning null

11/27/2019

Hi I have created following CustomResourceDefinition - crd.yaml

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: test.demo.k8s.com
  namespace: testns
spec:
  group: demo.k8s.com
  versions:
    - name: v1
      served: true
      storage: true
  scope: Namespaced
  names:
    plural: testpod
    singular: testpod
    kind: testpod

The corresponding resource is as below - cr.yaml

kind: testpod
metadata:
  name: testpodcr
  namespace: testns
spec:
  containers:
  - name: testname
    image: test/img:v5.16
    env:
    - name: TESTING_ON
      valueFrom:
        configMapKeyRef:
          name: kubernetes-config
          key: type
    volumeMounts:
    - name: testvol
      mountPath: "/test/vol"
      readOnly: true

When i use client-go program to fetch the spec value of cr object 'testpodcr' The value comes as null.

func (c *TestConfigclient) AddNewPodForCR(obj *TestPodConfig) *v1.Pod {
    log.Println("logging obj \n", obj.Name) // Prints the name as testpodcr
    log.Println("Spec value: \n", obj.Spec) //Prints null

    dep := &v1.Pod{
        ObjectMeta: meta_v1.ObjectMeta{
            //Labels: labels,
            GenerateName: "test-pod-",
        },
        Spec: obj.Spec,
    }

    return dep
}

Can anyone please help in figuring this out why the spec value is resulting to null

-- PREETI BANSAL
kubernetes
kubernetes-custom-resources

1 Answer

11/27/2019

There is an error with Your crd.yaml file. I am getting the following error:

$ kubectl apply -f crd.yaml 
The CustomResourceDefinition "test.demo.k8s.com" is invalid: metadata.name: Invalid value: "test.demo.k8s.com": must be spec.names.plural+"."+spec.group

In Your configuration the name: test.demo.k8s.com does not match plurar: testpod found in spec.names.

I modified Your crd.yaml and now it works:

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: testpods.demo.k8s.com
  namespace: testns
spec:
  group: demo.k8s.com
  versions:
    - name: v1
      served: true
      storage: true
  scope: Namespaced
  names:
    plural: testpods
    singular: testpod
    kind: Testpod
$ kubectl apply -f crd.yaml 
customresourcedefinition.apiextensions.k8s.io/testpods.demo.k8s.com created

After that Your cr.yaml also had to be fixed:

apiVersion: "demo.k8s.com/v1"
kind: Testpod
metadata:
  name: testpodcr
  namespace: testns
spec:
  containers:
  - name: testname
    image: test/img:v5.16
    env:
    - name: TESTING_ON
      valueFrom:
        configMapKeyRef:
          name: kubernetes-config
          key: type
    volumeMounts:
    - name: testvol
      mountPath: "/test/vol"
      readOnly: true

After that I created namespace testns and finally created Testpod object successfully:

$ kubectl create namespace testns
namespace/testns created
$ kubectl apply -f cr.yaml 
testpod.demo.k8s.com/testpodcr created
-- Piotr Malec
Source: StackOverflow