func getK8sClusterConfigs()

in gke-deploy/services/gcloud.go [97:161]


func getK8sClusterConfigs(ctx context.Context, clusterProject, clusterLocation, clusterName, kubeConfigFile string) error {
	fullClusterName := fmt.Sprintf(gkeResourceNameFormat, clusterProject, clusterLocation, clusterName)
	fmt.Printf("Full Cluster: %s\n", fullClusterName)
	ts, err := google.DefaultTokenSource(ctx, googleScopes...)
	if err != nil {
		return fmt.Errorf("failed to create google token source: %v", err)
	}
	options := []option.ClientOption{option.WithTokenSource(ts)}
	userAgent := os.Getenv("GOOGLE_APIS_USER_AGENT")
	if userAgent != "" {
		options = append(options, option.WithUserAgent(userAgent))
	}
	svc, err := container.NewService(ctx, options...)
	if err != nil {
		return fmt.Errorf("failed to initialize gke client: %v", err)
	}
	cluster, err := svc.Projects.Locations.Clusters.Get(fullClusterName).Do()
	if err != nil {
		return fmt.Errorf("failed to list clusters: %w", err)
	}
	fmt.Printf("Cluster's Endpoint is: %s\n", cluster.Endpoint)
	name := fmt.Sprintf(gkeContextFormat, clusterProject, cluster.Zone, cluster.Name)
	kubeConfig := &api.Config{
		APIVersion:     "v1",
		Kind:           "Config",
		Clusters:       map[string]*api.Cluster{},
		AuthInfos:      map[string]*api.AuthInfo{},
		Contexts:       map[string]*api.Context{},
		CurrentContext: name,
	}
	_, err = os.Stat(kubeConfigFile)
	if os.IsNotExist(err) {
	} else {
		conf, err := clientcmd.LoadFromFile(kubeConfigFile)
		if err != nil {
			return fmt.Errorf("failed to load kubeConfig from file %s : %v", kubeConfigFile, err)
		}
		kubeConfig = conf
	}
	cert, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClusterCaCertificate)
	if err != nil {
		return fmt.Errorf("failed to decode the cluster certificate: %v", err)
	}
	kubeConfig.Clusters[name] = &api.Cluster{
		CertificateAuthorityData: cert,
		Server:                   "https://" + cluster.Endpoint,
	}
	kubeConfig.Contexts[name] = &api.Context{
		Cluster:  name,
		AuthInfo: name,
	}
	kubeConfig.AuthInfos[name] = &api.AuthInfo{
		Exec: &api.ExecConfig{
			APIVersion:         kubeApiVersion,
			Command:            kubeCommand,
			Args:               kubeArgs,
			InstallHint:        kubeInstallHint,
			ProvideClusterInfo: kubeProvideClusterInfo,
		},
	}
	if err := clientcmd.WriteToFile(*kubeConfig, kubeConfigFile); err != nil {
		return fmt.Errorf("failed to write kubeConfig to file %s: %v", kubeConfigFile, err)
	}
	return nil
}