Created
May 14, 2022 19:44
-
-
Save MeirP-3/728f25f1aaf1a4222b611205748bd342 to your computer and use it in GitHub Desktop.
A demonstration of get pod with client-go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A demonstration of get pod using client-go | |
Based on client-go examples: https://github.com/kubernetes/client-go/tree/master/examples | |
To demonstrate, run this file with `go run <filename> --help` to see usage | |
*/ | |
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"os" | |
"path/filepath" | |
v1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/tools/clientcmd" | |
"k8s.io/client-go/util/homedir" | |
) | |
func main() { | |
podName := flag.String("pod-name", "", "name of the required pod") | |
namespaceName := flag.String("namespace", "", "namespace of the required pod") | |
var kubeconfig *string | |
if config, exist := os.LookupEnv("KUBECONFIG"); exist { | |
kubeconfig = &config | |
} else if home := homedir.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) | |
} | |
clientset, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
panic(err) | |
} | |
podClient := clientset.CoreV1().Pods(*namespaceName) | |
fmt.Println("Getting pod...") | |
result, err := podClient.Get(context.TODO(), *podName, v1.GetOptions{}) | |
if err != nil { | |
panic(err) | |
} | |
// Example fields | |
fmt.Printf("%+v\n", result.Name) | |
fmt.Printf("%+v\n", result.Namespace) | |
fmt.Printf("%+v\n", result.Spec.ServiceAccountName) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment