ConfigMap

A ConfigMap is an API object used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.

A ConfigMap allows you to decouple environment-specific configuration from your container images, so that your applications are easily portable.

App: Get Config From ENV

We already have and app that will return a JSON response {"message":"Success"}. Let's make it configurable so our apps will check the environment variable DEFAULT_MESSAGE and use the value as message in our response.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "os"
)

type Response struct {
    Message string `json:"message,omitempty"`
}

func main() {
    // get default message from env
    message := os.Getenv("DEFAULT_MESSAGE")
    if message == "" {
        // fallback message
        message = "Success"
    }

    srv := http.NewServeMux()
    srv.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        res := Response{
            Message: message,
        }

        err := json.NewEncoder(w).Encode(res)
        if err != nil {
            log.Fatal(err)
        }
    })

    fmt.Println("Server is running on port 8080...")
    err := http.ListenAndServe(":8080", srv)
    if err != nil {
        log.Fatal(err)
    }
}

Try to run it with additional environment variable like this DEFAULT_MESSAGE="k8s" go run main.go and it should return k8s as the message when we access it.

Build our apps again using command docker build --tag simple-go . so the new image will available in kubernetes docker images.

Define ConfigMap

Let's create a new file called configmap.yaml and define our ConfigMap object in there.

This will create a ConfigMap object with name simple-go-config. The data section is key value pair for our config. In here we have config data with key DEFAULT_MESSAGE and value "Everything is fine!".

Lets apply it using command kubectl apply -f configmap.yaml. And check it using kubectl get configmaps. We should see simple-go-config in the list there.

We can also get the details of it using command kubectl describe configmaps simple-go-config.

Bind ConfigMap in Deployment

Now that we already setup a ConfigMap we need to update our deployment config to set environment variable with name DEFAULT_MESSAGE and get the value from ConfigMap named simple-go-config and key DEFAULT_MESSAGE.

Apply the deployment and we should see a new sets of pods created replacing the old pods.

Now let's do a port-forward to one of the pods and access our apps with curl.

Our app now should return response message "Everything is fine!" like this.

Whenever we update a ConfigMap we also need to restart our pods so it will get the latest config available.

References

Last updated