Retrieving Specific Pod Details using Go
// examples/chapter-2/get-pod-details/main.go
package main
import (
"context"
"flag"
"fmt"
"log"
"path/filepath"
"strings" // For joining port details
// Kubernetes API imports
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors" // For IsNotFound check
// client-go imports
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
func main() {
// --- Setup Kubeconfig and Flags ---
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
// Flags for target Pod name and namespace
podName := flag.String("pod", "", "name of the pod to inspect")
namespace := flag.String("namespace", "default", "namespace of the pod")
flag.Parse()
// Validate required flags
if *podName == "" {
log.Fatal("Error: --pod flag is required")
}
// --- Load Config and Create Clientset ---
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
log.Fatalf("Error building kubeconfig: %s", err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalf("Error creating clientset: %s", err.Error())
}
// --- Get Specific Pod ---
fmt.Printf("Attempting to get Pod '%s' in namespace '%s'...\n", *podName, *namespace)
podsClient := clientset.CoreV1().Pods(*namespace)
// Use the Get method
pod, err := podsClient.Get(context.TODO(), *podName, metav1.GetOptions{})
// --- Handle Errors (especially NotFound) ---
if err != nil {
if k8serrors.IsNotFound(err) {
log.Fatalf("Pod '%s' not found in namespace '%s'\n", *podName, *namespace)
} else {
// Handle other potential errors (permissions, connection issues, etc.)
log.Fatalf("Error getting pod '%s': %s\n", *podName, err.Error())
}
}
// --- Pod Found - Extract and Print Details ---
fmt.Printf("Successfully retrieved Pod '%s'.\n", pod.Name)
fmt.Println("--- Details ---")
fmt.Printf(" Phase: %s\n", pod.Status.Phase)
fmt.Printf(" Pod IP: %s\n", pod.Status.PodIP) // Primary Pod IP
fmt.Printf(" Host IP: %s\n", pod.Status.HostIP) // Node IP where the Pod runs
fmt.Printf(" Node Name: %s\n", pod.Spec.NodeName) // Name of the Node
fmt.Println(" Container Ports (from Spec):")
if len(pod.Spec.Containers) > 0 {
for _, container := range pod.Spec.Containers {
fmt.Printf(" Container: %s\n", container.Name)
if len(container.Ports) > 0 {
for _, port := range container.Ports {
portInfo := []string{}
if port.Name != "" {
portInfo = append(portInfo, "Name="+port.Name)
}
portInfo = append(portInfo, fmt.Sprintf("Port=%d", port.ContainerPort))
portInfo = append(portInfo, "Proto="+string(port.Protocol)) // Default is TCP
fmt.Printf(" - %s\n", strings.Join(portInfo, ", "))
}
} else {
fmt.Println(" - No ports defined")
}
}
} else {
fmt.Println(" No containers defined in spec (this is unusual!)")
}
fmt.Println("---------------")
}PreviousDeep Dive into the Pod Object Spec and StatusNextUnderstanding Labels and Selectors for Network Targeting
Last updated
Was this helpful?