How to Create and Use ConfigMap with Kubernetes?

Photo of author

By admin

Are you using Kubernetes? Then ConfigMap is the place where you put your applications’ configurations and set connection strings, analytics keys, and service URLs.

You can easily separate the configuration settings and manage the light portable images to build efficient Kubernetes clusters. If you learn how to use ConfigMap with Kubernetes, you can easily manage all your applications and settings from one place. Here, we have shared helpful tips for:

  • How to use ConfigMap in environment variables?
  • How to create it? and
  • How to mount them in volumes?

So, check out this post from the very beginning to know every aspect of ConfigMap in Kubernetes.

What is ConfigMap in Kubernetes? Why Use it?

A configmap is a term for configuration settings that contains key-value pairs of strings. For the containerized applications to work, Kubernetes provides these values to the containers, and these keys help you determine the configuration value.

Configmaps come in the form of an API, and its main focus is to keep the configuration separate from the container image. A ConfigMap can either represent the entire configuration file or individual data.

While working with Kubernetes, developers always look forward to keeping the images light so that they can be portable easily. And for that, you will have to separate the configuration settings from the application code, and ConfigMaps helps you do that.

You can keep different types of configuration data in pods to make sure that the application is running fine in all types of environments. However, you can use the same application code with different configuration settings during the app’s development, testing, and production stage.

Moreover, a configmap is important, especially for the Twelve-Factor applications, which lets developers change the runtime of the applications dynamically.

How does ConfigMap Work?

Firstly, you will need multiple ConfigMaps because each one will act separately in different environments. And you will have to create and add a ConfigMap to the Kubernetes cluster. You will also have to use the value of ConfigMap in the pod reference.

This API object will help you store configurations for other objects to use, and Configmap has data and binaryData fields. Therefore, the fields only accept key-value pairs as values but the data and binaryData fields are optional.

The Data field is there to help developers create UTF-8 byte sequences, and the binary data field only contains binary data. Most of the time and in general, the config files are stored next to the application, or you can also keep them in the same repository.

For every protocol that Kubernetes follows, ConfigMap will follow the same commands. Configmap uses a helm chart to deploy applications. And the chart looks like something like this:

"apiVersion: v1
kind: ConfigMap
metadata:
  name: app
data:
  config.json: |
    {
      "welcome": {{ pluck .Values.global.env .Values.welcome | quote }},
      "name": {{ pluck .Values.global.env .Values.name | quote }}
    }"

If you change the values of these codes during the deployment, you will change the whole content of the ConfigMaps. Only before you create a Configmap on your system, you need to consider a few important things:

  • You need access to a user account with sudo or root privileges.
  • You need access to the command-line or terminal window (Ctrl+Alt+T).
  • Make sure Kubernetes is installed on your computer.

After making sure of these points, you can go ahead and learn how to install ConfigMap on your computer inside the Kubernetes platform.

How to Create a ConfigMap? [Step 1]

It is possible to create configmap from files, literal values, and directories. “kubectl create configmap [configmap_name] [attribute] [source]” is the basic syntax for creating a configmap on Kubernetes. The attributes can be of 2 types, and it is as per the source that you can use these 2 attributes:

  1. –from file (if the source is a file/directory)
  2. –from-literal (if the source is a key-value pair)

To go with the YAML method, you will have to define the ConfigMap in a YAML file first. You can first define the configmap in YAML and then mount the configmap as a value. You can easily create a configmap like you create other Kubernetes resources—using the `kubectl apply -f $file.yaml` code.

After creating, you will have to mount the same ConfigMap, considering it as a volume within your Pod’s YAML specification. Check out how to define the configmap in a YAML file from the section below:

Method 1: Define the ConfigMap in a YAML file

Create a YAML file configuration with the key-value pairs for your ConfigMap using the following code:

“kind: ConfigMap 
apiVersion: v1 
metadata:
  name: example-configmap 
data:
  # Configuration values can be set as key-value properties
  database: mongodb
  database_uri: mongodb://localhost:27017
  # Or set as complete file contents (even JSON!)
  keys: | 
    image.public.key=771 
    rsa.public.key=42”

You will have to create a ConfigMap under the name example-configmap from the example-configmap.YAML file.

But if you don’t want to go with this YAML File option, there are 4 other options that you can try before setting the key-value pairs. So, let’s get to know all of those options first.

Method 2: Create ConfigMap From Files

From the Kubernetes window, you can create a ConfigMap with one or multiple files in plaintext format. However, in order to do so, you will have to make sure that the files contain key-value pairs. Use the following command to create a configmap from files:

“kubectl create configmap [configmap_name] --from-file [path/to/file]”

If there are multiple files and you want to create a single Configmap file from them, you will need to use the following command:

“kubectl create configmap [configmap_name] --from-file [path/to/file1] --from-file [path/to/file2] --from-file [path/to/file3]”

See another option of creating a configmap configuration in the section below.

Method 3: Build a ConfigMap From Directories

You can create a single Configmap with all the files within the directories. Use the following command to create the configuration:

“kubectl create configmap [configmap_name] --from-file [path/to/directory]”

The Kubectl component will pack every file from the directory into the new ConfigMap. Kubectl will only use files with basenames, which are the only valid keys here, and it will minimize the subdirectories and non-regular files from including them in the configmap.

