通过Go Kubernetes客户端更新ConfigMap

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

Update ConfigMap via Go Kubernetes client

问题

我正在使用Go k8客户端将ConfigMap卷挂载到一个Pod上,其中template-conf是一个文件(在命名空间中部署的helm yaml)。

  1. pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{
  2. Name: "conf",
  3. VolumeSource: corev1.VolumeSource{
  4. ConfigMap: &corev1.ConfigMapVolumeSource{
  5. LocalObjectReference: corev1.LocalObjectReference{
  6. Name: "template-conf",
  7. },
  8. },
  9. },
  10. })

我想知道在Go中是否可以实现以下操作,或者是否有解决方法:

  1. 用另一个文件替换整个configMap文件的内容。
  2. 向configMap文件追加更多行。类似于以下代码:
  1. if (...) {
  2. ...append(configMap, {
  3. "hello-world\nhello-world\nhello-world"
  4. }),
  5. }
英文:

I am mounting a ConfigMap volume to a pod using Go k8 cient where template-conf is a file (deployed helm yaml in the namespace)

  1. pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{
  2. Name: "conf",
  3. VolumeSource: corev1.VolumeSource{
  4. ConfigMap: &corev1.ConfigMapVolumeSource{
  5. LocalObjectReference: corev1.LocalObjectReference{
  6. Name: "template-conf",
  7. },
  8. },
  9. },
  10. })

I was wondering if the following are possible to do in Go or if there's a workaround:

  1. Replacing the entire contents of the configMap file with another file
  2. Appending more lines to the configMap file. So something like this:
  1. if (...) {
  2. ...append(configMap, {
  3. "hello-world\nhello-world\nhello-world"
  4. }),
  5. }

答案1

得分: 1

ConfigMap 资源不是设计成直接通过替换整个内容或追加行来修改的。

尝试以下操作:

  1. // 检索现有的 ConfigMap
  2. configMap, err := clientset.CoreV1().ConfigMaps("namespace").Get(context.TODO(), "template-conf", metav1.GetOptions{})
  3. if err != nil {
  4. // 处理错误
  5. }
  6. // 修改 ConfigMap 中的数据
  7. configMap.Data["key1"] = "value1"
  8. configMap.Data["key2"] = "value2"
  9. // 更新 ConfigMap
  10. updatedConfigMap, err := clientset.CoreV1().ConfigMaps("namespace").Update(context.TODO(), configMap, metav1.UpdateOptions{})
  11. if err != nil {
  12. // 处理错误
  13. }

请注意,这是一个示例代码片段,你需要根据自己的实际情况进行适当的修改。

英文:

ConfigMap resource is not designed to be modified directly by replacing the entire contents or appending lines.

Try:

  1. // Retrieve the existing ConfigMap
  2. configMap, err := clientset.CoreV1().ConfigMaps("namespace").Get(context.TODO(), "template-conf", metav1.GetOptions{})
  3. if err != nil {
  4. // handle error
  5. }
  6. // Modify the data in the ConfigMap
  7. configMap.Data["key1"] = "value1"
  8. configMap.Data["key2"] = "value2"
  9. // Update the ConfigMap
  10. updatedConfigMap, err := clientset.CoreV1().ConfigMaps("namespace").Update(context.TODO(), configMap, metav1.UpdateOptions{})
  11. if err != nil {
  12. // handle error
  13. }

huangapple
  • 本文由 发表于 2023年7月11日 02:37:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656448.html
匿名

发表评论

匿名网友

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

确定