addlabel.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "encoding/json"
  16. "k8s.io/api/admission/v1beta1"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/klog"
  19. )
  20. const (
  21. addFirstLabelPatch string = `[
  22. { "op": "add", "path": "/metadata/labels", "value": {"added-label": "yes"}}
  23. ]`
  24. addAdditionalLabelPatch string = `[
  25. { "op": "add", "path": "/metadata/labels/added-label", "value": "yes" }
  26. ]`
  27. )
  28. // Add a label {"added-label": "yes"} to the object
  29. func addLabel(ar v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
  30. klog.V(2).Info("calling add-label")
  31. obj := struct {
  32. metav1.ObjectMeta
  33. Data map[string]string
  34. }{}
  35. raw := ar.Request.Object.Raw
  36. err := json.Unmarshal(raw, &obj)
  37. if err != nil {
  38. klog.Error(err)
  39. return toAdmissionResponse(err)
  40. }
  41. reviewResponse := v1beta1.AdmissionResponse{}
  42. reviewResponse.Allowed = true
  43. if len(obj.ObjectMeta.Labels) == 0 {
  44. reviewResponse.Patch = []byte(addFirstLabelPatch)
  45. } else {
  46. reviewResponse.Patch = []byte(addAdditionalLabelPatch)
  47. }
  48. pt := v1beta1.PatchTypeJSONPatch
  49. reviewResponse.PatchType = &pt
  50. return &reviewResponse
  51. }