Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 879
aks Avatar asked Jun 23 '17 01:06

aks


People also ask

How do I set the namespace in Kubernetes Deployment?

One way is to set the “namespace” flag when creating the resource: Loading... You can also specify a Namespace in the YAML declaration. If you specify a namespace in the YAML declaration, the resource will always be created in that namespace.

How do you create a pod in a namespace in Kubernetes?

To create a pod using the nginx image, run the command kubectl run nginx --image=nginx --restart=Never . This will create a pod named nginx, running with the nginx image on Docker Hub. And by setting the flag --restart=Never we tell Kubernetes to create a single pod rather than a Deployment.


2 Answers

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)
}
like image 178
Eric Tune Avatar answered Sep 24 '22 18:09

Eric Tune


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{})
like image 42
ikandars Avatar answered Sep 26 '22 18:09

ikandars