@@ -101,27 +101,44 @@ func injectionDeploy(request *admissionv1.AdmissionRequest) (*admissionv1.Admiss
101101 }, nil
102102 }
103103 target := deploy .DeepCopy ()
104+ added := false
104105 for k , v := range envs {
106+ // Check if the environment variable already exists
107+ exists := false
108+ for _ , env := range target .Spec .Template .Spec .Containers [0 ].Env {
109+ if env .Name == k {
110+ exists = true
111+ break
112+ }
113+ }
114+ // If it exists, skip adding it
115+ if exists {
116+ continue
117+ }
118+ // Add the environment variable
105119 target .Spec .Template .Spec .Containers [0 ].Env = append (target .Spec .Template .Spec .Containers [0 ].Env , corev1.EnvVar {Name : k , Value : v })
120+ added = true
106121 }
107122 log .Infof ("[mutation] /injection-deploy: add envs to deployment %s/%s, envs: %v, deploy's envs: %v" ,
108123 deploy .Name , deploy .Namespace , envs , target .Spec .Template .Spec .Containers [0 ].Env )
109- patchStr , err := createDeployPatch (target , & deploy )
110- if err != nil {
124+ if added {
125+ patchStr , err := createDeployPatch (target , & deploy )
126+ if err != nil {
127+ return & admissionv1.AdmissionResponse {
128+ UID : request .UID ,
129+ Allowed : true ,
130+ }, nil
131+ }
111132 return & admissionv1.AdmissionResponse {
112133 UID : request .UID ,
113134 Allowed : true ,
135+ Patch : patchStr ,
136+ PatchType : func () * admissionv1.PatchType {
137+ pt := admissionv1 .PatchTypeJSONPatch
138+ return & pt
139+ }(),
114140 }, nil
115141 }
116- return & admissionv1.AdmissionResponse {
117- UID : request .UID ,
118- Allowed : true ,
119- Patch : patchStr ,
120- PatchType : func () * admissionv1.PatchType {
121- pt := admissionv1 .PatchTypeJSONPatch
122- return & pt
123- }(),
124- }, nil
125142 } else {
126143 log .Warnf ("[mutation] /injection-deploy: the deployment %s/%s does not have the %s or %s label" ,
127144 deploy .Name , deploy .Namespace , config .ServiceSpaceLabel , config .ApplicationLabel )
0 commit comments