I am writing a command line tool in Go which will perform an action based on the existence of a particular pod on a k8s
cluster, in a specific namespace.
I could do via command line (shell) invocations within my go
program something like
kubectl get pods -n mynapespace l app=myapp
or in case I am not certain about the labels, something even less elegant as:
kubectl get pods -n mynapespace | grep -i somepatternIamcertainabout
However, given that I am using the k8s native language (Go) I was wondering whether there might be a more Go native/specific way of making such an inquiry to the k8s api server, without resorting to shell invocations from within my cli tool.
The kubectl utility is just a convenience wrapper that talks to the Kubernetes API using bog standard HTTP. The Go standard library has a great http package. The perfect fit for what you're trying to accomplish.
In fact, you could just use this official client package from the Kubernetes project itself.
However, given that I am using the k8s native language (Go) I was wondering whether there might be a more Go native/specific way of making such an inquiry to the k8s api server, without resorting to shell invocations from within my cli tool.
If you want to talk with k8s cluster in your programs written in go without resorting to shell invocations, client-go library is the way to go. It contains everything you need to query your k8s api server in your go programs.
What's included
- The
kubernetes
package contains the clientset to access Kubernetes API.- The
discovery
package is used to discover APIs supported by a Kubernetes API server.- The
dynamic
package contains a dynamic client that can perform generic operations on arbitrary Kubernetes API objects.- The
plugin/pkg/client/auth
packages contain optional authentication plugins for obtaining credentials from external sources.- The
transport
package is used to set up auth and start a connection.- The
tools/cache
package is useful for writing controllers.