how to implement `kubectl create -f pod.yaml` using kubernetes go client library

9/18/2017

I have a folder with name "myspec" which has some kube-spec files , let's say

  • pod.yaml , service.yaml, secret.yaml

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.

-- user3190479
kubernetes
kubernetes-go-client

2 Answers

10/28/2018

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
}
-- jayunit100
Source: StackOverflow

9/27/2017

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
}
-- user3190479
Source: StackOverflow