I need to set or add a environment variable to a existing kubernetes deployment using golang. It should be added to the config after a restart.
func (r *SparkETLReconciler) DoRestart(w http.ResponseWriter, req *http.Request) {
ctx := context.TODO()
r.Log.Info("restart hit!")
fmt.Fprintf(w, "Hi there, I love %s!", req.URL.Path[1:])
found := &appsv1.Deployment{}
err := r.Get(ctx, types.NamespacedName{
Name: "vmc-etl-test",
Namespace: "ndl",
}, found)
if err != nil {
r.Log.Error(err, "deploy check failed")
} else {
fmt.Fprintf(w, "I found the deployment!")
}
deleteErr := r.DeleteAllOf(ctx, &corev1.Pod{}, client.InNamespace("ndl"), client.MatchingLabels{"operatorETLName": req.URL.Path[1:])
if deleteErr != nil {
r.Log.Error(deleteErr, "deletion of deployment's pods failed")
} else {
fmt.Fprintf(w, "Deployment's pods deleted, restarting")
}
}
CodePudding user response:
After you fetched the your deployment, you can add env variable in the following manner.
# Assuming you have only 1 container in the Pod
found.Spec.Template.Spec.Containers[0].Env = []v1.EnvVar{
{
Name: "ENV_VARIABLE_NAME",
Value: "ENV_VARIABLE_VALUE",
},
}
Needless to say, if you already have some env variables in your container, then you'd better append()
them, otherwise you'll override them.
Also, you'll need to send a call to Update()
(or CreateOrUpdate()
) your deployment.