import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/kubernetes/pkg/apis/core/v1" "k8s.io/kubernetes/pkg/apis/policy/v1beta1" "k8s.io/kubernetes/pkg/apis/extensions/v1beta1" "k8s.io/kubernetes/pkg/admission" ) type ValidateResourcesAdmissionController struct { decoder runtime.Decoder } func (h *ValidateResourcesAdmissionController) Admit(admissionReview *admission.AdmissionRequest) (*admission.AdmissionResponse, error) { obj := admissionReview.Object.Raw gvk := admissionReview.Kind.GroupVersionKind() switch gvk { case v1.SchemeGroupVersion.WithKind("Pod"): var pod v1.Pod if err := h.decoder.Decode(obj, &pod); err != nil { return nil, err } // Add custom validation logic here case v1beta1.SchemeGroupVersion.WithKind("PodSecurityPolicy"): var psp v1beta1.PodSecurityPolicy if err := h.decoder.Decode(obj, &psp); err != nil { return nil, err } // Add custom validation logic here case v1beta1.SchemeGroupVersion.WithKind("Deployment"): var deployment v1beta1.Deployment if err := h.decoder.Decode(obj, &deployment); err != nil { return nil, err } // Add custom validation logic here default: return &admission.AdmissionResponse{ Allowed: true, }, nil } return &admission.AdmissionResponse{ Allowed: false, Result: &metav1.Status{ Message: "Resource validation failed", Reason: metav1.StatusReasonForbidden, Code: http.StatusForbidden, Details: &metav1.StatusDetails{ Name: gvk.Kind, Group: gvk.Group, Kind: "admission-controller", }, }, }, nil }
type AddLabelsAdmissionController struct { decoder runtime.Decoder } func (h *AddLabelsAdmissionController) Admit(admissionReview *admission.AdmissionRequest) (*admission.AdmissionResponse, error) { obj := admissionReview.Object.Raw gvk := admissionReview.Kind.GroupVersionKind() // Only modify Deployment resources if gvk.Group != "extensions" || gvk.Kind != "Deployment" { return &admission.AdmissionResponse{ Allowed: true, }, nil } var deployment v1beta1.Deployment if err := h.decoder.Decode(obj, &deployment); err != nil { return nil, err } // Add a custom label to the Deployment spec labels := deployment.Spec.Template.Labels if labels == nil { labels = make(map[string]string) } labels["my-custom-label"] = "true" deployment.Spec.Template.Labels = labels marshaled, err := json.Marshal(deployment) if err != nil { return nil, err } return &admission.AdmissionResponse{ Allowed: true, Patch: []types.PatchOperation{ { Op: "replace", Path: "/spec/template/metadata/labels", Value: labels, }, }, PatchType: &types.PatchType{ JSONPatch: "application/json-patch+json", }, Object: runtime.RawExtension{ Raw: marshaled, }, }, nil }This example shows how to implement a Kubernetes admission controller that adds a custom label to Deployment resources. The Admit method decodes the request object into a Deployment resource, modifies the label map, and returns a patch operation that updates the spec/template/metadata/labels path of the resource. Package library: k8s.io/kubernetes/pkg/admission