Skip to content

Commit

Permalink
feat(reconsiler): add serviceaccount support
Browse files Browse the repository at this point in the history
Signed-off-by: Dentrax <furkan.turkal@hotmail.com>
Signed-off-by: Batuhan Apaydın <batuhan.apaydin@trendyol.com>
  • Loading branch information
Dentrax authored and alexellis committed Nov 12, 2020
1 parent 6cbd12d commit 1f32431
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 0 deletions.
2 changes: 2 additions & 0 deletions config/rbac/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ rules:
resources:
- serviceaccounts
verbs:
- create
- delete
- get
- list
- patch
Expand Down
111 changes: 111 additions & 0 deletions controllers/serviceaccount_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
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 (
v1 "alexellis/registry-creds/api/v1"
"context"
"fmt"
"github.com/pkg/errors"

"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// ServiceAccountReconciler reconciles a ServiceAccount object
type ServiceAccountReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=core,resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=serviceaccounts/status,verbs=get;update;patch

func (r *ServiceAccountReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
ctx := context.Background()
r.Log.WithValues("serviceaccount", req.NamespacedName)

var sa corev1.ServiceAccount
if err := r.Get(ctx, req.NamespacedName, &sa); err != nil {
r.Log.Info(fmt.Sprintf("%s", errors.Wrap(err, "unable to fetch serviceaccount")))
return ctrl.Result{}, nil
}

r.Log.Info(fmt.Sprintf("detected a change in serviceaccount: %s", sa.Name))

pullSecretList := &v1.ClusterPullSecretList{}
err := r.Client.List(ctx, pullSecretList)
if err != nil {
r.Log.Info(fmt.Sprintf("unable to list ClusterPullSecrets, %s", err.Error()))
return ctrl.Result{}, nil
}

for _, clusterPullSecret := range pullSecretList.Items {
err = r.appendSecretToSA(clusterPullSecret, sa.Namespace, sa.Name)
if err != nil {
r.Log.Info(err.Error())
return ctrl.Result{}, nil
}
}

return ctrl.Result{}, nil
}

func (r *ServiceAccountReconciler) appendSecretToSA(clusterPullSecret v1.ClusterPullSecret, ns, serviceAccountName string) error {
ctx := context.Background()

secretKey := clusterPullSecret.Name + "-registrycreds"

sa := &corev1.ServiceAccount{}
err := r.Client.Get(ctx, client.ObjectKey{Name: serviceAccountName, Namespace: ns}, sa)
if err != nil {
r.Log.Info(fmt.Sprintf("error getting SA in namespace: %s, %s", ns, err.Error()))
wrappedErr := fmt.Errorf("unable to append pull secret to service account: %s", err)
r.Log.Info(wrappedErr.Error())
return wrappedErr
}

r.Log.Info(fmt.Sprintf("Pull secrets: %v", sa.ImagePullSecrets))

hasSecret := hasImagePullSecret(sa, secretKey)

if !hasSecret {
sa.ImagePullSecrets = append(sa.ImagePullSecrets, corev1.LocalObjectReference{
Name: secretKey,
})

err = r.Update(ctx, sa.DeepCopy())
if err != nil {
wrappedErr := fmt.Errorf("unable to append pull secret to service account: %s", err)
r.Log.Info(wrappedErr.Error())
return err
}
}

return nil
}


func (r *ServiceAccountReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&corev1.ServiceAccount{}).
Complete(r)
}
19 changes: 19 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"

corev1 "k8s.io/api/core/v1"

opsv1 "alexellis/registry-creds/api/v1"
"alexellis/registry-creds/controllers"
// +kubebuilder:scaffold:imports
Expand All @@ -40,6 +42,7 @@ func init() {
_ = clientgoscheme.AddToScheme(scheme)

_ = opsv1.AddToScheme(scheme)
_ = corev1.AddToScheme(scheme)
// +kubebuilder:scaffold:scheme
}

Expand Down Expand Up @@ -81,6 +84,14 @@ func main() {
setupLog.Error(err, "unable to create controller", "controller", "ClusterPullSecret")
os.Exit(1)
}
if err = (&controllers.ServiceAccountReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("ServiceAccount"),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ServiceAccount")
os.Exit(1)
}
// +kubebuilder:scaffold:builder

if err = (&controllers.NamespaceWatcher{
Expand All @@ -92,6 +103,14 @@ func main() {
setupLog.Error(err, "unable to create watcher", "watcher", "Namespace")
os.Exit(1)
}
if err = (&controllers.ServiceAccountReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("ServiceAccount"),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ServiceAccount")
os.Exit(1)
}
// +kubebuilder:scaffold:builder

setupLog.Info("starting manager")
Expand Down

0 comments on commit 1f32431

Please sign in to comment.