Skip to content

Commit

Permalink
Function CopySecretWithName for creating secrets with specific name
Browse files Browse the repository at this point in the history
  • Loading branch information
mgencur committed Jul 18, 2023
1 parent d89300c commit 32a28e5
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions pkg/utils/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ import (
// It'll either return a pointer to the new Secret or and error indicating
// why it couldn't do it.
func CopySecret(corev1Input clientcorev1.CoreV1Interface, srcNS string, srcSecretName string, tgtNS string, svcAccount string) (*corev1.Secret, error) {
return CopySecretWithName(corev1Input,
srcNS,
srcSecretName,
tgtNS,
srcSecretName, /* Use same target name as source by default */
svcAccount)
}

// CopySecretWithName will copy a secret from one namespace into another.
// Allows for specifying target secret name.
func CopySecretWithName(corev1Input clientcorev1.CoreV1Interface, srcNS, srcSecretName, tgtNS, tgtSecretName, svcAccount string) (*corev1.Secret, error) {
tgtNamespaceSvcAcct := corev1Input.ServiceAccounts(tgtNS)
srcSecrets := corev1Input.Secrets(srcNS)
tgtNamespaceSecrets := corev1Input.Secrets(tgtNS)
Expand All @@ -54,7 +65,7 @@ func CopySecret(corev1Input clientcorev1.CoreV1Interface, srcNS string, srcSecre
context.Background(),
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: srcSecretName,
Name: tgtSecretName,
},
Data: srcSecret.Data,
Type: srcSecret.Type,
Expand All @@ -65,12 +76,11 @@ func CopySecret(corev1Input clientcorev1.CoreV1Interface, srcNS string, srcSecre
if err != nil && !apierrs.IsAlreadyExists(err) {
return nil, fmt.Errorf("error copying the Secret: %s", err)
}

_, err = tgtNamespaceSvcAcct.Patch(context.Background(), svcAccount, types.StrategicMergePatchType,
[]byte(`{"imagePullSecrets":[{"name":"`+srcSecretName+`"}]}`), metav1.PatchOptions{})
[]byte(`{"imagePullSecrets":[{"name":"`+tgtSecretName+`"}]}`), metav1.PatchOptions{})
if err != nil {
return nil, fmt.Errorf("patch failed on NS/SA (%s/%s): %s",
tgtNS, srcSecretName, err)
tgtNS, tgtSecretName, err)
}
return newSecret, nil
}

0 comments on commit 32a28e5

Please sign in to comment.