Search code examples
gokubernetesconfigmap

Update ConfigMap via Go Kubernetes client


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)

    pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{
        Name: "conf",
        VolumeSource: corev1.VolumeSource{
            ConfigMap: &corev1.ConfigMapVolumeSource{
                LocalObjectReference: corev1.LocalObjectReference{
                    Name: "template-conf",
                },
            },
        },
    })

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:
if (...) {
    ...append(configMap, {
        "hello-world\nhello-world\nhello-world"
    }),
}

Solution

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

    Try:

    // Retrieve the existing ConfigMap
    configMap, err := clientset.CoreV1().ConfigMaps("namespace").Get(context.TODO(), "template-conf", metav1.GetOptions{})
    if err != nil {
        // handle error
    }
    
    // Modify the data in the ConfigMap
    configMap.Data["key1"] = "value1"
    configMap.Data["key2"] = "value2"
    
    // Update the ConfigMap
    updatedConfigMap, err := clientset.CoreV1().ConfigMaps("namespace").Update(context.TODO(), configMap, metav1.UpdateOptions{})
    if err != nil {
        // handle error
    }