@@ -30,6 +30,9 @@ const (
30
30
podsInitContainerPatch string = `[
31
31
{"op":"add","path":"/spec/initContainers","value":[{"image":"webhook-added-image","name":"webhook-added-init-container","resources":{}}]}
32
32
]`
33
+ podsSidecarPatch string = `[
34
+ {"op":"add", "path":"/spec/containers/-","value":{"image":"%v","name":"webhook-added-sidecar","resources":{}}}
35
+ ]`
33
36
)
34
37
35
38
// only allow pods to pull images from specific registry.
@@ -77,6 +80,42 @@ func admitPods(ar v1.AdmissionReview) *v1.AdmissionResponse {
77
80
}
78
81
79
82
func mutatePods (ar v1.AdmissionReview ) * v1.AdmissionResponse {
83
+ shouldPatchPod := func (pod * corev1.Pod ) bool {
84
+ if pod .Name != "webhook-to-be-mutated" {
85
+ return false
86
+ }
87
+ return ! hasContainer (pod .Spec .InitContainers , "webhook-added-init-container" )
88
+ }
89
+ return applyPodPatch (ar , shouldPatchPod , podsInitContainerPatch )
90
+ }
91
+
92
+ func mutatePodsSidecar (ar v1.AdmissionReview ) * v1.AdmissionResponse {
93
+ if sidecarImage == "" {
94
+ return & v1.AdmissionResponse {
95
+ Allowed : false ,
96
+ Result : & metav1.Status {
97
+ Status : "Failure" ,
98
+ Message : "No image specified by the sidecar-image parameter" ,
99
+ Code : 500 ,
100
+ },
101
+ }
102
+ }
103
+ shouldPatchPod := func (pod * corev1.Pod ) bool {
104
+ return ! hasContainer (pod .Spec .Containers , "webhook-added-sidecar" )
105
+ }
106
+ return applyPodPatch (ar , shouldPatchPod , fmt .Sprintf (podsSidecarPatch , sidecarImage ))
107
+ }
108
+
109
+ func hasContainer (containers []corev1.Container , containerName string ) bool {
110
+ for _ , container := range containers {
111
+ if container .Name == containerName {
112
+ return true
113
+ }
114
+ }
115
+ return false
116
+ }
117
+
118
+ func applyPodPatch (ar v1.AdmissionReview , shouldPatchPod func (* corev1.Pod ) bool , patch string ) * v1.AdmissionResponse {
80
119
klog .V (2 ).Info ("mutating pods" )
81
120
podResource := metav1.GroupVersionResource {Group : "" , Version : "v1" , Resource : "pods" }
82
121
if ar .Request .Resource != podResource {
@@ -93,8 +132,8 @@ func mutatePods(ar v1.AdmissionReview) *v1.AdmissionResponse {
93
132
}
94
133
reviewResponse := v1.AdmissionResponse {}
95
134
reviewResponse .Allowed = true
96
- if pod . Name == "webhook-to-be-mutated" {
97
- reviewResponse .Patch = []byte (podsInitContainerPatch )
135
+ if shouldPatchPod ( & pod ) {
136
+ reviewResponse .Patch = []byte (patch )
98
137
pt := v1 .PatchTypeJSONPatch
99
138
reviewResponse .PatchType = & pt
100
139
}
0 commit comments