How to apply kubernetes workload

7/31/2019

I'm writing a Go program that will run in a kubernetes cluster.

I want the program to apply a kubernetes workload using a yaml (yaml in json format)

import (
    "encoding/json"
    "fmt"
    corev1 "k8s.io/api/core/v1"
)
var (
    workload = `{
        "apiVersion": "v1",
        "kind": "Pod",
        "metadata": {
            "name": "sleep",
        },
        "spec": {
            "containers": [
                {
                    "name": "sleep2",
                    "image": "tutum/curl",
                    "command": [
                        "/bin/sleep",
                        "infinity"
                    ],
                    "imagePullPolicy": "Always",
                    "env": [
                        {
                            "name": "ENV_VAR",
                            "value": "i/love/sleeping"
                        }
                    ]
                }
            ]
        }
    }`
)

func ApplyWorkload(){
    pod := corev1.Pod{}
    if err := json.Unmarshal(workload, &pod); err != nil {
        fmt.Errorf("%v", err)
    }
    // apply pod here

}

How can I apply the workload in Go?

What can I do if my workload is a deployment, should I run a switch-case for each possible workload?

-- David Wer
go
kubernetes

1 Answer

7/31/2019

You need kubernetes client-go to create pod or deployment.

import "k8s.io/client-go/kubernetes"

clientset, err := kubernetes.NewForConfig(cfg) // cfg is  the *config 

//    .... ... .. create deployment
result, err := clientset.AppsV1().Deployments(namespaceName).Create(deployment) // deployment object

//    ... .... ... create pod
result, err := clientset.CoreV1().Pods(namespaceName).Create(Pod) // Pod object
-- Kamol Hasan
Source: StackOverflow