Home > Backend Development > Golang > How to add environment variables to kubernetes deployment using golang?

How to add environment variables to kubernetes deployment using golang?

王林
Release: 2024-02-08 23:45:28
forward
585 people have browsed it

如何使用 golang 将环境变量添加到 kubernetes 部署?

php editor Apple brings you an article on how to use golang to add environment variables to Kubernetes deployment. In Kubernetes deployment, the setting of environment variables is very important and can help us configure the behavior of the application. Using golang, you can easily inject environment variables into Kubernetes Pods to achieve more flexible and configurable deployment. Next, we will detail how to use golang to achieve this goal.

Question content

I need to set or add environment variables to an existing kubernetes deployment using golang. It should be added to the configuration after reboot.

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")
    }
}
Copy after login

Solution

After getting deployed, you can add environment variables in the following ways.

# 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",
        },
}
Copy after login

Needless to say, if you already have some environment variables in your container, you'd better append() them, otherwise you'll be overwriting them.

Additionally, you need to send a call to update() (or createorupdate()) in your deployment.

The above is the detailed content of How to add environment variables to kubernetes deployment using golang?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template