Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 497
C. Damoc Avatar asked Dec 01 '25 02:12

C. Damoc


1 Answers

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

like image 66
C. Damoc Avatar answered Dec 03 '25 02:12

C. Damoc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!