Saltar al contenido

¿Por qué deberías potenciar los ConfigMaps en tus implementaciones de Kubernetes?

black and silver laptop computer beside yellow ceramic mug
computadora portátil negra y plateada al lado de una taza de cerámica amarilla
Foto por Sigmund en Unsplash

ConfigMaps es uno de los objetos más conocidos y, al mismo tiempo, menos utilizados en el ecosistema de Kubernetes. Es uno de los objetos principales que ha estado allí desde el principio, incluso si probamos muchas otras formas de implementar una solución de Gestión de Configuración (como Consul, Spring Cloud Config y otros).

Basado en las palabras de su propia documentación:

Un ConfigMap es un objeto API utilizado para almacenar datos no confidenciales en pares clave-valor.

https://kubernetes.io/docs/concepts/configuration/configmap/

Su motivación fue proporcionar una solución nativa para la gestión de configuraciones para implementaciones nativas de la nube. Una forma de gestionar e implementar configuraciones enfocándose en un código diferente de la configuración. Ahora, todavía recuerdo los archivos WAR con el archivo application.properties dentro de él.

ConfigMap es un recurso tan simple como puedes ver en el fragmento a continuación:

apiVersion: v1
kind: ConfigMap
metadata:
  name: game-demo
data:
  player_initial_lives: "3"
  ui_properties_file_name: "user-interface.properties"

Los ConfigMaps son objetos que pertenecen a un namespace. Tienen una fuerte relación con Deployment y Pod y permiten la opción de tener diferentes entornos lógicos usando namespace donde pueden implementar la misma aplicación. Aún así, con una configuración específica, por lo que necesitarán un configMap particular para soportar eso, incluso si se basa en el mismo archivo YAML de recursos.

Desde una perspectiva técnica, el contenido del ConfigMap se almacena en la base de datos etcd como sucede con cualquier información relacionada con el entorno de Kubernetes, y debes recordar que etcd por defecto no está cifrado, por lo que todos los datos pueden ser recuperados por cualquiera que tenga acceso a él.

Propósitos de los ConfigMaps

Parámetros de Configuración

El primer y principal propósito del configMap es proporcionar parámetros de configuración a tu carga de trabajo. Una forma industrializada de eliminar la necesidad de variables de entorno es vincular la configuración del entorno desde tu aplicación.

Proporcionar Archivos Dependientes del Entorno

Otro uso significativo es proporcionar o reemplazar archivos dentro de tus contenedores que contengan el archivo de configuración crítica. Uno de los ejemplos principales que ilustra esto es proporcionar una configuración de registro para tu aplicación si tu aplicación está utilizando la biblioteca logback. En este caso, necesitas proporcionar un archivo logback.xml, para que sepa cómo aplicar tu configuración de registro.

Otras opciones pueden ser propiedades. El archivo necesita estar ubicado allí o incluso certificados de clave pública para manejar conexiones SSL solo con servidores en lista segura.

Carpetas de Solo Lectura

Otra opción es usar el ConfigMap como una carpeta de solo lectura para proporcionar una forma inmutable de vincular información al contenedor. Un caso de uso de esto puede ser los Dashboards de Grafana que estás agregando a tu pod de Grafana (si no estás usando el operador de Grafana)

Diferentes formas de crear un ConfigMap

Tienes varias formas de crear un ConfigMap usando el modo interactivo que simplifica su creación. Aquí están las que más uso:

Crear un configMap para alojar pares clave-valor con fines de configuración

kubectl create configMap name  --from-literal=key=value

Crear un configMap usando un archivo de propiedades similar a Java para poblar el ConfigMap en un par clave-valor.

 kubectl create configMap name --from-env-file=filepath

Crear un configMap usando un archivo para ser parte del contenido del ConfigMap

 kubectl create configMap name --from-file=filepath

 Ciclo de Vida de Actualización del ConfigMap

