Google 容器集群作为配置

Google container cluster as config

我正在尝试使用 go-client 提供的 kubernetes go-client with cloud.google.com/go/container. I create the cluster using the google cloud go container package, then I want to deploy on that cluster using go-client. The out of cluster example 使用 kube 配置文件来获取集群的凭据。但是因为我刚刚在我的应用程序中创建了这个集群,所以我没有那个配置文件。

如何使用 "google.golang.org/genproto/googleapis/container/v1" 集群设置“k8s.io/client-go/rest”配置?必填字段是什么?下面的代码是我目前拥有的(没有显示实际的 CA 证书)。

func getConfig(cluster *containerproto.Cluster) *rest.Config {
    return &rest.Config{
        Host:     "https://" + cluster.GetEndpoint(),
        TLSClientConfig: rest.TLSClientConfig{
            Insecure: false,
            CAData: []byte(`-----BEGIN CERTIFICATE-----
                ...
                -----END CERTIFICATE-----`),
        },
    }

它导致此错误:x509:由未知授权机构签署的证书。因此,显然缺少一些东西。 任何其他方法都非常受欢迎!提前致谢

我在这里回答了一个非常相似的问题:

简而言之,推荐的方法是:

  1. 创建一个 Google Cloud IAM 服务帐户 + 下载其 json 密钥
  2. GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为 key.json
  3. gcloud container clusters describe 中查找集群的 IP 地址和 CA 证书(或者只是从 gcloud get-credentials
  4. 中获取 .kube/config 文件
  5. 将这些值传递给 client-go 和 运行 您的带有环境变量的程序。

ClientCertificate、ClientKey 和 ClusterCaCertificate 需要按照描述进行解码here

func CreateK8sClientFromCluster(cluster *gkev1.Cluster) {
    decodedClientCertificate, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClientCertificate)
    if err != nil {
        fmt.Println("decode client certificate error:", err)
        return
    }
    decodedClientKey, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClientKey)
    if err != nil {
        fmt.Println("decode client key error:", err)
        return
    }
    decodedClusterCaCertificate, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClusterCaCertificate)
    if err != nil {
        fmt.Println("decode cluster CA certificate error:", err)
        return
    }

    config := &rest.Config{
        Username: cluster.MasterAuth.Username,
        Password: cluster.MasterAuth.Password,
        Host:     "https://" + cluster.Endpoint,
        TLSClientConfig: rest.TLSClientConfig{
            Insecure: false,
            CertData: decodedClientCertificate,
            KeyData:  decodedClientKey,
            CAData:   decodedClusterCaCertificate,
        },
    }

    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        fmt.Printf("failed to get k8s client set from config: %s\n", err)
        return
    }
}