簡體   English   中英

如何直接從 Go 中的 GCP 服務帳戶 JSON 密鑰文件創建 kube.netes.Clientset?

[英]How can I create a kubernetes.Clientset directly from a GCP service account JSON key file in Go?

我正在尋找一種從服務帳戶 JSON 密鑰文件開始在 Go 中為 GKE 初始化kube.netes.Clientset的方法。 我找到了一些線索,比如這個博客這個相關的要點,但是那里概述的方法似乎需要列出 GCP 項目中的所有集群以創建 kubeconfig 的內存中表示,這並不理想。

使用來自https://github.com/rancher/kontainer-engineGKE 驅動程序代碼作為靈感,我想出了以下方法(避免了對k8s.io/client-go/tools/clientcmd的依賴):

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "strings"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/api/container/v1"
    "google.golang.org/api/option"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
)

func getGKEClientset(cluster *container.Cluster, ts oauth2.TokenSource) (kubernetes.Interface, error) {
    capem, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClusterCaCertificate)
    if err != nil {
        return nil, fmt.Errorf("failed to decode cluster CA cert: %s", err)
    }

    config := &rest.Config{
        Host: cluster.Endpoint,
        TLSClientConfig: rest.TLSClientConfig{
            CAData: capem,
        },
    }
    config.Wrap(func(rt http.RoundTripper) http.RoundTripper {
        return &oauth2.Transport{
            Source: ts,
            Base:   rt,
        }
    })

    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, fmt.Errorf("failed to initialise clientset from config: %s", err)
    }

    return clientset, nil
}

func main() {
    gcpServiceAccountKeyFile := "gcp_service_account_key.json"
    gkeLocation := "<GKE Project Location>" // i.e. us-east1
    gkeClusterName := "<GKE Cluster Name>"
    gkeNamespace :=  "<GKE Cluster Namespace>"

    data, err := ioutil.ReadFile(gcpServiceAccountKeyFile)
    if err != nil {
        log.Fatalf("Failed to read GCP service account key file: %s", err)
    }

    ctx := context.Background()

    creds, err := google.CredentialsFromJSON(ctx, data, container.CloudPlatformScope)
    if err != nil {
        log.Fatalf("Failed to load GCP service account credentials: %s", err)
    }

    gkeService, err := container.NewService(ctx, option.WithHTTPClient(oauth2.NewClient(ctx, creds.TokenSource)))
    if err != nil {
        log.Fatalf("Failed to initialise Kubernetes Engine service: %s", err)
    }

    name := fmt.Sprintf("projects/%s/locations/%s/clusters/%s", creds.ProjectID, gkeLocation, gkeClusterName)
    cluster, err := container.NewProjectsLocationsClustersService(gkeService).Get(name).Do()
    if err != nil {
        log.Fatalf("Failed to load GKE cluster %q: %s", name, err)
    }

    clientset, err := getGKEClientset(cluster, creds.TokenSource)
    if err != nil {
        log.Fatalf("Failed to initialise Kubernetes clientset: %s", err)
    }

    pods, err := clientset.CoreV1().Pods(gkeNamespace).List(ctx, v1.ListOptions{})
    if err != nil {
        log.Fatalf("Failed to list pods: %s", err)
    }
    log.Printf("There are %d pods in the namespace", len(pods.Items))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM