Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"bytes"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"os"
ctrl "sigs.k8s.io/controller-runtime"
)
func createMutationConfig(caCert *bytes.Buffer) {
var (
webhookNamespace, _ = os.LookupEnv("WEBHOOK_NAMESPACE")
mutationCfgName, _ = os.LookupEnv("MUTATE_CONFIG")
// validationCfgName, _ = os.LookupEnv("VALIDATE_CONFIG") Not used here in below code
webhookService, _ = os.LookupEnv("WEBHOOK_SERVICE")
)
config := ctrl.GetConfigOrDie()
kubeClient, err := kubernetes.NewForConfig(config)
if err != nil {
panic("failed to set go -client")
}
path := "/mutate"
fail := admissionregistrationv1.Fail
mutateconfig := &admissionregistrationv1.MutatingWebhookConfiguration{
ObjectMeta: metav1.ObjectMeta{
Name: mutationCfgName,
},
Webhooks: []admissionregistrationv1.MutatingWebhook{{
Name: "mapplication.kb.io",
ClientConfig: admissionregistrationv1.WebhookClientConfig{
CABundle: caCert.Bytes(), // CA bundle created earlier
Service: &admissionregistrationv1.ServiceReference{
Name: webhookService,
Namespace: webhookNamespace,
Path: &path,
},
},
Rules: []admissionregistrationv1.RuleWithOperations{{Operations: []admissionregistrationv1.OperationType{
admissionregistrationv1.Create},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
},
}},
FailurePolicy: &fail,
}},
}
if _, err := kubeClient.AdmissionregistrationV1().MutatingWebhookConfigurations().Create(mutateconfig)
err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment