Build an AI‑Powered Kubernetes CLI with Go, Cobra, and OpenAI Function Calling
This tutorial shows how to combine Kubernetes client‑go, the Cobra CLI framework, and OpenAI function calling in Go to create an interactive command‑line assistant that can generate YAML, deploy resources, query objects, and delete items in a Kubernetes cluster.
Interacting with Kubernetes
Kubernetes clusters are the core infrastructure in cloud‑native environments; the standard command‑line tool kubectl works for manual tasks, while programmatic access requires the official Go client library client-go. client-go provides a Clientset for core, apps, networking APIs, an Informer for watching resource changes, a Lister for cached reads, a Workqueue for asynchronous processing, and more.
Example: list all Pods in the current context.
mkdir k8s-pod-list && cd k8s-pod-list
go mod init k8s-pod-list
go get k8s.io/client-go/kubernetes
go get k8s.io/client-go/tools/clientcmd
go get k8s.io/client-go/rest
package main
import (
"context"
"fmt"
"log"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
func main() {
var kubeconfig string
if home := homedir.HomeDir(); home != "" {
kubeconfig = filepath.Join(home, ".kube", "config")
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d pods:
", len(pods.Items))
for _, pod := range pods.Items {
fmt.Printf("Namespace: %s, Pod: %s
", pod.Namespace, pod.Name)
}
}The client-go library is the foundation for building controllers, operators, or any automation that talks to the Kubernetes API.
Cobra library overview
Cobrais the most popular Go library for building modern CLI applications. It powers projects such as Kubectl , Helm , and Docker CLI.
Command : defines a command and its sub‑commands, e.g. app server or app config set.
Flags : global and local flags like --config or -v.
Args : positional arguments, e.g. kubectl get pod.
Automatic help generation and shell completion.
Example: create a simple hello command.
&cobra.Command{
Use: "hello",
Short: "Print a greeting",
Long: `A simple command that says hello`,
Run: func(cmd *cobra.Command, args []string) {
if name == "" {
name = "World"
}
fmt.Printf("Hello, %s!
", name)
},
}Flags can be added with StringVarP, BoolVar, IntVar, etc.
Building the Chat K8s CLI tool
The goal is a CLI named k8scopilot that can:
Enter an interactive chat mode: k8scopilot ask chatgpt.
Deploy resources (e.g., a Deployment with the nginx image).
Query resources in a namespace.
Delete resources.
Project setup:
mkdir k8scopilot && cd k8scopilot
go mod init
cobra-cli initAdd commands:
cobra-cli add ask
cobra-cli add chatgpt -p "askCmd"Implement startChat to read user input, exit on exit, and forward the text to the OpenAI client.
func startChat() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("I am K8S Copilot, ask me K8S questions")
for {
fmt.Print("> ")
if scanner.Scan() {
input := scanner.Text()
if input == "exit" {
fmt.Println("Exiting chat")
break
}
if input == "" {
continue
}
fmt.Println("You entered:", input)
}
}
}Wrap the OpenAI SDK in utils/openai.go to create a client and a SendMessage method that calls ChatCompletion with GPT‑4oMini.
Define three function definitions for the model: generateAndDeployResource: generate YAML from user input and apply it. queryResource: list resources of a given type in a namespace. deleteResource: remove a specific resource.
Function‑calling logic sends the user prompt, receives a tool call, unmarshals the arguments, and invokes the corresponding Go function.
Implementation of the three functions uses the utils.ClientGo wrapper (which builds a Clientset, DynamicClient, and DiscoveryClient) to interact with the cluster, map GVK to GVR, and perform create, list, or delete operations.
Finally, processInput creates the OpenAI client and calls the function‑calling helper; startChat prints the response.
Tips: the article is only a starting point; building a production‑grade tool requires further work.
Conclusion
The tutorial demonstrates how to combine AI (OpenAI function calling) with Kubernetes automation (client‑go) and a Go CLI framework (Cobra) to create an intelligent assistant that understands natural‑language commands and performs real cluster operations.
Ops Development Stories
Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
