Saltar al contenido

Plantillas de Helm en Archivos: Cómo Personalizar el Contenido de ConfigMaps Simplificado en 10 Minutos

Las plantillas de Helm en archivos, como el contenido de ConfigMaps o el contenido de Secrets, son uno de los requisitos más comunes cuando estás en el proceso de crear un nuevo gráfico de helm. Como ya sabes, el gráfico de Helm es cómo usamos Kubernetes para empaquetar nuestros recursos de aplicación y YAML en un solo componente que podemos gestionar de una vez para facilitar el proceso de mantenimiento y operación.

Visión General de las Plantillas de Helm

Por defecto, el proceso de plantillas funciona con archivos YAML, permitiéndonos usar algunas variables y algunas funciones lógicas para personalizar y templar nuestros recursos YAML de Kubernetes según nuestras necesidades.

Entonces, en resumen, solo podemos tener archivos yaml dentro de la carpeta de plantillas de un YAML. Pero a veces nos gustaría hacer el mismo proceso en ConfigMaps o Secrets o ser más concretos con el contenido de esos ConfigMaps, por ejemplo, archivos de propiedades y así sucesivamente.

Plantillas de Helm en Archivos: Cómo Personalizar el Contenido de ConfigMaps Simplificado
Plantillas de Helm en Archivos: Visión General de las Plantillas de Helm mostrando los Archivos fuera de las plantillas que usualmente se requieren

Como puedes ver, es bastante normal tener diferentes archivos como archivos de configuración json, archivos de propiedades, scripts de shell como parte de tu gráfico de helm, y la mayoría de las veces te gustaría dar un enfoque dinámico a su contenido, y es por eso que usar Plantillas de Helm en Archivos es tan importante para ser el enfoque principal de este artículo

Funciones de Ayuda de Helm para Gestionar Archivos

Por defecto, Helm nos proporciona un conjunto de funciones para gestionar archivos como parte del gráfico de helm para simplificar el proceso de incluirlos como parte del gráfico, como el contenido de ConfigMap o Secret. Algunas de estas funciones son las siguientes:

  • .Files.Glob: Esta función permite encontrar cualquier patrón de archivos internos que coincida con el patrón, como el siguiente ejemplo:
    { range $path, $ := .Files.Glob ".yaml" }
  • .Files.Get: Esta es la opción más simple para reunir el contenido de un archivo específico que conoces la ruta completa dentro de tu gráfico de helm, como el siguiente ejemplo: {{ .Files.Get "config1.toml" | b64enc }}

Incluso puedes combinar ambas funciones para usarlas juntas como en el siguiente ejemplo:

 {{ range $path, $_ :=  .Files.Glob  "**.yaml" }}
      {{ $.Files.Get $path }}
{{ end }}

Luego puedes combinar eso una vez que tengas el archivo que deseas usar con algunas funciones de ayuda para introducir fácilmente en un ConfigMap y un Secret como se explica a continuación:

  • .AsConfig : Usa el contenido del archivo para ser introducido como ConfigMap manejando el patrón: nombre-del-archivo: contenido-del-archivo
  • .AsSecrets: Similar al anterior, pero haciendo la codificación base64 para los datos.

Aquí puedes ver un ejemplo real de usar este enfoque en una situación real de gráfico de helm:

apiVersion: v1
kind: Secret
metadata:
  name: zones-property
  namespace: {{ $.Release.Namespace }}
data: 
{{ ( $.Files.Glob "tml_zones_properties.json").AsSecrets | indent 2 }} 

Puedes encontrar más información sobre eso aquí. Pero esto solo nos permite tomar el archivo tal cual e incluirlo en un ConfigMap. No nos permite hacer ninguna lógica o sustitución al contenido como parte de ese proceso. Entonces, si queremos modificar esto, este no es un ejemplo válido.

¿Cómo Usar Plantillas de Helm en Archivos como ConfigMaps o Secrets?

En caso de que podamos hacer algunas modificaciones al contenido, necesitamos usar la siguiente fórmula:

apiVersion: v1
kind: Secret
metadata:
  name: papi-property
  namespace: {{ $.Release.Namespace }}
data:
{{- range $path, $bytes := .Files.Glob "tml_papi_properties.json" }}
{{ base $path | indent 2 }}: {{ tpl ($.Files.Get $path) $ | b64enc }}
{{ end }}

Entonces, lo que estamos haciendo aquí es primero iterar por los archivos que coinciden con el patrón usando la función .Files.Glob que explicamos antes, iterando en caso de que tengamos más de uno. Luego creamos manualmente la estructura siguiendo el patrón: nombre-del-archivo: contenido-del-archivo.

