4

For any example, the client-go connect to the kubernetes cluster with the kubeconfig file, but I don't want to do that. I've createed a service account, now I have a ServiceAccount Token, how to connect to the kubernetes cluster with this token outside of the kubernetes cluster?

package main

import (
    "flag"
    "k8s.io/client-go/tools/clientcmd"
    "log"
    "k8s.io/client-go/kubernetes"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "fmt"
)

var clientset *kubernetes.Clientset

func main()  {
    k8sconfig := flag.String("k8sconfig","./k8sconfig","kubernetes config file path")
    flag.Parse()
    config , err := clientcmd.BuildConfigFromFlags("",*k8sconfig)
    if err != nil {
        log.Println(err)
    }
    clientset , err = kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatalln(err)
    } else {
        fmt.Println("connect k8s success")
    }


    pods,err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
    if err != nil {
        log.Println(err.Error())
    }
}
yzhengwei
  • 67
  • 2
  • 6

1 Answers1

3

The client-go already has built-in authentication both In Cluster Authentication (to be used from a Pod with a ServiceAccount) and also Out of Cluster Authentication (to be used from outside the cluster, e.g. for local development)

The client-go has examples of both:

The in-cluster exampe is quite short:

    // creates the in-cluster config
    config, err := rest.InClusterConfig()
    if err != nil {
        panic(err.Error())
    }
    // creates the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }

You need to import "k8s.io/client-go/rest"

Jonas
  • 121,568
  • 97
  • 310
  • 388
  • I want to connect to the kubernetes cluster outside of the kubernetes – yzhengwei Mar 21 '21 at 14:51
  • Then you need to export the token and the private SSL certificate used to access the API Server - this is NOT recommended. But the kubeconfig for out-of-cluster authentication more or less does this for you. – Jonas Mar 21 '21 at 16:58