I wrote a mutating webhook for kubernetes to add default class to new ingress object.
The core part is this:
func patch( annotations map[string]string, name string) []byte {
var patches []Patch
if len(annotations) == 0 {
klog.V(0).Infof("New annotation to %v.
", name)
patchNew := Patch{"add", "/metadata/annotations", map[string]string{}}
patches = append(patches, patchNew)
}
if _, ok := annotations[key]; !ok {
klog.V(0).Infof("Added class %v to %v.
", Class, name)
patchAdd := Patch{"add", "/metadata/annotations/" + strings.Replace(key, "/", "~1", -1), Class}
patches = append(patches, patchAdd)
} else {
klog.V(0).Info("No need to add class.
")
}
bytes, _ := json.Marshal(patches)
return bytes
}
It works, but it feels quite clumsy. Does this solution make sense, or is there an easier way to achieve the same result?
(I don't do much go programming, any improvements welcome.)