Para hacer eso, usamos la función base para proporcionar solo el nombre del archivo desde una ruta completa (y agregar la indentación adecuada) y luego usamos .Files.Get para obtener el contenido del archivo y hacer la codificación base64 usando la función b64enc porque, en este caso, estamos manejando un secreto.

El truco aquí es agregar la función tpl que permite que el contenido de este archivo pase por el proceso de plantillas; así es como todas las modificaciones que necesitamos hacer y las variables referenciadas desde el objeto .Values serán reemplazadas adecuadamente, dándote todo el poder y flexibilidad del Gráfico de Helm en archivos de texto como propiedades, archivos JSON y mucho más.

¡Espero que esto sea tan útil para ti como lo ha sido para mí al crear nuevos gráficos de helm! Y mira aquí para otros trucos usando bucles o dependencias.

Etiquetas:

Helm Templates in Files: How To Customize ConfigMaps Content Simplified in 10 Minutes

Helm Templates in Files, such as ConfigMaps Content or Secrets Content, is of the most common requirements when you are in the process of creating a new helm chart. As you already know, Helm Chart is how we use Kubernetes to package our application resources and YAML in a single component that we can manage at once to ease the maintenance and operation process.

Helm Templates Overview

By default, the template process works with YAML files, allowing us to use some variables and some logic functions to customize and templatize our Kubernetes YAML resources to our needs.

So, in a nutshell, we can only have yaml files inside the templates folder of a YAML. But sometimes we would like to do the same process on ConfigMaps or Secrets or to be more concrete to the content of those ConfigMaps, for example, properties files and so on.

Helm Templates in Files: How To Customize ConfigMaps Content Simplified
Helm Templates in Files: Helm Templates Overview Overview showing the Files outside the templates that are usually required

As you can see it is quite normal to have different files such as json configuration file, properties files, shell scripts as part of your helm chart, and most of the times you would like to give some dynamic approach to its content, and that’s why using helm Templates in Files it is so important to be the main focus for this article

Helm Helper Functions to Manage Files

By default, Helm provides us with a set of functions to manage files as part of the helm chart to simplify the process of including them as part of the chart, such as the content of ConfigMap or Secret. Some of these functions are the following:

  • .Files.Glob: This function allows to find any pattern of internal files that matches the pattern, such as the following example:
    { range $path, $ := .Files.Glob ".yaml" }
  • .Files.Get: This is the simplest option to gather the content of a specific file that you know the full path inside your helm chart, such as the following sample: {{ .Files.Get "config1.toml" | b64enc }}

You can even combine both functions to use together such as in the following sample:

 {{ range $path, $_ :=  .Files.Glob  "**.yaml" }}
      {{ $.Files.Get $path }}
{{ end }}

Then you can combine that once you have the file that you want to use with some helper functions to easily introduce in a ConfigMap and a Secret as explained below:

  • .AsConfig : Use the file content to be introduced as ConfigMap handling the pattern: file-name: file-content
  • .AsSecrets: Similar to the previous one, but doing the base64 encoding for the data.

Here you can see a real example of using this approach in an actual helm chart situation:

apiVersion: v1
kind: Secret
metadata:
  name: zones-property
  namespace: {{ $.Release.Namespace }}
data: 
{{ ( $.Files.Glob "tml_zones_properties.json").AsSecrets | indent 2 }} 

You can find more information about that here. But this only allows us to grab the file as is and include it in a ConfigMap. It is not allowing us to do any logic or any substitution to the content as part of that process. So, if we want to modify this, this is not a valid sample.

How To Use Helm Templates in Files Such as ConfigMaps or Secrets?

In case we can do some modifications to the content, we need to use the following formula:

apiVersion: v1
kind: Secret
metadata:
  name: papi-property
  namespace: {{ $.Release.Namespace }}
data:
{{- range $path, $bytes := .Files.Glob "tml_papi_properties.json" }}
{{ base $path | indent 2 }}: {{ tpl ($.Files.Get $path) $ | b64enc }}
{{ end }}

So, here we are doing is first iterating for the files that match the pattern using the .Files.Glob function we explained before, iterating in case we have more than one. Then we manually create the structure following the pattern : file-name: file-content.

To do that, we use the function base to provide just the filename from a full path (and add the proper indentation) and then use the .Files.Get to grab the file’s content and do the base64 encoding using the b64encfunction because, in this case, we’re handling a secret.

The trick here is adding the tpl function that allows this file’s content to go through the template process; this is how all the modifications that we need to do and the variables referenced from the .Values object will be adequately replaced, giving you all the power and flexibility of the Helm Chart in text files such as properties, JSON files, and much more.

I hope this is as useful for you as it has been for me in creating new helm charts! And Look here for other tricks using loops or dependencies.

Deja una respuesta

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