Tech/Notes on kubernetes programming in Go
It's been a long time since I wrote Go code. Lately I've been picking that up again because I wanted to write some code to interface with Kubernetes.
In this page I'll be collecting random notes and snippets about that.
Note: as I'm not a professional Go programmer, please take these notes with the appropriate grain of salt.
Quick links
- client-go main documentation page
- golang standard library documentation page
Snippets
Loading config for a specific context
Loading in-cluster config is easy, but loading config from the local kubeconfig file for a specific context is slightly convoluted.
Here is a quick snippet:
// https://pkg.go.dev/k8s.io/client-go
package main
import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
func configForContext(kubeconfigPath, ctx string) (*rest.Config, error) {
loading := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath}
overrides := &clientcmd.ConfigOverrides{CurrentContext: ctx}
cc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loading, overrides)
return cc.ClientConfig()
}
Why do i need this?
Multiple reason. The first one: i don't have a default context set in my kubeconfig file. I think it's a dangerous default to have and it makes it easy to run commands against the wrong cluster. Moreover, if i'm writing a tool, it might be a kubectl plugin and in that case, i'd like to be able to point that to a specific context by passing --context and --namespace as it's customary with other kubectl commands.
