I have a folder with name "myspec" which has some kube-spec files , let's say
when I run the command "kubectl create -f myspec" it creates everything , pod , service and secret.
Now I wish to perform the same thing using kubernetes go client library.
I believe the previous poster, meant to post This:
1) You first convert the string to bytes.
2) Then serialize it to a pod.
3) Then create the pod like any other object.
This can be done, without loss of generality, for Pods, Services, ReplicationControllers, Deployments, ConfigMaps, Secrets, and any other kubernetes API object.
example
func CreatePodFromYaml(podAsYaml string, ns string) error {
var p v1.Pod
err := json.Unmarshal([]byte(podAsYaml), &p)
if err != nil {
return err
}
pod, poderr := kubernetesConfig().CoreV1().Pods(ns).Create(&p)
if poderr != nil {
return poderr
}
fmt.Printf("Created Pod %q.\n", pod.GetObjectMeta().GetName())
return nil
}
To compile this code, you'll also need to make the kubernetesConfig object:
func kubernetesConfig() *kubernetes.Clientset {
config, err := clientcmd.BuildConfigFromFlags("", "/$HOME/.kube/config")
if err != nil {
fmt.Println(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println(err.Error())
}
return clientset
}
I am able to create the pod using kubernetes go client library , i am passing json file and namespace name to the function and it unmarhshal to the v1.Pod object and call the create function as below
func createPod(b []byte, ns string) {
var p v1.Pod.Name
err := json.Unmarshal(b, &p)
if err != nil {
}
pod, poderr := kubernetesConfig().CoreV1().Pods(ns).Create(&p)
pod.
if poderr != nil {
fmt.Println(poderr.Error())
} else {
fmt.Printf("Created Pod %q.\n", pod.GetObjectMeta().GetName())
}
}
func kubernetesConfig() *kubernetes.Clientset {
config, err := clientcmd.BuildConfigFromFlags("", "/$HOME/.kube/config")
if err != nil {
fmt.Println(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println(err.Error())
}
return clientset
}