Los ConfigMaps se actualizan de la misma manera que cualquier otro objeto de Kubernetes, y puedes usar incluso los mismos comandos como kubctl apply para hacerlo. Pero debes tener cuidado porque una cosa es actualizar el ConfigMap en sí y otra cosa es que el recurso que usa este ConfigMap se actualice.

En todos los casos de uso que hemos descrito aquí, el contenido del ConfigMap depende del ciclo de vida del Pod. Eso significa que el contenido del ConfigMap se lee en el proceso de inicialización del Pod. Por lo tanto, para actualizar los datos del ConfigMap dentro del pod, necesitarás reiniciar o traer una nueva instancia del pod después de haber modificado el objeto ConfigMap en sí.

Etiquetas:

Why You Should Empower ConfigMaps in Your Kubernetes Deployments?

black and silver laptop computer beside yellow ceramic mug
black and silver laptop computer beside yellow ceramic mug
Photo by Sigmund on Unsplash

ConfigMaps is one of the most known and, at the same time, less used objects in the Kubernetes ecosystem. It is one of the primary objects that has been there from the beginning, even if we tried so many other ways to implement a Config Management solution (such as Consul, Spring Cloud Config, and others).

Based on its own documentation words:

A ConfigMap is an API object used to store non-confidential data in key-value pairs.

https://kubernetes.io/docs/concepts/configuration/configmap/

Its motivation was to provide a native solution for configuration management for cloud-native deployments. A way to manage and deploy configuration focusing on different code from the configuration. Now, I still remember the WAR files with the application.properties file inside of it.

ConfigMap is a resource as simple as you can see in the snippet below:

apiVersion: v1
kind: ConfigMap
metadata:
  name: game-demo
data:
  player_initial_lives: "3"
  ui_properties_file_name: "user-interface.properties"

ConfigMaps are objects that belong to a namespace. They have a strong relationship with Deployment and Pod and enable the option to have different logical environments using namespace where they can deploy the same application. Still, with a specific configuration, so they will need a particular configMap to support that, even if it is based on the same resource YAML file.

From a technical perspective, the content of the ConfigMap is stored in the etcd database as it happens for any information that is related to the Kubernetes environment, and you should remember that etcd by default is not encrypted, so all the data can be retrieved for anyone that has access to it.

Purposes of ConfigMaps

Configuration Parameters

The first and foremost purpose of the configMap is to provide configuration parameters to your workload. An industrialized way to remove the need for env variables is to link the environment configuration from your application.

Providing Environment Dependent Files

Another significant usage is providing or replacing files inside your containers containing the critical configuration file. One of the primary samples that illustrate this is to give a logging configuration for your app if your app is using the logback library. In this case, you need to provide a logback.xml file, so it knows how to apply your logging configuration.

Other options can be properties. The file needs to be located there or even public-key certificates to handle SSL connections with safelisted servers only.

Read-Only Folders

Another option is to use the ConfigMap as a read-only folder to provide an immutable way to link information to the container. One use-case of this can be Grafana Dashboards that you are adding to your Grafana pod (if you are not using the Grafana operator)

Different ways to create a ConfigMap

You have several ways to create a ConfigMap using the interactive mode that simplifies its creation. Here are the ones that I use the most:

Create a configMap to host key-value pairs for configuration purposes

kubectl create configMap name  --from-literal=key=value

Create a configMap using a Java-like properties file to populate the ConfigMap in a key-value pair.

 kubectl create configMap name --from-env-file=filepath

Create a configMap using a file to be part of the content of the ConfigMap

 kubectl create configMap name --from-file=filepath

 ConfigMap Refresh Lifecycle

ConfigMaps are updated in the same way as any other Kubernetes object, and you can use even the same commands such as kubctl apply to do that. But you need to be careful because one thing is to update the ConfigMap itself and another thing is that the resource using this ConfigMap is updated.

In all the use-cases that we have described here, the content of the ConfigMap depends on the Pod’s lifecycle. That means that the content of the ConfigMap is read on the initialization process of the Pod. So to update the ConfigMap data inside the pod, you will need to restart or bring a new instance of the pod after you have modified the ConfigMap object itself.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *