Created
December 6, 2018 15:53
-
-
Save noqcks/5a458d4bc311c96934833651647854ab to your computer and use it in GitHub Desktop.
Kubernetes go-client deployment patching.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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