Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())
    }
}
like image 969
yzhengwei Avatar asked Oct 18 '25 02:10

yzhengwei


1 Answers

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:

  • out of cluster authentication example
  • in cluster authentication example - it is using ServiceAccount token

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"

like image 91
Jonas Avatar answered Oct 19 '25 21:10

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!