gokubernetesknative-serving

List service in go


I'm trying to list knative (v0.17.0) services, I have a clientset but I don't know where to start. Here is a service I launched for my test :

apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
  name: "helloworld"
spec:
  runLatest:
    configuration:
      revisionTemplate:
        spec:
          container:
            image: "gcr.io/knative-samples/helloworld-go"
            env:
              - name: "TARGET"
                value: "world"

If you have any advice, tutorial or example it would be great


Solution

  • Basing this off this gist adapted for the post-1.18 client-go, and the Serving clientset godoc:

    import (
      "context"
      "fmt"
      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
      "k8s.io/client-go/tools/clientcmd"
      servingv1 "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1"
    }
    
    func doIt() error {
      config, err := clientcmd.BuildConfigFromFLags("", "") // Uses defaults
      if err != nil {
        return err
      }
    
      serving, err := servingv1.NewForConfig(config)
      if err != nil {
        return err
      }
    
      // Get services in the default namespace
      list, err := serving.Services("default").List(context.Background(), metav1.ListOptions{})
      if err != nil {
        return err
      }
      // How to print them out.
      fmt.Printf("There are %d services in the default namespace", len(list.Items))
      for _, i := range list.Items {
        fmt.Printf("  > Service %q", i.Name)
      }
    }