github.com/argoproj/argo-cd/v3@v3.2.1/applicationset/utils/clusterUtils.go (about)

     1  package utils
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/argoproj/argo-cd/v3/common"
     8  	appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
     9  	"github.com/argoproj/argo-cd/v3/util/db"
    10  
    11  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    12  	"k8s.io/client-go/kubernetes"
    13  )
    14  
    15  // ClusterSpecifier contains only the name and server URL of a cluster. We use this struct to avoid partially-populating
    16  // the full Cluster struct, which would be misleading.
    17  type ClusterSpecifier struct {
    18  	Name   string
    19  	Server string
    20  }
    21  
    22  func ListClusters(ctx context.Context, clientset kubernetes.Interface, namespace string) ([]ClusterSpecifier, error) {
    23  	clusterSecretsList, err := clientset.CoreV1().Secrets(namespace).List(ctx,
    24  		metav1.ListOptions{LabelSelector: common.LabelKeySecretType + "=" + common.LabelValueSecretTypeCluster})
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	if clusterSecretsList == nil {
    30  		return nil, nil
    31  	}
    32  
    33  	clusterSecrets := clusterSecretsList.Items
    34  
    35  	clusterList := make([]ClusterSpecifier, len(clusterSecrets))
    36  
    37  	hasInClusterCredentials := false
    38  	for i, clusterSecret := range clusterSecrets {
    39  		cluster, err := db.SecretToCluster(&clusterSecret)
    40  		if err != nil || cluster == nil {
    41  			return nil, fmt.Errorf("unable to convert cluster secret to cluster object '%s': %w", clusterSecret.Name, err)
    42  		}
    43  		clusterList[i] = ClusterSpecifier{
    44  			Name:   cluster.Name,
    45  			Server: cluster.Server,
    46  		}
    47  		if cluster.Server == appv1.KubernetesInternalAPIServerAddr {
    48  			hasInClusterCredentials = true
    49  		}
    50  	}
    51  	if !hasInClusterCredentials {
    52  		// There was no secret for the in-cluster config, so we add it here. We don't fully-populate the Cluster struct,
    53  		// since only the name and server fields are used by the generator.
    54  		clusterList = append(clusterList, ClusterSpecifier{
    55  			Name:   "in-cluster",
    56  			Server: appv1.KubernetesInternalAPIServerAddr,
    57  		})
    58  	}
    59  	return clusterList, nil
    60  }