Skip to content

Instantly share code, notes, and snippets.

@bells17
Last active February 4, 2020 11:22
Show Gist options
  • Save bells17/48fe549d52160e43a5db6ab363a27b55 to your computer and use it in GitHub Desktop.
Save bells17/48fe549d52160e43a5db6ab363a27b55 to your computer and use it in GitHub Desktop.
fetch pod & node
package main
import (
"bytes"
"flag"
"fmt"
"html/template"
"os"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
// creates the out-of-cluster config
var kubeconfig *string
if home := os.Getenv("HOME"); 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()
// use the current context in kubeconfig
config, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
output, err := outputPods(clientset, "docker-desktop", Tmpl)
if err != nil {
panic(err.Error())
}
fmt.Printf(output)
}
var Tmpl = `
{{range .Items}}Node Name: {{.Spec.NodeName}}
Pod Name: {{.ObjectMeta.Name}}
Pod Namespace: {{.ObjectMeta.Namespace}}
{{end}}
`
func outputPods(clientset *kubernetes.Clientset, nodeName string, tmpl string) (string, error) {
pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{
FieldSelector: "spec.nodeName=" + nodeName,
})
if err != nil {
return "", err
}
t, err := template.New("output").Parse(tmpl)
if err != nil {
return "", err
}
b := new(bytes.Buffer)
err = t.Execute(b, pods)
return b.String(), err
}
$ go run main.go
Node Name: docker-desktop
Pod Name: nginx-pod
Pod Namespace: default
Node Name: docker-desktop
Pod Name: nginx-pod2
Pod Namespace: default
@bells17
Copy link
Author

bells17 commented Feb 4, 2020

@sravankumar777

Recently our team had changed the cluster configuration as insecure

Sorry, I have never tried this setting.
Could you tell me about the details of this setting?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment