![]() |
VOOZH | about |
We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.
Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.
Follow TNS on your favorite social media networks.
Become a TNS follower on LinkedIn.
Check out the latest featured and trending stories while you wait for your first TNS newsletter.
Key takeaways:
Running Kubernetes commands programmatically can feel overwhelming at first. You might find yourself shelling out to `kubectl` in scripts or trying to wrangle complex APIs just to list a few pods or apply a config. It’s not always clear where to start or how to do it cleanly in Golang (Go).
The good news? You don’t need to rely on shell hacks or guesswork. Go is the language Kubernetes itself is written in — and with the official `client-go` library, you can interact with your cluster directly, just like `kubectl` does.
Learn how to run core Kubernetes operations in Go. From setting up the client to handling authentication, parsing output and writing testable code, get a practical foundation to build your own tools and automations.
Go is one of the best languages for working with Kubernetes. In fact, Kubernetes itself is written in Go. That means you get first-class support and access to official client libraries when writing tools or automations.
Here are some key reasons to use Go for Kubernetes automation:
Before you can run Kubernetes commands in Go, you need to have a few tools and settings in place. These will ensure your Go code can connect to your cluster and perform actions safely. Here’s what you will need.
To write and run Go code, you need to have the Go toolchain installed. This includes the Go compiler, the `go` command line tool and support for modules (i.e., Go’s dependency management system).
Here’s why it’s important:
| 💡 | To check if Go is installed, run `go` version in your terminal. To initialize a module, use `go mod init <your-module-name>`. |
To interact with a Kubernetes cluster, your Go program needs access to a kubeconfig file. This file tells your code how to connect to the cluster and what credentials to use. Role-based access control (RBAC) is also important. It defines what actions your code is allowed to perform.
Here’s why this matters:
| 💡 | Make sure the user or service account you’re using has the right roles for the tasks you plan to automate. |
client-goTo run Kubernetes commands in Go, you need the official Go client library called `client-go`. This library gives your code the tools to connect to your cluster and work with Kubernetes resources. Here’s how you can add it to your project and load your cluster credentials.
First, you’ll need to add `client-go` to your Go module. We do it using the `go get` command, which pulls the library into your project and lets you use it in your code.
Use this command to fetch the latest version of the `client-go` library and add it to your `go.mod` file:
You may also need related packages depending on your setup:
These libraries help define and manage Kubernetes objects. After that, your `go.mod` file should include the dependencies, and you’re ready to start coding.
To connect to a Kubernetes cluster, `client-go` uses your kubeconfig file — the same file you use with `kubectl`. Here’s a basic example that loads your credentials and creates a client:
Here’s what this code does:
kubectl-Equivalent CommandsOnce you’ve set up your Go project with client-go, you can start performing the same tasks you’d normally do with kubectl — but programmatically. This is useful for building custom tools, automating workflows or writing controllers.
Below are examples of how to list, create and delete Kubernetes resources using Go.
Here’s how to list common resources in a specific namespace:
This is similar to running kubectl get pods, kubectl get deployments or kubectl get services.
You can create a new Kubernetes deployment (or other resources) using Go structs. Here’s a basic example for a deployment:
For updates, you can use Update() instead of Create(), typically after fetching and modifying the existing resource.
To delete a resource, you just call the delete method on the client:
This works the same way for deployments, services or other resources — just use the appropriate client group.
Sometimes, it’s easier or more flexible to run actual `kubectl` commands from your Go code, especially if you don’t need full control over the Kubernetes API or if you want to reuse familiar CLI behavior. This approach is helpful for quick scripts, automation or when you want to avoid dealing with complex Kubernetes types directly.
The os/exec package in Go lets you run shell commands, including `kubectl`. Here’s how you can use it:
This code runs kubectl get pods -n default and prints the result. It combines both stdout and stderr in case there’s an error. Before running this code, make sure `kubectl` is installed and available in your system’s PATH.
If you want to stream the output as the command runs — instead of waiting for it to finish — you can do this:
This approach is useful for commands like kubectl logs -f or kubectl exec where live output is important.
To interact with a Kubernetes cluster, your Go program needs proper authentication and permissions. Kubernetes supports different ways to authenticate depending on where your code is running — inside the cluster or outside of it. Below are the two most common approaches.
If your Go program runs inside a Kubernetes cluster (e.g., in a Pod), it can use a built-in service account for authentication.
Here’s how it works:
/var/run/secrets/kubernetes.io/serviceaccount/.Use this to set it up in your code:
You’ll also need to set proper RBAC roles or role bindings for the service account to control what it can access.
If your code runs outside the cluster, like on your laptop or CI/CD pipeline, you’ll typically use a kubeconfig file that holds your credentials.
client-go automatically reads this file when you use clientcmd.BuildConfigFromFlags.
This kubeconfig file can contain:
Here’s a quick example:
This setup is useful for developers testing locally or for automation tools interacting with Kubernetes securely.
Once you fetch Kubernetes resources using Go, you may want to display or export them in a readable format, such as YAML, JSON or custom views. This is helpful for debugging, logging or building CLI tools with output similar to `kubectl`. Below are two common ways to format Kubernetes objects in Go.
Kubernetes objects can be serialized into YAML or JSON using Go’s encoding libraries.
Use this code to convert them to JSON:
Here’s the code to convert them to YAML:
Both formats are useful when saving or displaying the full object definition.
If you want to print only specific fields, like kubectl get pods -o custom-columns, you can use Go templates.
Try this code:
This approach gives you full control over what gets printed and how. You can also use this technique to build scripts or tools with clean, user-friendly output.
When working with Kubernetes in Go, things won’t always go smoothly. Network hiccups, temporary unavailability or permission errors are common. That’s why it’s important to handle errors gracefully and retry when needed.
Retries help your app recover from transient issues, and backoff strategies make sure you’re not overloading the API by retrying too aggressively.
Here are some simple and effective strategies to consider:
err != nil and log the error details. This helps with debugging.k8s.io/apimachinery/pkg/util/wait make this easy.| ✅ | The Kubernetes Go client includes built-in helpers like wait.ExponentialBackoff() for retry logic. You can use them, too. |
Testing your Kubernetes code is key to avoiding surprises in production. Go makes it easy to write both unit and integration tests using the Kubernetes client libraries.
Unit tests check your logic without needing a real cluster. Integration tests run your code against a real (or simulated) Kubernetes cluster. Here’s how to handle both.
The `client-go` library provides a fake client you can use to mock Kubernetes interactions. This lets you test your code without needing a live cluster.
Kubernetes in Docker (KinD) is great for running real Kubernetes clusters locally for integration testing.
With KinD, you can:
Here’s how to go about it:
Tools like envtest and controller-runtime also help with integration tests in custom controllers.
If you’re building a CLI tool that interacts with Kubernetes, it’s important to go beyond just “working code.” Your tool should be reliable, user-friendly, and ready for real-world use.
Here are some best practices to follow:
--kubeconfig file or --context if they work with multiple clusters.--timeout flags and Ctrl+C to let users exit cleanly.--verbose or --debug flags for deeper insights during troubleshooting.--output=json or --output=yaml for scripting and automation.Following these best practices can turn a simple script into a robust tool that your team or community can rely on.
Go is a natural fit for Kubernetes automation. With the official client libraries, you can interact with clusters directly, build reliable CLI tools and handle complex tasks programmatically — all while keeping things fast and efficient.
Whether you’re managing resources, building custom controllers or writing internal tools, mastering these patterns will help you create more powerful and production-ready Kubernetes applications in Go.
Learn Go to take full control of your Kubernetes workflows and build tools that scale with your infrastructure.