Reputation: 85895
I'm using the native client-go API in Go to get the list of Pods managed by a Deployment type controller under a given namespace ("default"), but the returned list is not containing the list of Pods
labelSelector := labels.Set(obj.Spec.Selector.MatchLabels)
where obj
is of type *appsv1.Deployment
from https://pkg.go.dev/k8s.io/api/apps/v1?tab=doc#Deployment
podsList, err := getPodList(string(labelSelector.AsSelector().String()), kubeClient, res.Namespace)
with the function definition being
func getPodList( labelSelector string, client kubernetes.Interface, ns string ) (*corev1.PodList, error) {
options := metav1.ListOptions{
LabelSelector: labelSelector,
}
podList, err := client.CoreV1().Pods(ns).List(options)
return podList, err
}
The type returned - https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#PodList should contain the Items []Pod
slice which is not available in my returned information.
Using the following packages in the Go code
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
Upvotes: 0
Views: 6345
Reputation: 85895
It seems I got it working all along, but just handled the return type of CoreV1().Pods(ns).List(options)
incorrectly. It was returning a pointer to a slice of PodList
- https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#PodList
Here is the minimal code, which I made work which could be useful for posterity
package main
import (
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"os"
"path/filepath"
)
func main() {
kubeconfig := filepath.Join(
os.Getenv("HOME"), ".kube", "config",
)
// Initialize kubernetes-client
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
fmt.Printf("Error building kubeconfig: %v\n", err)
os.Exit(1)
}
// create new client with the given config
// https://pkg.go.dev/k8s.io/client-go/kubernetes?tab=doc#NewForConfig
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
fmt.Printf("Error building kubernetes clientset: %v\n", err)
os.Exit(2)
}
// use the app's label selector name. Remember this should match with
// the deployment selector's matchLabels. Replace <APPNAME> with the
// name of your choice
options := metav1.ListOptions{
LabelSelector: "app=<APPNAME>",
}
// get the pod list
// https://pkg.go.dev/k8s.io/[email protected]+incompatible/kubernetes/typed/core/v1?tab=doc#PodInterface
podList, _ := kubeClient.CoreV1().Pods("default").List(options)
// List() returns a pointer to slice, derefernce it, before iterating
for _, podInfo := range (*podList).Items {
fmt.Printf("pods-name=%v\n", podInfo.Name)
fmt.Printf("pods-status=%v\n", podInfo.Status.Phase)
fmt.Printf("pods-condition=%v\n", podInfo.Status.Conditions)
}
}
Upvotes: 3