How do i create a namespace using kubernetes go-client from running container inside a cluster
Asked Answered
I

2

8

I have a Kubernetes cluster and have a running container (X). From this container i want to create a new namespace, deploy a pod in this name space and spawn container(Y). I know kubernetes provides REST APIs. however, i am exploring goClient to do the same and not sure how to use namespace creation api.

Irk answered 23/6, 2017 at 1:28 Comment(0)
T
10
import (
    "github.com/golang/glog"
    "k8s.io/client-go/kubernetes"
    "k8s.io/kubernetes/pkg/api/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

clientConfig, err := config.createClientConfigFromFile()
if err != nil {
        glog.Fatalf("Failed to create a ClientConfig: %v. Exiting.", err)
}

clientset, err := clientset.NewForConfig(clientConfig)
if err != nil {
        glog.Fatalf("Failed to create a ClientSet: %v. Exiting.", err)
}

nsSpec := &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}

_, err := clientset.Core().Namespaces().Create(nsSpec)
}
Trilby answered 27/6, 2017 at 22:16 Comment(2)
createClientConfigFromFile() should find the service account token when run in a pod. If you have authorization turned on, you need to make sure the Pod's service account is authorized to create namespaces.Trilby
Core has been deprecated. Please update to use CoreV1 in the answer.Ellerd
P
9

This one is works for me:

clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    panic(err)
}

nsName := &corev1.Namespace{
    ObjectMeta: metav1.ObjectMeta{
        Name: "my-new-namespace",
    },
}

clientset.CoreV1().Namespaces().Create(context.Background(), nsName, metav1.CreateOptions{})
Peril answered 11/5, 2021 at 9:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.