Nowadays, I am learning advance
golang, along with that knowledge, I am trying to understand kubernetes in more depth. I found
client-go as goto thing to explore & learn things. I am also putting respective client-go code links wherever needed.
What’s client-go ?
Simple, golang client library for talking to kubernetes cluster
Where’s client-go ?
- you can find it in
kubernetes/kubernetes/stagingdirectory and published by bot to
k8s.io/client-go, kubernetes also uses client-go. it’s interesting if you see
client-gofrom kubernetes vendor, it has symlinks to
In this Adventure, very first step is to see how to connect to API Server :)
Connecting to API Server
There are two ways to talk to cluster using any go program:
outside cluster: if your program is standalone and if you have either kubeconfig file or master URL.
inside cluster: if your program is supposed to run on kubernetes (for example, controller)
- When your program runs on kubernetes, it uses service account token inside the pods
/var/run/secrets/kubernetes.io/serviceaccountfor auth and tls stuff.
Connecting to cluster using client-go
- clientcmd holds the required code to configuring connection to the cluster using kubeconfig as well as about modification to kubeconfig. Code reference here.
- if you have master URL and kubeconfig both:
config, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
- if you have only have kubeconfig file:
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
- If you are running program on kubernetes, you don’t need to provided parameters, it will automatically fetch details using serviceaccount tokens:
config, err := clientcmd.BuildConfigFromFlags("", "")
If you don’t provide any parameters, it fallbacks to
InClusterConfig, even if it fails, it fallbacks to default configs which is either
KUBERNETES_MASTERenvironment variable or simply
http://localhost:8080, code reference here.
Directly use this (even above way internally uses this), Code Ref here.
import "k8s.io/client-go/rest" ... config,err := rest.InClusterConfig()
This method basically gets
KUBERNETES_SERVICE_PORT environment variables (which are injected into every pod) and service token to generate the config.
confighas all necessary information to talk to the cluster from anywhere :) If you check struct defination here
it has fields like
Username, Password, BearerToken, etc which are needed to talk to cluster
- If you explore more, you will see
Kind: Config) struct which is API resource for kubeconfig, code is here