Saltar al contenido

Metadatos de Kubernetes: Potencia tus aplicaciones con contenido de tus pods

black laptop computer turned on on table

Descubre cómo extraer toda la información disponible para inyectarla en tus pods

Empodera tus pods con contenido de tu metadata de Kubernetes

Foto de James Harrison en Unsplash

La metadata de Kubernetes es cómo accederás a parte de la información de tus pods en tu aplicación en tiempo de ejecución. Cuando te mueves de un tipo de desarrollo tradicional a uno nativo de la nube, usualmente necesitas acceder a alguna información disponible de manera predeterminada en un entorno convencional.

Esto sucede especialmente cuando hablamos de una plataforma que en el pasado se desplegaba en cualquier plataforma que estaba poblada con información como el nombre de la aplicación, versión, dominio, etc. Pero esto es complicado en un enfoque nativo de la nube. O tal vez no, pero al menos por algún tiempo, te has estado preguntando cómo puedes acceder a parte de la información que conoces sobre tu carga de trabajo nativa de la nube, para que la aplicación en ejecución dentro del pod también la conozca.

Porque cuando defines un nativo de la nube, describes mucha información muy relevante. Por ejemplo, pensemos en eso. Cuando inicias tu pod, conoces el nombre de tu pod porque es tu nombre de host:

Pero cuando defines tu carga de trabajo, tienes un nombre de despliegue; ¿cómo puedes obtenerlo desde tu pod? ¿Cómo obtienes en qué espacio de nombres se ha desplegado tu pod? ¿O qué hay de toda la metadata que definimos como etiquetas y anotaciones?

Lo bueno es que hay una manera de obtener cada dato que hemos comentado, así que no te preocupes; obtendrás toda esta información disponible para usar si la necesitas.

La forma estándar de acceder a cualquier información es a través de variables de entorno. Esta es la forma tradicional en que proporcionamos datos iniciales a nuestro pod. Ya hemos visto que sabemos que podemos usar ConfigMaps para poblar variables de entorno, pero esta no es la única manera de proporcionar datos a nuestros pods. Hay mucho más, así que échale un vistazo.

Descubriendo la opción fieldRef

Cuando discutimos el uso de ConfigMap como variables de entorno, teníamos dos maneras de poblar esa información. Proporcionando todo el contenido de ConfigMap, en cuyo caso usamos la opción envFrom, también podemos usar valueFrom y proporcionar el nombre del configMap y la misma clave de la que nos gustaría obtener el valueFrom.

Así que, siguiendo el enfoque de esta sección, tenemos un comando aún más útil llamado fieldRef. fieldRef es el nombre del comando para una referencia a un campo, y podemos usarlo dentro de la directiva valueFrom. En resumen, podemos proporcionar una referencia de campo como un valor para una clave de variable de entorno.

Así que echemos un vistazo a los datos que podemos obtener de este objeto:

  • metadata.name: Esto obtiene el nombre del pod como un valor para un valor de entorno
  • metadata.namespace: Proporciona el espacio de nombres en el que el pod está ejecutándose como el valor
  • metadata.labels[LABELNAME]: Extrae el valor de la etiqueta como el valor para la clave de entorno
  • metadata.annotations[ANNOTATIONNAME]: Extrae el valor de la anotación como valor para la clave de entorno

Aquí puedes ver un fragmento que define diferentes variables de entorno usando esta metadata como el valor para que puedas usarlo dentro del pod simplemente recopilándolo como variables de entorno estándar:

        env:
        - name: APP_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['app']
        - name: DOMAIN_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['domain']
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name 

Yendo aún más allá

Pero esto no es todo lo que la opción fieldRef puede proporcionar, hay mucho más, y si te gustaría echar un vistazo, puedes hacerlo aquí:

Kubernetes Metadata: Empower Your Apps With Content From Your Pods.

black laptop computer turned on on table

Discover how to extract all the information available to inject it into your pods

Empower Your Pods With Content From Your Kubernetes Metadata

Photo by James Harrison on Unsplash

Kubernetes Metadata is how you will access some of the information from your pods in your application at runtime. When you are moving from a traditional kind of development to a cloud-native one, you usually need to access some out-of-the-box information available in a conventional environment.

This happens especially when we are talking about a platform that in the past was deployed on any platform that was populated with some information such as application name, version, domain, and so on. But this is tricky in a cloud-native approach. Or maybe not, But at least for some time, you have been wondering how you can get access to some of the information you know about your cloud-native workload, so the running application inside the pod knows it as well.

Because when you define a cloud-native, you describe a lot of very relevant information. For example, let’s think about that. When you start your pod, you know your pod name because it is your hostname:

But when you define your workload, you have a deployment name; how can you get it from your pod? How do you get which namespace your pod has been deployed to? Or what about all the metadata we define as labels and annotations?

The good thing is that there is a way to get any single data we have commented on, so don’t worry; you will get all this information available to use if you need to.

The standard way to access any information is through environment variables. This is the traditional way that we provide initial data to our pod. We already have seen we know we can use ConfigMaps to populate environment variables, but this is not the only way to provide data to our pods. There is much more, so take a look at it.

Discovering the fieldRef option

When we discussed using ConfigMap as environment variables, we had two ways to populate that information. Providing all the ConfigMap content, in which case we used the envFrom option, we can also use the valueFrom and provide the configMap name and the same key we would like to get the valueFrom.

So, following this section approach, we have an even more helpful command called fieldRef. fieldRef is the command name for a reference to a field, and we can use it inside the valueFrom directive. In a nutshell, we can provide a field reference as a value to an environment variable key.

So let’s take a look at the data that we can get from this object:

  • metadata.name: This gets the pod name as a value for an environment value
  • metadata.namespace: Provides the namespace that the pod is running as the value
  • metadata.lables[LABELNAME]: Extract the value of the label as the value for the environment key
  • metadata.annotations[ANNOTATIONNAME]: Extract the value of the annotation as value for the environment key

So here, you can see a snippet that defines different environment variables using this metadata as the value so you can use it inside the pod just gathering as standard environment variables:

        env:
        - name: APP_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['app']
        - name: DOMAIN_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['domain']
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name 

Going Even Beyond

But this is not everything that the fieldRef option can provide, there is much more, and if you would like to take a look, you can do it here:

Deja una respuesta

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