Skip to content

Instantly share code, notes, and snippets.

@Yapcheekian
Created March 4, 2022 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yapcheekian/5e4ed28bf24018cdd7d34b305e5c5d23 to your computer and use it in GitHub Desktop.
Save Yapcheekian/5e4ed28bf24018cdd7d34b305e5c5d23 to your computer and use it in GitHub Desktop.
mutating webhook in k8s
package mutator
import (
"encoding/json"
"log"
"net/http"
admission "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func Mutation(w http.ResponseWriter, r *http.Request) {
ar := new(admission.AdmissionReview)
err := json.NewDecoder(r.Body).Decode(ar)
if err != nil {
handleError(w, nil, err)
return
}
pod := &corev1.Pod{}
if err := json.Unmarshal(ar.Request.Object.Raw, pod); err != nil {
handleError(w, ar, err)
return
}
for i := 0; i < len(pod.Spec.Containers); i++ {
pod.Spec.Containers[i].Env = append(pod.Spec.Containers[i].Env, corev1.EnvVar{
Name: "DEBUG",
Value: "true",
})
}
containersBytes, err := json.Marshal(&pod.Spec.Containers)
if err != nil {
handleError(w, ar, err)
return
}
patch := []JSONPatchEntry{
{
OP: "replace",
Path: "/spec/containers",
Value: containersBytes,
},
}
patchBytes, err := json.Marshal(&patch)
if err != nil {
handleError(w, ar, err)
return
}
patchType := admission.PatchTypeJSONPatch
response := &admission.AdmissionResponse{
UID: ar.Request.UID,
Allowed: true,
Patch: patchBytes,
PatchType: &patchType,
}
responseAR := &admission.AdmissionReview{
TypeMeta: metav1.TypeMeta{
Kind: "AdmissionReview",
APIVersion: "admission.k8s.io/v1",
},
Response: response,
}
json.NewEncoder(w).Encode(responseAR)
}
type JSONPatchEntry struct {
OP string `json:"op"`
Path string `json:"path"`
Value json.RawMessage `json:"value,omitempty"`
}
func handleError(w http.ResponseWriter, ar *admission.AdmissionReview, err error) {
if err != nil {
log.Println("[Error]", err.Error())
}
response := &admission.AdmissionResponse{
Allowed: false,
}
if ar != nil {
response.UID = ar.Request.UID
}
ar.Response = response
json.NewEncoder(w).Encode(ar)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment