yzhengwei
yzhengwei

Reputation: 75

How to connect to Kubernetes Cluster using ServiceAccount Token?

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())
    }
}

Upvotes: 4

Views: 4496

Answers (2)

weberc2
weberc2

Reputation: 7938

In addition to the service account token, your client also needs the certificate authority data for the cluster. You can find this in the kubeconfig file (typically ~/.kube/config)--this certificate authority data is not a secret so you can treat it like any other configuration. Additionally, if your cluster API is in a private network, you may need to proxy through to it (i.e., your kubeconfig cluster entry contains a proxy-url).

clientset, err := kubernetes.NewForConfig(&rest.Config{
    // one way to get a token is `kubectl create token <service-account>`
    BearerToken: os.Getenv("TOKEN"),

    // the address for the Kubernetes control plane, e.g., `https://10.0.0.1`.
    // this corresponds to the `server` field in your kubeconfig's cluster
    // entry.
    Host: os.Getenv("HOST"),

    // you can get this from kubeconfig's cluster certificate-authority-data
    // field, but be sure to base64 decode it first (after base64 decoding it
    // should look like `-----BEGIN CERTIFICATE-----\n...`)
    TLSClientConfig: rest.TLSClientConfig{CAData: []byte(os.Getenv("CERT"))},

    // set some timeout or else it will wait forever if it can't reach the
    // server
    Timeout: 10 * time.Second,
    
    // only required if your host is not accessible from the machine running
    // this code--omit it if you don't have a `proxy-url` field in the
    // kubeconfig entry for your cluster.
    Proxy: http.ProxyURL(&url.URL{Scheme: "http", Host: os.Getenv("PROXY")}),
})

The rest.Config object has lots of fields which may or may not be relevant; you can find the full documentation here.

Upvotes: 0

Jonas
Jonas

Reputation: 129035

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"

Upvotes: 2

Related Questions