How can I add a env variable to a kubernetes deployment using golang?

huangapple go评论88阅读模式
英文:

How can I add a env variable to a kubernetes deployment using golang?

问题

我需要使用Golang设置或添加一个环境变量到一个已存在的Kubernetes部署中。在重新启动后,它应该被添加到配置中。

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")
	}
}

请注意,这只是一个代码片段,你需要根据你的实际需求进行适当的修改和集成。

英文:

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")
	}
}

答案1

得分: 0

在获取到你的部署之后,你可以按照以下方式添加环境变量。

# 假设你的 Pod 中只有一个容器
found.Spec.Template.Spec.Containers[0].Env = []v1.EnvVar{
		{
			Name:  "ENV_VARIABLE_NAME",
			Value: "ENV_VARIABLE_VALUE",
		},
}

当然,如果你的容器中已经有一些环境变量,最好使用 append() 方法将它们添加进去,否则会覆盖原有的环境变量。

此外,你需要调用 Update()(或 CreateOrUpdate())来更新你的部署。

英文:

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.

huangapple
  • 本文由 发表于 2022年12月8日 02:30:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/74721392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定