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
@sravankumar777
Copy link

Hi @bells17,

Thanks for your reply. Yes, i work from Japan location recently got shifted to Japan.
I am sorry, i dont speak japanese.

However, about the my queries.

Yes, i want to fetch all pods.
Yes, want to list all pods for multiple different nodes provided by user.

Thanks for assisting & supporting me.

@bells17
Copy link
Author

bells17 commented Jan 15, 2020

No worries!

I updated script to below.
Could you review it?

package main

import (
	"bytes"
	"flag"
	"fmt"
	"html/template"
	"os"
	"path/filepath"

	corev1 "k8s.io/api/core/v1"
	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)
	output, err := outputAllPodsPerEachNode(clientset, Tmpl2)
	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
}

var Tmpl2 = `
{{ range $key, $value := . }}
Node Name: {{$key}}

{{ range $k, $pod := $value }}
Pod  Name: {{$pod.ObjectMeta.Name}}
Pod Namespace: {{$pod.ObjectMeta.Namespace}}
{{ end }}

{{end}}
`

func outputAllPodsPerEachNode(clientset *kubernetes.Clientset, tmpl string) (string, error) {
	pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{})
	if err != nil {
		return "", err
	}

	podsPerNode := map[string][]corev1.Pod{}
	for _, pod := range pods.Items {
		name := pod.Spec.NodeName
		if _, ok := podsPerNode[name]; !ok {
			podsPerNode[name] = []corev1.Pod{}
		}
		podsPerNode[name] = append(podsPerNode[name], pod)
	}

	t, err := template.New("output").Parse(tmpl)
	if err != nil {
		return "", err
	}

	b := new(bytes.Buffer)
	err = t.Execute(b, podsPerNode)
	return b.String(), err
}

output

go run main.go                                                                                                                          18:46:26


Node Name: docker-desktop


Pod  Name: nginx-pod
Pod Namespace: default

Pod  Name: nginx-pod2
Pod Namespace: default


@sravankumar777
Copy link

@bells17, I'm sorry to trouble you again.

Recently our team had changed the cluster configuration as insecure and while i'm doing InClusterConfig(), it would be make secure communication. So, i am not able retrieve pods.

However, i did try to make the TLSConfig as insecure: true.
I get error as specifying a root certificates file with the insecure flag is not allowed.

I even tried to make the null configuration of certificates in TLSConfig as below.

config.TLSClientConfig.Insecure = true
config.TLSClientConfig.CertFile = nil
config.TLSClientConfig.CertData = nil
config.TLSClientConfig.CAData = nil

Can you please help me out in this step?

@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