github.com/verrazzano/verrazzano@v1.7.0/cluster-operator/internal/capi/client.go (about)

     1  // Copyright (c) 2023, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package capi
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  
    10  	corev1 "k8s.io/api/core/v1"
    11  	"k8s.io/apimachinery/pkg/runtime"
    12  	"k8s.io/apimachinery/pkg/runtime/schema"
    13  	"k8s.io/apimachinery/pkg/types"
    14  	"k8s.io/client-go/tools/clientcmd"
    15  	clipkg "sigs.k8s.io/controller-runtime/pkg/client"
    16  )
    17  
    18  var GVKCAPICluster = schema.GroupVersionKind{
    19  	Group:   "cluster.x-k8s.io",
    20  	Version: "v1beta1",
    21  	Kind:    "Cluster",
    22  }
    23  
    24  // GetClusterClient creates a controller-runtime client for a given CAPI cluster reference, if the kubeconfig for that cluster is available.
    25  func GetClusterClient(ctx context.Context, cli clipkg.Client, cluster types.NamespacedName, scheme *runtime.Scheme) (clipkg.Client, error) {
    26  	kubeconfigSecret := &corev1.Secret{}
    27  	kubeconfigSecretNSN := types.NamespacedName{
    28  		Namespace: cluster.Namespace,
    29  		Name:      fmt.Sprintf("%s-kubeconfig", cluster.Name),
    30  	}
    31  	if err := cli.Get(ctx, kubeconfigSecretNSN, kubeconfigSecret); err != nil {
    32  		return nil, err
    33  	}
    34  	kubeconfig, ok := kubeconfigSecret.Data["value"]
    35  	if !ok {
    36  		return nil, fmt.Errorf("no kubeconfig found for cluster %s/%s", cluster.Namespace, cluster.Name)
    37  	}
    38  	config, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	return clipkg.New(config, clipkg.Options{
    43  		Scheme: scheme,
    44  	})
    45  }