Method 4: Develop a ConfigMap From Literal Values

Use the –from-literal option to create ConfigMaps from literal values, and for that, you need to use the following syntax:

“kubectl create configmap [configmap_name] --from-literal [key1]=[value1] --from-literal [key2]=[value]2”

Mount the ConfigMap through a Volume [Step 2]

Each name in the ConfigMap becomes a new file after the developing and mounting process. The directory is (`/etc/config`)and to mount them, use the following code:

“kind: Pod 
apiVersion: v1 
metadata:
  name: pod-using-configmap
spec:
  # Add the ConfigMap as a volume to the Pod
  volumes:
    # `name` here must match the name
    # specified in the volume mount
    - name: example-configmap-volume
      # Populate the volume with config map data
      configMap:
        # `name` here must match the name 
        # specified in the ConfigMap's YAML 
        name: example-configmap
  containers:
    - name: container-configmap
      image: nginx:1.7.9
      # Mount the volume that contains the configuration data 
      # into your container filesystem
      volumeMounts:
        # `name` here must match the name
        # from the volumes section of this pod
        - name: example-configmap-volume
            mountPath: /etc/config”

You will have to attach the configmap to the created pod with ‘kubectl exec -it

pod-using-configmap sh` command and then run `ls /etc/config`. Once done, you will notice that every key from the ConfigMap has been added as a new file in the directory.

To find the values of the configmap files, you can use the `cat` command that will also allow you to check out the components of each file so that you can find out their values. To check out the configuration settings of the file, use Python/Node.js/PHP.

You can also use environment variables to configure pods and get them to use a specific ConfigMap. Check out the next step to do that.

Use ConfigMap with EnvFrom

ConfigMaps lets you find multiple values in the environment variables, and you can use that advantage for the mounting process. Add the env option in the yaml file of the pod, and you will get the specified environment variables from the newly-created configmap. Use this code:

"env: 
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: [configmap_name] 
              key: [key/file_name]”

To get all the variables from the configmap at once, add this envFrom code to the same YAML file:

"envFrom:
  - configMapKeyRef
      name: env-config”

After that, use the kubectl create command to create the pod with the particular configurations and settings.

Other Ways to Create and Use ConfigMaps

You can use the `kubectl create configmap` command to create Configmap in 3 other different ways. If you don’t feel comfortable with the previous methods, here are your other options:

  • Alternative Method 1: Use the content of an entire directory with the kubectl creates configmap my-config –from-file=./my/dir/path/ command.
  • Alternative Method 2: Use the content of a file, or a specific set of files with the kubectl create configmap my-config –from-file=./my/file.txt command.
  • Alternative Method 3: Use all the literal key-value pairs that are defined in the command line with the kubectl create configmap my-config –from-literal=key1=value1 –from-literal=key2=value2 command.

In case you are having any trouble with one of these methods, you can run the kubectl create configmap –help command. It will guide you.

Why You Should Be Careful with the Configmap Codes?

When you change a ConfigMap, you may encounter 4 different scenarios:

  • First: The Configmap mounted as the subPath volume is changed. And the config file on the Docker container won’t be updated because of that.
  • Second: You have modified and deployed the ConfigMap in the Kubernetes cluster, and you have deleted the pod, and when the new pod comes in, it will mount the updated version of the cluster resource without anyone’s help.
  • Third: We have used the modified ConfigMap’s hash sum in a deployment annotation, but since we have updated the ConfigMap, it has also changed the deployment. Therefore, the old pod will be deleted and automatically replaced by a new one. The new pod will contain the updated version of the resource.
  • Fourth: The mounted directory of the ConfigMap has been modified as well, and the config file in the pod will be updated without restarting the pod.

If any of these changes occur, and you are not okay with it, you can deal with them just as easily. Have a look at the section below that will help you track changes of a ConfigMap in Kubernetes.

Tracking Changes Of Configmap in Kubernetes

Use a simple Go application to monitor the changes and add the following configuration for the process:

"$ cat configfiles/config.json 
{
  "welcome": "Hello",
  "name": "Alice"
}"

After running the code, you will see the following results:

2020/03/03 22:18:22 config: &{Hello Alice}
2020/03/03 22:18:52 config: &{Hello Alice}

You can use ConfigMap as a configuration source to deploy the application to Kubernetes. However, don’t use the file from the image. Use the following code:

“helm install -n configmaps-demo --namespace configmaps-demo ./configmaps-demo --set 'name.production=Alice' --set 'global.env=production'”
"- production: "Alice"
+ production: "Bob"

This will change the configuration. Update the helm chat in the Kubernetes cluster with the following code:

“helm upgrade configmaps-demo ./configmaps-demo --set 'name.production=Bob' --set 'global.env=production”

You can use third-party tools to track changes in your configuration files. Here is what might be helpful in your case.

If your configuration file is accidentally changed, you can use jimmidyson/configmap-reload to send an HTTP request.

Conclusion

If you have a deep understanding of Kubernetes and Configmap, you can easily pull off any problem that comes in your way. Therefore, try to learn and study these as much as possible to understand the details. If you have any questions, feel free to ask them in the comments box below.

Leave a Comment