Skip to content

Instantly share code, notes, and snippets.

@mzupan
Created February 8, 2018 21:43
Show Gist options
  • Save mzupan/3aa70915f56684b86472b1ed53c19743 to your computer and use it in GitHub Desktop.
Save mzupan/3aa70915f56684b86472b1ed53c19743 to your computer and use it in GitHub Desktop.
Pulling out kubernetes services with the first port in Go
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func main() {
var kubeconfig *string
if home := 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")
}
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
services, err := clientset.CoreV1().Services("").List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d services in the cluster\n", len(services.Items))
for _, s := range services.Items {
fmt.Printf(" -- Service name %s with port %d\n",s.Name, s.Spec.Ports[0].Port)
}
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment