026 Project 26: Kubernetes Pod Lister

026 Build a Kubernetes Pod Lister

List pods across namespaces using client-go.

Setup

go mod init example.com/k8s-pods
go get k8s.io/client-go@latest

Full main.go

package main

import (
    "context"
    "flag"
    "fmt"
    "os"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
)

func main() {
    kubeconfig := flag.String("kubeconfig", os.Getenv("HOME")+"/.kube/config", "kubeconfig path")
    namespace := flag.String("n", "", "namespace (empty=all)")
    flag.Parse()

    cfg, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err)
    }
    cli, err := kubernetes.NewForConfig(cfg)
    if err != nil {
        panic(err)
    }

    ns := *namespace
    if ns == "" {
        ns = metav1.NamespaceAll
    }
    pods, err := cli.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})
    if err != nil {
        panic(err)
    }

    for _, p := range pods.Items {
        fmt.Printf("%s/%s\t%s\t%s\n", p.Namespace, p.Name, p.Status.Phase, p.Spec.NodeName)
    }
}

Step-by-Step Explanation

  1. Build Kubernetes client config from kubeconfig.
  2. Scope operations by namespace or resource type.
  3. Query or watch API objects.
  4. Extract actionable status fields.
  5. Return output and exit codes suitable for scripts and CI.

Code Anatomy

  • Setup phase creates client and context.
  • Query/watch phase pulls cluster state.
  • Presentation phase prints concise operational results.

Learning Goals

  • Use client-go safely and predictably.
  • Convert API objects into operator-facing insights.
  • Build automation-friendly cluster checks.