Created
August 8, 2022 12:51
-
-
Save mgnisia/3aa2312b5b2e2eb58b8405b33a670107 to your computer and use it in GitHub Desktop.
Client Go with Home Directory Example
This file contains hidden or 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
package main | |
import ( | |
"context" | |
"flag" | |
"log" | |
"path/filepath" | |
"testing" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
clientset "k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/tools/clientcmd" | |
"k8s.io/client-go/util/homedir" | |
) | |
func Test_Some_Kind_Of_Test(t *testing.T) { | |
var kubeconfig *string | |
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() | |
// use the current context in kubeconfig | |
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) | |
if err != nil { | |
panic(err.Error()) | |
} | |
client := clientset.NewForConfigOrDie(config) | |
ctx, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
api := client.CoreV1() | |
pods, err := api.Pods("some-namespace").List(ctx, metav1.ListOptions{}) | |
if err != nil { | |
panic(err.Error()) | |
} | |
for _, v := range pods.Items { | |
log.Println(v.Labels) | |
log.Println(v.Name) | |
log.Println(v.Status.Phase) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment