-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ Add SecretSyncer controller to save pull secret data locally
- Loading branch information
Showing
2 changed files
with
156 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
/* | ||
Copyright 2024. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package controllers | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"os" | ||
|
||
"github.com/go-logr/logr" | ||
corev1 "k8s.io/api/core/v1" | ||
apierrors "k8s.io/apimachinery/pkg/api/errors" | ||
ctrl "sigs.k8s.io/controller-runtime" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
"sigs.k8s.io/controller-runtime/pkg/log" | ||
"sigs.k8s.io/controller-runtime/pkg/predicate" | ||
) | ||
|
||
// SecretSyncerReconciler reconciles a specific secret object | ||
type SecretSyncerReconciler struct { | ||
client.Client | ||
SecretName string | ||
SecretNamespace string | ||
AuthFilePath string | ||
} | ||
|
||
func (r *SecretSyncerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { | ||
logger := log.FromContext(ctx) | ||
|
||
if req.Name != r.SecretName || req.Namespace != r.SecretNamespace { | ||
logger.Info("Received unexpected request for secret", req.Name, "in namespace", req.Namespace) | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
secret := &corev1.Secret{} | ||
err := r.Get(ctx, req.NamespacedName, secret) | ||
if err != nil { | ||
if apierrors.IsNotFound(err) { | ||
logger.Info("Secret", req.Name, "in namespace", req.Namespace, "deleted.") | ||
return r.emptySecretFile(logger) | ||
} | ||
logger.Error(err, "Failed to get Secret") | ||
return ctrl.Result{}, err | ||
} | ||
|
||
return r.writeSecretToFile(secret, logger) | ||
} | ||
|
||
// SetupWithManager sets up the controller with the Manager. | ||
func (r *SecretSyncerReconciler) SetupWithManager(mgr ctrl.Manager) error { | ||
_, err := ctrl.NewControllerManagedBy(mgr). | ||
For(&corev1.Secret{}). | ||
WithEventFilter(newSecretPredicate(r.SecretName, r.SecretNamespace)). | ||
Build(r) | ||
|
||
return err | ||
} | ||
|
||
func newSecretPredicate(secretName, secretNamespace string) predicate.Predicate { | ||
return predicate.NewPredicateFuncs(func(obj client.Object) bool { | ||
secret, ok := obj.(*corev1.Secret) | ||
if !ok { | ||
return false | ||
} | ||
return secret.Name == secretName && secret.Namespace == secretNamespace | ||
}) | ||
} | ||
|
||
// writeSecretToFile writes the secret data to the specified file | ||
func (r *SecretSyncerReconciler) writeSecretToFile(secret *corev1.Secret, logger logr.Logger) (ctrl.Result, error) { | ||
secretData := make(map[string]string) | ||
for key, value := range secret.Data { | ||
// image registry secrets are always stored with the key .dockerconfigjson | ||
// ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#registry-secret-existing-credentials | ||
if key == ".dockerconfigjson" { | ||
secretData[key] = string(value) | ||
} | ||
} | ||
|
||
jsonData, err := json.Marshal(secretData) | ||
if err != nil { | ||
return ctrl.Result{}, fmt.Errorf("failed to marshal secret data: %w", err) | ||
} | ||
err = os.WriteFile(r.AuthFilePath, jsonData, 0644) | ||
if err != nil { | ||
return ctrl.Result{}, fmt.Errorf("failed to write secret data to file: %w", err) | ||
} | ||
logger.Info("Saved Secret data locally") | ||
return ctrl.Result{}, nil | ||
} | ||
|
||
// emptySecretFile deletes the secret data from the file if the secret is deleted | ||
func (r *SecretSyncerReconciler) emptySecretFile(logger logr.Logger) (ctrl.Result, error) { | ||
logger.Info("Emptying local auth file.") | ||
if _, err := os.Stat(r.AuthFilePath); err == nil { | ||
file, err := os.OpenFile(r.AuthFilePath, os.O_WRONLY|os.O_TRUNC, 0644) | ||
if err != nil { | ||
return ctrl.Result{}, fmt.Errorf("failed to open and empty secret file: %w", err) | ||
} | ||
defer file.Close() | ||
logger.Info("Auth file emptied successfully", "file", r.AuthFilePath) | ||
} else if os.IsNotExist(err) { | ||
logger.Info("Secret file does not exist, nothing to empty", "file", r.AuthFilePath) | ||
} else { | ||
return ctrl.Result{}, fmt.Errorf("failed to check secret file: %w", err) | ||
} | ||
|
||
return ctrl.Result{}, nil | ||
} |