What’s client-go ?
Where’s client-go ?
- you can find it in
kubernetes/kubernetes/staging
directory and published by bot tok8s.io/client-go
, kubernetes also uses client-go. it’s interesting if you seeclient-go
from kubernetes vendor, it has symlinks tokubernetes/kubernetes/staging
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)
- There are two ways to talk to cluster using any go program:
- When your program runs on kubernetes, it uses service account token inside the pods
/var/run/secrets/kubernetes.io/serviceaccount
for 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.
import "k8s.io/client-go/tools/clientcmd"
- 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 eitherKUBERNETES_MASTER
environment variable or simplyhttp://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_HOST
and KUBERNETES_SERVICE_PORT
environment variables (which are injected into every pod) and service token to generate the config.
config
has all necessary information to talk to the cluster from anywhere :) If you check struct defination here
it has fields like Host, APIPath
, Username, Password, BearerToken
, etc which are needed to talk to cluster
- If you explore more, you will see
clientcmd/api
hasConfig
(Kind: Config
) struct which is API resource for kubeconfig, code is here