kubernetes client-go error: an empty namespace may not be set during creation

7/19/2019

Programmatically creating a pod using the Kubernetes client-go gives me the following error: an empty namespace may not be set during creation

Started from this example: https://github.com/feiskyer/go-examples/blob/master/kubernetes/pod-create/pod.go

#go

handler := clientset.CoreV1().Pods("").PodInterface

pod := apiv1.Pod{
    TypeMeta: metav1.TypeMeta{
        Kind:       "Pod",
        APIVersion: "v1",
    },
    ObjectMeta: metav1.ObjectMeta{
        Name:      "my-pod",
        Namespace: "my-namespace",
    },
    Spec: apiv1.PodSpec{
        Containers: []apiv1.Container{
            {
                Name:  "my-container",
                Image: "my-container",
            },
        },
    },
}

result, err := handler.Create(pod)

Expectation: Pod is created.
Actual: Creation fails with k8s error: an empty namespace may not be set during creation

-- C. Damoc
client-go
kubernetes
namespaces

2 Answers

7/19/2019

is Namespace: "my-namespace" present in the cluster? if not, remove the entry. the pod gets created in default namespace

-- P Ekambaram
Source: StackOverflow

7/19/2019

To fix the issue above, I had to specify the namespace in the following line:

handler := clientset.CoreV1().Pods("my-namespace").PodInterface

This fixed the error, because it is not allowed to create a pod outside an namespace. So, even if the namespace was provided in the pod object, it also must be specified 'as a flag'.

So, it should be similar to something like (see the flag --namespace in the command):

#my-pod-file-definition.yaml
----------------------------
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: my-namespace
spec:
  containers:
  - name: my-container
    image: my-image

kubectl apply -f my-pod-file-definition.yaml --namespace=my-namespace

-- C. Damoc
Source: StackOverflow