Skip to content

Instantly share code, notes, and snippets.

@lawrencejones
Created January 9, 2019 16:48
Show Gist options
  • Save lawrencejones/66dde895f6f40d25e5fbc47d9fbd259d to your computer and use it in GitHub Desktop.
Save lawrencejones/66dde895f6f40d25e5fbc47d9fbd259d to your computer and use it in GitHub Desktop.
Annotate configmaps with author
package main
import (
"context"
"net/http"
"os"
kitlog "github.com/go-kit/kit/log"
"github.com/lawrencejones/theatre/pkg/signals"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
apitypes "k8s.io/apimachinery/pkg/types"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp" // this is required to auth against GCP
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/builder"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission/types"
)
var logger = kitlog.NewLogfmtLogger(os.Stderr)
type configmapAnnotator struct {
mgr manager.Manager
}
func (a *configmapAnnotator) Handle(ctx context.Context, req types.Request) types.Response {
cfgmap := &corev1.ConfigMap{}
if err := a.mgr.GetAdmissionDecoder().Decode(req, cfgmap); err != nil {
admission.ErrorResponse(http.StatusBadRequest, err)
}
username := req.AdmissionRequest.UserInfo.Username
copy := cfgmap.DeepCopy()
copy.ObjectMeta.Annotations = map[string]string{"author": username}
logger.Log("username", username, "configmap", cfgmap.Name)
return admission.PatchResponse(cfgmap, copy)
}
func main() {
mgr, _ := manager.New(config.GetConfigOrDie(), manager.Options{})
wh, _ := builder.NewWebhookBuilder().
Mutating().
Operations(admissionregistrationv1beta1.Create).
ForType(&corev1.ConfigMap{}).
Handlers(&configmapAnnotator{mgr}).
WithManager(mgr).
Build()
svr, _ := webhook.NewServer("author-admission-server", mgr, webhook.ServerOptions{
CertDir: "/tmp/cert",
BootstrapOptions: &webhook.BootstrapOptions{
Secret: &apitypes.NamespacedName{
Namespace: "theatre-system",
Name: "theatre-author-admission-server",
},
Service: &webhook.Service{
Namespace: "theatre-system",
Name: "theatre-author-admission-server",
// Selectors should select the pods that runs this webhook server.
Selectors: map[string]string{
"app": "theatre-dev",
},
},
},
})
svr.Register(wh)
ctx, cancel := signals.SetupSignalHandler()
defer cancel()
if err := mgr.Start(ctx.Done()); err != nil {
panic(err)
}
// spew.Dump(svr.Register(wh))
// spew.Dump(svr.InstallWebhookManifests())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment