From f744036c71cf0e4fe8fc32063c3a8c6c98fd402a Mon Sep 17 00:00:00 2001 From: Philip Laine Date: Fri, 14 Jun 2024 15:16:55 +0200 Subject: [PATCH] refactor: remove use of k8s secret (#2565) ## Description Removes use of k8s secret functions. ## Related Issue Relates to #2507 ## Checklist before merging - [x] Test, docs, adr added or updated as needed - [x] [Contributor Guide Steps](https://github.com/defenseunicorns/zarf/blob/main/.github/CONTRIBUTING.md#developer-workflow) followed --- src/internal/packager/helm/post-render.go | 45 +++++++--- src/pkg/cluster/secrets.go | 58 +++++++++---- src/pkg/cluster/state.go | 27 +++--- src/pkg/cluster/zarf.go | 56 ++++++++---- src/pkg/k8s/secrets.go | 100 ---------------------- src/pkg/packager/remove.go | 73 ++++++++++++---- 6 files changed, 190 insertions(+), 169 deletions(-) delete mode 100644 src/pkg/k8s/secrets.go diff --git a/src/internal/packager/helm/post-render.go b/src/internal/packager/helm/post-render.go index 0a44acd06b..92b912ae63 100644 --- a/src/internal/packager/helm/post-render.go +++ b/src/internal/packager/helm/post-render.go @@ -159,24 +159,49 @@ func (r *renderer) adoptAndUpdateNamespaces(ctx context.Context) error { continue } - // Create the secret - validRegistrySecret := c.GenerateRegistryPullCreds(name, config.ZarfImagePullSecretName, r.state.RegistryInfo) - // Try to get a valid existing secret - currentRegistrySecret, _ := c.GetSecret(ctx, name, config.ZarfImagePullSecretName) + validRegistrySecret := c.GenerateRegistryPullCreds(name, config.ZarfImagePullSecretName, r.state.RegistryInfo) + // TODO: Refactor as error is not checked instead of checking for not found error. + currentRegistrySecret, _ := c.Clientset.CoreV1().Secrets(name).Get(ctx, config.ZarfImagePullSecretName, metav1.GetOptions{}) if currentRegistrySecret.Name != config.ZarfImagePullSecretName || !reflect.DeepEqual(currentRegistrySecret.Data, validRegistrySecret.Data) { - // Create or update the zarf registry secret - if _, err := c.CreateOrUpdateSecret(ctx, validRegistrySecret); err != nil { + err := func() error { + _, err := c.Clientset.CoreV1().Secrets(validRegistrySecret.Namespace).Create(ctx, validRegistrySecret, metav1.CreateOptions{}) + if err != nil && !kerrors.IsAlreadyExists(err) { + return err + } + if err == nil { + return nil + } + _, err = c.Clientset.CoreV1().Secrets(validRegistrySecret.Namespace).Update(ctx, validRegistrySecret, metav1.UpdateOptions{}) + if err != nil { + return err + } + return nil + }() + if err != nil { message.WarnErrf(err, "Problem creating registry secret for the %s namespace", name) } - // Generate the git server secret - gitServerSecret := c.GenerateGitPullCreds(name, config.ZarfGitServerSecretName, r.state.GitServer) - // Create or update the zarf git server secret - if _, err := c.CreateOrUpdateSecret(ctx, gitServerSecret); err != nil { + gitServerSecret := c.GenerateGitPullCreds(name, config.ZarfGitServerSecretName, r.state.GitServer) + err = func() error { + _, err := c.Clientset.CoreV1().Secrets(gitServerSecret.Namespace).Create(ctx, gitServerSecret, metav1.CreateOptions{}) + if err != nil && !kerrors.IsAlreadyExists(err) { + return err + } + if err == nil { + return nil + } + _, err = c.Clientset.CoreV1().Secrets(gitServerSecret.Namespace).Update(ctx, gitServerSecret, metav1.UpdateOptions{}) + if err != nil { + return err + } + return nil + }() + if err != nil { message.WarnErrf(err, "Problem creating git server secret for the %s namespace", name) } + } } return nil diff --git a/src/pkg/cluster/secrets.go b/src/pkg/cluster/secrets.go index a7190c8037..cfbb90953e 100644 --- a/src/pkg/cluster/secrets.go +++ b/src/pkg/cluster/secrets.go @@ -34,8 +34,6 @@ type DockerConfigEntryWithAuth struct { // GenerateRegistryPullCreds generates a secret containing the registry credentials. func (c *Cluster) GenerateRegistryPullCreds(namespace, name string, registryInfo types.RegistryInfo) *corev1.Secret { - secretDockerConfig := c.GenerateSecret(namespace, name, corev1.SecretTypeDockerConfigJson) - // Auth field must be username:password and base64 encoded fieldValue := registryInfo.PullUsername + ":" + registryInfo.PullPassword authEncodedValue := base64.StdEncoding.EncodeToString([]byte(fieldValue)) @@ -56,9 +54,23 @@ func (c *Cluster) GenerateRegistryPullCreds(namespace, name string, registryInfo message.WarnErrf(err, "Unable to marshal the .dockerconfigjson secret data for the image pull secret") } - // Add to the secret data - secretDockerConfig.Data[".dockerconfigjson"] = dockerConfigData - + secretDockerConfig := &corev1.Secret{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1.SchemeGroupVersion.String(), + Kind: "Secret", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + Labels: map[string]string{ + ZarfManagedByLabel: "zarf", + }, + }, + Type: corev1.SecretTypeDockerConfigJson, + Data: map[string][]byte{ + ".dockerconfigjson": dockerConfigData, + }, + } return secretDockerConfig } @@ -66,12 +78,25 @@ func (c *Cluster) GenerateRegistryPullCreds(namespace, name string, registryInfo func (c *Cluster) GenerateGitPullCreds(namespace, name string, gitServerInfo types.GitServerInfo) *corev1.Secret { message.Debugf("k8s.GenerateGitPullCreds(%s, %s, gitServerInfo)", namespace, name) - gitServerSecret := c.GenerateSecret(namespace, name, corev1.SecretTypeOpaque) - gitServerSecret.StringData = map[string]string{ - "username": gitServerInfo.PullUsername, - "password": gitServerInfo.PullPassword, + gitServerSecret := &corev1.Secret{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1.SchemeGroupVersion.String(), + Kind: "Secret", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + Labels: map[string]string{ + ZarfManagedByLabel: "zarf", + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{}, + StringData: map[string]string{ + "username": gitServerInfo.PullUsername, + "password": gitServerInfo.PullPassword, + }, } - return gitServerSecret } @@ -87,7 +112,7 @@ func (c *Cluster) UpdateZarfManagedImageSecrets(ctx context.Context, state *type } else { // Update all image pull secrets for _, namespace := range namespaceList.Items { - currentRegistrySecret, err := c.GetSecret(ctx, namespace.Name, config.ZarfImagePullSecretName) + currentRegistrySecret, err := c.Clientset.CoreV1().Secrets(namespace.Name).Get(ctx, config.ZarfImagePullSecretName, metav1.GetOptions{}) if err != nil { continue } @@ -97,11 +122,10 @@ func (c *Cluster) UpdateZarfManagedImageSecrets(ctx context.Context, state *type (namespace.Labels[k8s.AgentLabel] != "skip" && namespace.Labels[k8s.AgentLabel] != "ignore") { spinner.Updatef("Updating existing Zarf-managed image secret for namespace: '%s'", namespace.Name) - // Create the secret newRegistrySecret := c.GenerateRegistryPullCreds(namespace.Name, config.ZarfImagePullSecretName, state.RegistryInfo) if !reflect.DeepEqual(currentRegistrySecret.Data, newRegistrySecret.Data) { - // Create or update the zarf registry secret - if _, err := c.CreateOrUpdateSecret(ctx, newRegistrySecret); err != nil { + _, err := c.Clientset.CoreV1().Secrets(newRegistrySecret.Namespace).Update(ctx, newRegistrySecret, metav1.UpdateOptions{}) + if err != nil { message.WarnErrf(err, "Problem creating registry secret for the %s namespace", namespace.Name) } } @@ -123,7 +147,7 @@ func (c *Cluster) UpdateZarfManagedGitSecrets(ctx context.Context, state *types. } else { // Update all git pull secrets for _, namespace := range namespaceList.Items { - currentGitSecret, err := c.GetSecret(ctx, namespace.Name, config.ZarfGitServerSecretName) + currentGitSecret, err := c.Clientset.CoreV1().Secrets(namespace.Name).Get(ctx, config.ZarfGitServerSecretName, metav1.GetOptions{}) if err != nil { continue } @@ -136,8 +160,8 @@ func (c *Cluster) UpdateZarfManagedGitSecrets(ctx context.Context, state *types. // Create the secret newGitSecret := c.GenerateGitPullCreds(namespace.Name, config.ZarfGitServerSecretName, state.GitServer) if !reflect.DeepEqual(currentGitSecret.StringData, newGitSecret.StringData) { - // Create or update the zarf git secret - if _, err := c.CreateOrUpdateSecret(ctx, newGitSecret); err != nil { + _, err := c.Clientset.CoreV1().Secrets(newGitSecret.Namespace).Update(ctx, newGitSecret, metav1.UpdateOptions{}) + if err != nil { message.WarnErrf(err, "Problem creating git server secret for the %s namespace", namespace.Name) } } diff --git a/src/pkg/cluster/state.go b/src/pkg/cluster/state.go index ba0cf0ee95..64b8162c21 100644 --- a/src/pkg/cluster/state.go +++ b/src/pkg/cluster/state.go @@ -27,6 +27,7 @@ import ( // Zarf Cluster Constants. const ( + ZarfManagedByLabel = "app.kubernetes.io/managed-by" ZarfNamespaceName = "zarf" ZarfStateSecretName = "zarf-state" ZarfStateDataKey = "state" @@ -214,7 +215,7 @@ func (c *Cluster) InitZarfState(ctx context.Context, initOptions types.ZarfInitO // LoadZarfState returns the current zarf/zarf-state secret data or an empty ZarfState. func (c *Cluster) LoadZarfState(ctx context.Context) (state *types.ZarfState, err error) { // Set up the API connection - secret, err := c.GetSecret(ctx, ZarfNamespaceName, ZarfStateSecretName) + secret, err := c.Clientset.CoreV1().Secrets(ZarfNamespaceName).Get(ctx, ZarfStateSecretName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("%w. %s", err, message.ColorWrap("Did you remember to zarf init?", color.Bold)) } @@ -267,17 +268,10 @@ func (c *Cluster) debugPrintZarfState(state *types.ZarfState) { func (c *Cluster) SaveZarfState(ctx context.Context, state *types.ZarfState) error { c.debugPrintZarfState(state) - // Convert the data back to JSON. data, err := json.Marshal(&state) if err != nil { return err } - - // Set up the data wrapper. - dataWrapper := make(map[string][]byte) - dataWrapper[ZarfStateDataKey] = data - - // The secret object. secret := &corev1.Secret{ TypeMeta: metav1.TypeMeta{ APIVersion: corev1.SchemeGroupVersion.String(), @@ -291,14 +285,23 @@ func (c *Cluster) SaveZarfState(ctx context.Context, state *types.ZarfState) err }, }, Type: corev1.SecretTypeOpaque, - Data: dataWrapper, + Data: map[string][]byte{ + ZarfStateDataKey: data, + }, } // Attempt to create or update the secret and return. - if _, err := c.CreateOrUpdateSecret(ctx, secret); err != nil { - return fmt.Errorf("unable to create the zarf state secret") + _, err = c.Clientset.CoreV1().Secrets(secret.Namespace).Create(ctx, secret, metav1.CreateOptions{}) + if err != nil && !kerrors.IsAlreadyExists(err) { + return fmt.Errorf("unable to create the zarf state secret: %w", err) + } + if err == nil { + return nil + } + _, err = c.Clientset.CoreV1().Secrets(secret.Namespace).Update(ctx, secret, metav1.UpdateOptions{}) + if err != nil { + return fmt.Errorf("unable to update the zarf state secret: %w", err) } - return nil } diff --git a/src/pkg/cluster/zarf.go b/src/pkg/cluster/zarf.go index 921268e6a6..787852b761 100644 --- a/src/pkg/cluster/zarf.go +++ b/src/pkg/cluster/zarf.go @@ -12,13 +12,15 @@ import ( "strings" "time" + autoscalingV2 "k8s.io/api/autoscaling/v2" + corev1 "k8s.io/api/core/v1" + kerrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "github.com/defenseunicorns/zarf/src/config" "github.com/defenseunicorns/zarf/src/pkg/k8s" "github.com/defenseunicorns/zarf/src/pkg/message" "github.com/defenseunicorns/zarf/src/types" - autoscalingV2 "k8s.io/api/autoscaling/v2" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // GetDeployedZarfPackages gets metadata information about packages that have been deployed to the cluster. @@ -26,7 +28,8 @@ import ( // Returns a list of DeployedPackage structs and a list of errors. func (c *Cluster) GetDeployedZarfPackages(ctx context.Context) ([]types.DeployedPackage, error) { // Get the secrets that describe the deployed packages - secrets, err := c.GetSecretsWithLabel(ctx, ZarfNamespaceName, ZarfPackageInfoLabel) + listOpts := metav1.ListOptions{LabelSelector: ZarfPackageInfoLabel} + secrets, err := c.Clientset.CoreV1().Secrets(ZarfNamespaceName).List(ctx, listOpts) if err != nil { return nil, err } @@ -54,7 +57,7 @@ func (c *Cluster) GetDeployedZarfPackages(ctx context.Context) ([]types.Deployed // We determine what packages have been deployed to the cluster by looking for specific secrets in the Zarf namespace. func (c *Cluster) GetDeployedPackage(ctx context.Context, packageName string) (deployedPackage *types.DeployedPackage, err error) { // Get the secret that describes the deployed package - secret, err := c.GetSecret(ctx, ZarfNamespaceName, config.ZarfPackagePrefix+packageName) + secret, err := c.Clientset.CoreV1().Secrets(ZarfNamespaceName).Get(ctx, config.ZarfPackagePrefix+packageName, metav1.GetOptions{}) if err != nil { return deployedPackage, err } @@ -178,11 +181,6 @@ func (c *Cluster) RecordPackageDeploymentAndWait(ctx context.Context, pkg types. func (c *Cluster) RecordPackageDeployment(ctx context.Context, pkg types.ZarfPackage, components []types.DeployedComponent, connectStrings types.ConnectStrings, generation int) (deployedPackage *types.DeployedPackage, err error) { packageName := pkg.Metadata.Name - // Generate a secret that describes the package that is being deployed - secretName := config.ZarfPackagePrefix + packageName - deployedPackageSecret := c.GenerateSecret(ZarfNamespaceName, secretName, corev1.SecretTypeOpaque) - deployedPackageSecret.Labels[ZarfPackageInfoLabel] = packageName - // Attempt to load information about webhooks for the package var componentWebhooks map[string]map[string]types.Webhook existingPackageSecret, err := c.GetDeployedPackage(ctx, packageName) @@ -209,16 +207,44 @@ func (c *Cluster) RecordPackageDeployment(ctx context.Context, pkg types.ZarfPac } // Update the package secret - deployedPackageSecret.Data = map[string][]byte{"data": packageData} - var updatedSecret *corev1.Secret - if updatedSecret, err = c.CreateOrUpdateSecret(ctx, deployedPackageSecret); err != nil { + deployedPackageSecret := &corev1.Secret{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1.SchemeGroupVersion.String(), + Kind: "Secret", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: config.ZarfPackagePrefix + packageName, + Namespace: ZarfNamespaceName, + Labels: map[string]string{ + ZarfManagedByLabel: "zarf", + ZarfPackageInfoLabel: packageName, + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{ + "data": packageData, + }, + } + updatedSecret, err := func() (*corev1.Secret, error) { + secret, err := c.Clientset.CoreV1().Secrets(deployedPackageSecret.Namespace).Create(ctx, deployedPackageSecret, metav1.CreateOptions{}) + if err != nil && !kerrors.IsAlreadyExists(err) { + return nil, err + } + if err == nil { + return secret, nil + } + secret, err = c.Clientset.CoreV1().Secrets(deployedPackageSecret.Namespace).Update(ctx, deployedPackageSecret, metav1.UpdateOptions{}) + if err != nil { + return nil, err + } + return secret, nil + }() + if err != nil { return nil, fmt.Errorf("failed to record package deployment in secret '%s'", deployedPackageSecret.Name) } - if err := json.Unmarshal(updatedSecret.Data["data"], &deployedPackage); err != nil { return nil, err } - return deployedPackage, nil } diff --git a/src/pkg/k8s/secrets.go b/src/pkg/k8s/secrets.go deleted file mode 100644 index 82b9ef52de..0000000000 --- a/src/pkg/k8s/secrets.go +++ /dev/null @@ -1,100 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: 2021-Present The Zarf Authors - -// Package k8s provides a client for interacting with a Kubernetes cluster. -package k8s - -import ( - "context" - "crypto/tls" - "fmt" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// GetSecret returns a Kubernetes secret. -func (k *K8s) GetSecret(ctx context.Context, namespace, name string) (*corev1.Secret, error) { - return k.Clientset.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}) -} - -// GetSecretsWithLabel returns a list of Kubernetes secrets with the given label. -func (k *K8s) GetSecretsWithLabel(ctx context.Context, namespace, labelSelector string) (*corev1.SecretList, error) { - listOptions := metav1.ListOptions{LabelSelector: labelSelector} - return k.Clientset.CoreV1().Secrets(namespace).List(ctx, listOptions) -} - -// GenerateSecret returns a Kubernetes secret object without applying it to the cluster. -func (k *K8s) GenerateSecret(namespace, name string, secretType corev1.SecretType) *corev1.Secret { - return &corev1.Secret{ - TypeMeta: metav1.TypeMeta{ - APIVersion: corev1.SchemeGroupVersion.String(), - Kind: "Secret", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - Labels: map[string]string{ - ZarfManagedByLabel: "zarf", - }, - }, - Type: secretType, - Data: map[string][]byte{}, - } -} - -// GenerateTLSSecret returns a Kubernetes secret object without applying it to the cluster. -func (k *K8s) GenerateTLSSecret(namespace, name string, conf GeneratedPKI) (*corev1.Secret, error) { - if _, err := tls.X509KeyPair(conf.Cert, conf.Key); err != nil { - return nil, err - } - - secretTLS := k.GenerateSecret(namespace, name, corev1.SecretTypeTLS) - secretTLS.Data[corev1.TLSCertKey] = conf.Cert - secretTLS.Data[corev1.TLSPrivateKeyKey] = conf.Key - - return secretTLS, nil -} - -// CreateOrUpdateTLSSecret creates or updates a Kubernetes secret with a new TLS secret. -func (k *K8s) CreateOrUpdateTLSSecret(ctx context.Context, namespace, name string, conf GeneratedPKI) (*corev1.Secret, error) { - secret, err := k.GenerateTLSSecret(namespace, name, conf) - if err != nil { - return secret, err - } - - return k.CreateOrUpdateSecret(ctx, secret) -} - -// DeleteSecret deletes a Kubernetes secret. -func (k *K8s) DeleteSecret(ctx context.Context, secret *corev1.Secret) error { - namespaceSecrets := k.Clientset.CoreV1().Secrets(secret.Namespace) - - err := namespaceSecrets.Delete(ctx, secret.Name, metav1.DeleteOptions{}) - if err != nil && !errors.IsNotFound(err) { - return fmt.Errorf("error deleting the secret: %w", err) - } - - return nil -} - -// CreateOrUpdateSecret creates or updates a Kubernetes secret. -func (k *K8s) CreateOrUpdateSecret(ctx context.Context, secret *corev1.Secret) (createdSecret *corev1.Secret, err error) { - - namespaceSecrets := k.Clientset.CoreV1().Secrets(secret.Namespace) - - if _, err = k.GetSecret(ctx, secret.Namespace, secret.Name); err != nil { - // create the given secret - if createdSecret, err = namespaceSecrets.Create(ctx, secret, metav1.CreateOptions{}); err != nil { - return createdSecret, fmt.Errorf("unable to create the secret: %w", err) - } - } else { - // update the given secret - if createdSecret, err = namespaceSecrets.Update(ctx, secret, metav1.UpdateOptions{}); err != nil { - return createdSecret, fmt.Errorf("unable to update the secret: %w", err) - } - } - - return createdSecret, nil -} diff --git a/src/pkg/packager/remove.go b/src/pkg/packager/remove.go index 5169e53cbf..091f446ae2 100644 --- a/src/pkg/packager/remove.go +++ b/src/pkg/packager/remove.go @@ -10,10 +10,14 @@ import ( "errors" "fmt" "runtime" - "slices" "github.com/defenseunicorns/pkg/helpers/v2" + "helm.sh/helm/v3/pkg/storage/driver" + corev1 "k8s.io/api/core/v1" + kerrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "github.com/defenseunicorns/zarf/src/config" "github.com/defenseunicorns/zarf/src/internal/packager/helm" "github.com/defenseunicorns/zarf/src/pkg/cluster" @@ -22,8 +26,6 @@ import ( "github.com/defenseunicorns/zarf/src/pkg/packager/filters" "github.com/defenseunicorns/zarf/src/pkg/packager/sources" "github.com/defenseunicorns/zarf/src/types" - "helm.sh/helm/v3/pkg/storage/driver" - corev1 "k8s.io/api/core/v1" ) // Remove removes a package that was already deployed onto a cluster, uninstalling all installed helm charts. @@ -104,25 +106,60 @@ func (p *Packager) Remove(ctx context.Context) (err error) { return nil } -func (p *Packager) updatePackageSecret(ctx context.Context, deployedPackage types.DeployedPackage) { +func (p *Packager) updatePackageSecret(ctx context.Context, deployedPackage types.DeployedPackage) error { // Only attempt to update the package secret if we are actually connected to a cluster if p.cluster != nil { + newPackageSecretData, err := json.Marshal(deployedPackage) + if err != nil { + return err + } + secretName := config.ZarfPackagePrefix + deployedPackage.Name // Save the new secret with the removed components removed from the secret - newPackageSecret := p.cluster.GenerateSecret(cluster.ZarfNamespaceName, secretName, corev1.SecretTypeOpaque) - newPackageSecret.Labels[cluster.ZarfPackageInfoLabel] = deployedPackage.Name - - newPackageSecretData, _ := json.Marshal(deployedPackage) - newPackageSecret.Data["data"] = newPackageSecretData - - _, err := p.cluster.CreateOrUpdateSecret(ctx, newPackageSecret) + newPackageSecret := &corev1.Secret{ + TypeMeta: metav1.TypeMeta{ + APIVersion: corev1.SchemeGroupVersion.String(), + Kind: "Secret", + }, + ObjectMeta: metav1.ObjectMeta{ + Name: secretName, + Namespace: cluster.ZarfNamespaceName, + Labels: map[string]string{ + cluster.ZarfManagedByLabel: "zarf", + cluster.ZarfPackageInfoLabel: deployedPackage.Name, + }, + }, + Type: corev1.SecretTypeOpaque, + Data: map[string][]byte{ + "data": newPackageSecretData, + }, + } + err = func() error { + _, err := p.cluster.Clientset.CoreV1().Secrets(newPackageSecret.Namespace).Get(ctx, newPackageSecret.Name, metav1.GetOptions{}) + if err != nil && !kerrors.IsNotFound(err) { + return err + } + if kerrors.IsNotFound(err) { + _, err = p.cluster.Clientset.CoreV1().Secrets(newPackageSecret.Namespace).Create(ctx, newPackageSecret, metav1.CreateOptions{}) + if err != nil { + return fmt.Errorf("unable to create the zarf state secret: %w", err) + } + return nil + } + _, err = p.cluster.Clientset.CoreV1().Secrets(newPackageSecret.Namespace).Update(ctx, newPackageSecret, metav1.UpdateOptions{}) + if err != nil { + return fmt.Errorf("unable to update the zarf state secret: %w", err) + } + return nil + }() // We warn and ignore errors because we may have removed the cluster that this package was inside of if err != nil { message.Warnf("Unable to update the '%s' package secret: '%s' (this may be normal if the cluster was removed)", secretName, err.Error()) } } + return nil } func (p *Packager) removeComponent(ctx context.Context, deployedPackage *types.DeployedPackage, deployedComponent types.DeployedComponent, spinner *message.Spinner) (*types.DeployedPackage, error) { @@ -165,7 +202,10 @@ func (p *Packager) removeComponent(ctx context.Context, deployedPackage *types.D deployedComponent.InstalledCharts = helpers.RemoveMatches(deployedComponent.InstalledCharts, func(t types.InstalledChart) bool { return t.ChartName == chart.ChartName }) - p.updatePackageSecret(ctx, *deployedPackage) + err := p.updatePackageSecret(ctx, *deployedPackage) + if err != nil { + return nil, err + } } if err := actions.Run(onRemove.Defaults, onRemove.After, nil); err != nil { @@ -187,19 +227,22 @@ func (p *Packager) removeComponent(ctx context.Context, deployedPackage *types.D secretName := config.ZarfPackagePrefix + deployedPackage.Name // All the installed components were deleted, therefore this package is no longer actually deployed - packageSecret, err := p.cluster.GetSecret(ctx, cluster.ZarfNamespaceName, secretName) + packageSecret, err := p.cluster.Clientset.CoreV1().Secrets(cluster.ZarfNamespaceName).Get(ctx, secretName, metav1.GetOptions{}) // We warn and ignore errors because we may have removed the cluster that this package was inside of if err != nil { message.Warnf("Unable to delete the '%s' package secret: '%s' (this may be normal if the cluster was removed)", secretName, err.Error()) } else { - err = p.cluster.DeleteSecret(ctx, packageSecret) + err = p.cluster.Clientset.CoreV1().Secrets(packageSecret.Namespace).Delete(ctx, packageSecret.Name, metav1.DeleteOptions{}) if err != nil { message.Warnf("Unable to delete the '%s' package secret: '%s' (this may be normal if the cluster was removed)", secretName, err.Error()) } } } else { - p.updatePackageSecret(ctx, *deployedPackage) + err := p.updatePackageSecret(ctx, *deployedPackage) + if err != nil { + return nil, err + } } return deployedPackage, nil