Skip to content

Instantly share code, notes, and snippets.

@noqcks
Created December 6, 2018 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noqcks/5a458d4bc311c96934833651647854ab to your computer and use it in GitHub Desktop.
Save noqcks/5a458d4bc311c96934833651647854ab to your computer and use it in GitHub Desktop.
Kubernetes go-client deployment patching.
package main
// the equivalent of kubectl set image deployment/api api="image"
import (
"fmt"
patchtype "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"os"
"path/filepath"
"reflect"
)
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
func context(context string) (*rest.Config, error) {
home := homeDir()
kubeconfig := filepath.Join(home, ".kube", "config")
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
&clientcmd.ConfigOverrides{
CurrentContext: context,
}).ClientConfig()
}
func main() {
// switch context
config, err := context("cluster-name")
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
const patchjson = `{
"spec": {
"template": {
"spec": {
"containers": [
{ "name": "app", "image": "<image name>" }
]
}
}
}
}
`
deployment, err := clientset.AppsV1beta1().Deployments("default").Patch(
"app",
patchtype.StrategicMergePatchType,
[]byte(patchjson))
fmt.Println(deployment)
fmt.Println(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment