github.com/Racer159/jackal@v0.32.7-0.20240401174413-0bd2339e4f2e/src/pkg/k8s/sa.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // SPDX-FileCopyrightText: 2021-Present The Jackal Authors
     3  
     4  // Package k8s provides a client for interacting with a Kubernetes cluster.
     5  package k8s
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"time"
    11  
    12  	corev1 "k8s.io/api/core/v1"
    13  	"k8s.io/apimachinery/pkg/api/errors"
    14  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    15  )
    16  
    17  // GetAllServiceAccounts returns a list of services accounts for all namespaces.
    18  func (k *K8s) GetAllServiceAccounts() (*corev1.ServiceAccountList, error) {
    19  	return k.GetServiceAccounts(corev1.NamespaceAll)
    20  }
    21  
    22  // GetServiceAccounts returns a list of service accounts in a given namespace.
    23  func (k *K8s) GetServiceAccounts(namespace string) (*corev1.ServiceAccountList, error) {
    24  	metaOptions := metav1.ListOptions{}
    25  	return k.Clientset.CoreV1().ServiceAccounts(namespace).List(context.TODO(), metaOptions)
    26  }
    27  
    28  // GetServiceAccount returns a single service account by namespace and name.
    29  func (k *K8s) GetServiceAccount(namespace, name string) (*corev1.ServiceAccount, error) {
    30  	metaOptions := metav1.GetOptions{}
    31  	return k.Clientset.CoreV1().ServiceAccounts(namespace).Get(context.TODO(), name, metaOptions)
    32  }
    33  
    34  // UpdateServiceAccount updates the given service account in the cluster.
    35  func (k *K8s) UpdateServiceAccount(svcAccount *corev1.ServiceAccount) (*corev1.ServiceAccount, error) {
    36  	metaOptions := metav1.UpdateOptions{}
    37  	return k.Clientset.CoreV1().ServiceAccounts(svcAccount.Namespace).Update(context.TODO(), svcAccount, metaOptions)
    38  }
    39  
    40  // WaitForServiceAccount waits for a service account to be created in the cluster.
    41  func (k *K8s) WaitForServiceAccount(ns, name string, timeout time.Duration) (*corev1.ServiceAccount, error) {
    42  	expired := time.After(timeout)
    43  
    44  	for {
    45  		select {
    46  		case <-expired:
    47  			return nil, fmt.Errorf("timed out waiting for service account %s/%s to exist", ns, name)
    48  
    49  		default:
    50  			sa, err := k.Clientset.CoreV1().ServiceAccounts(ns).Get(context.TODO(), name, metav1.GetOptions{})
    51  			if err != nil {
    52  				if errors.IsNotFound(err) {
    53  					time.Sleep(1 * time.Second)
    54  					continue
    55  				}
    56  				return nil, fmt.Errorf("error getting service account %s/%s: %w", ns, name, err)
    57  			}
    58  
    59  			return sa, nil
    60  		}
    61  	}
    62  }