2

我正在尝试将kubernetes go-client与 cloud.google.com/go/container 一起使用。我使用 google cloud go 容器包创建集群,然后我想使用 go-client 在该集群上部署。集群外示例使用 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:由未知机构签名的证书。因此,显然缺少一些东西。任何其他方法都非常受欢迎!提前致谢

4

2 回答 2

5

ClientCertificate、ClientKey 和 ClusterCaCertificate 需要按照此处所述进行解码

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
    }
}
于 2018-09-18T21:15:40.647 回答
1

我在这里回答了一个非常相似的问题:Access Kubernetes GKE cluster outside of GKE cluster with client-go? .

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

  1. 创建一个 Google Cloud IAM 服务帐号 + 下载其 json 密钥
  2. GOOGLE_APPLICATION_CREDENTIALSenv var 设置为该 key.json
  3. 查找集群的 IP 地址和 CA 证书gcloud container clusters describe(或简单地.kube/configgcloud get-credentials
  4. 将这些值传递给 client-go 并使用 env var 运行您的程序。
于 2018-09-12T00:05:20.187 回答