The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Configuración de Kubernetes

Quarkus includes the kubernetes-config extension which allows developers to use Kubernetes ConfigMaps and Secrets as a configuration source, without having to mount them into the Pod running the Quarkus application or make any other modifications to their Kubernetes Deployment (or OpenShift DeploymentConfig).

Configuración

Once you have your Quarkus project configured you can add the kubernetes-config extension by running the following command in your project base directory.

CLI
quarkus extension add kubernetes-config
Maven
./mvnw quarkus:add-extension -Dextensions='kubernetes-config'
Gradle
./gradlew addExtension --extensions='kubernetes-config'

Esto añadirá lo siguiente a su archivo de construcción:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-kubernetes-config</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-kubernetes-config")

Uso

La extensión funciona leyendo ConfigMaps y Secretos directamente desde el servidor de la API de Kubernetes utilizando el Cliente Kubernetes.

La extensión entiende los siguientes tipos de ConfigMaps y Secretos como fuentes de entrada:

  • ConfigMaps y Secretos que contienen datos literales (vea esto para un ejemplo sobre cómo crear uno)

  • ConfigMaps y Secretos creados a partir de archivos denominados application.properties, application.yaml o application.yml (ver aquí un ejemplo de cómo crear uno).

La extensión está desactivada por defecto para evitar que la aplicación realice llamadas a la API cuando no se ejecuta en un entorno Kubernetes. Para habilitarla, configure quarkus.kubernetes-config.enabled=true (por ejemplo, utilizando un perfil específico).

The values of quarkus.kubernetes-config.config-maps and quarkus.kubernetes-config.secrets determine which ConfigMaps and/or Secrets will be used as configuration sources. Keep in mind that these ConfigMaps and Secrets must be in the same Kubernetes Namespace as the running application. If they are to be found in a different namespace, then quarkus.kubernetes-config.namespace must be set to the proper value.

Prioridad de las propiedades obtenidas

Las propiedades obtenidas a partir de los ConfigMaps y Secretos tienen mayor prioridad que (es decir, anulan) cualquier propiedad del mismo nombre que se encuentre en application.properties (o los equivalentes en YAML), pero tienen menor prioridad que las propiedades establecidas a través de Variables de Entorno o Propiedades del Sistema Java.

Además, cuando se utilizan varios ConfigMaps (o Secretos), los ConfigMaps (o Secretos) definidos más tarde en la lista tienen una mayor prioridad que los ConfigMaps definidos anteriormente en la lista.

Por último, cuando se utilizan tanto ConfigMaps como Secretos, estos últimos siempre tienen mayor prioridad que los primeros.

Permisos de Kubernetes

Since reading ConfigMaps involves interacting with the Kubernetes API Server, when RBAC is enabled on the cluster, the ServiceAccount that is used to run the application needs to have the proper permissions for such access.

Afortunadamente, cuando se utiliza la extensión kubernetes-config junto con la extensión Kubernetes, se generan automáticamente todos los recursos Kubernetes necesarios para que esto ocurra.

Secretos

By default, the Kubernetes extension doesn’t generate the necessary resources to allow accessing secrets. Set quarkus.kubernetes-config.secrets.enabled=true to generate the necessary role and corresponding role binding.

Ejemplo de configuración

Un caso de uso muy común es desplegar una aplicación de Quarkus que necesita acceder a una base de datos relacional que a su vez ya ha sido desplegada en Kubernetes. El uso de la extensión quarkus-kubernetes-config hace que este caso de uso sea muy sencillo de manejar.

Supongamos que nuestra aplicación Quarkus necesita hablar con PostgreSQL y que cuando PostgreSQL se desplegó en nuestro clúster Kubernetes, se creó un Secret llamado postgresql como parte de ese despliegue y contiene las siguientes entradas:

  • database-name

  • database-user

  • database-password

Una posible forma de hacer que Quarkus utilice estas entradas para conectar la base de datos es utilizar la siguiente configuración:

%prod.quarkus.kubernetes-config.secrets.enabled=true                            (1)
quarkus.kubernetes-config.secrets=postgresql                                    (2)

%prod.quarkus.datasource.jdbc.url=postgresql://somehost:5432/${database-name}   (3)
%prod.quarkus.datasource.username=${database-user}                              (4)
%prod.quarkus.datasource.password=${database-password}                          (5)
1 Habilitar la lectura de secretos. Tenga en cuenta el uso del perfil %prod ya que sólo queremos que esta configuración se aplique cuando la aplicación se ejecute en producción.
2 Configure el nombre del secreto que se utilizará. No es necesario anteponer el perfil %prod, ya que no tendrá ningún efecto si la lectura del secreto está desactivada.
3 Quarkus sustituirá ${database-name} por el valor obtenido de la entrada con nombre database-name del postgres Secret. somehost es el nombre del Kubernetes Service que se creó cuando se desplegó PostgreSQL en Kubernetes.
4 Quarkus sustituirá ${database-user} por el valor obtenido de la entrada con nombre database-user del postgres Secret.
5 Quarkus sustituirá ${database-password} por el valor obtenido de la entrada con nombre database-password del postgres Secret.

Los valores anteriores permiten que la aplicación sea completamente agnóstica con respecto a la configuración de la base de datos real utilizada en producción, al tiempo que no inhibe la usabilidad de la aplicación en tiempo de desarrollo.

Alternativas

El uso de las extensiones de quarkus-kubernetes-config es completamente opcional, ya que existen otras formas de configurar una aplicación para que utilice ConfigMaps o Secrets.

One common alternative is to map each entry of the ConfigMap and / Secret to an environment variable on the Kubernetes Deployment - see this for more details. To achieve that in Quarkus, we could use the quarkus-kubernetes extension (which is responsible for creating Kubernetes manifests and include the following configuration) and configure it as so:

quarkus.kubernetes.env.secrets=postgresql
quarkus.kubernetes.env.mapping.database-name.from-secret=postgresql
quarkus.kubernetes.env.mapping.database-name.with-key=database-name
quarkus.kubernetes.env.mapping.database-user.from-secret=postgresql
quarkus.kubernetes.env.mapping.database-user.with-key=database-user
quarkus.kubernetes.env.mapping.database-password.from-secret=postgresql
quarkus.kubernetes.env.mapping.database-password.with-key=database-password

%prod.quarkus.datasource.jdbc.url=postgresql://somehost:5432/${database-name}
%prod.quarkus.datasource.username=${database-user}
%prod.quarkus.datasource.password=${database-password}

El resultado final de la configuración anterior sería la siguiente env parte que se aplica el Deployment generado:

          env:
            - name: DATABASE_NAME
              valueFrom:
                secretKeyRef:
                  key: database-name
                  name: postgresql
            - name: DATABASE_USER
              valueFrom:
                secretKeyRef:
                  key: database-user
                  name: postgresql
            - name: DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  key: database-password
                  name: postgresql

Vea esto para más detalles.

Referencia de configuración

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Tipo

Por defecto

Whether configuration can be read from secrets. If set to true, Kubernetes resources allowing access to secrets (role and role binding) will be generated.

Environment variable: QUARKUS_KUBERNETES_CONFIG_SECRETS_ENABLED

Show more

boolean

false

The name of the role.

Environment variable: QUARKUS_KUBERNETES_CONFIG_SECRETS_ROLE_CONFIG_NAME

Show more

string

view-secrets

The namespace of the role.

Environment variable: QUARKUS_KUBERNETES_CONFIG_SECRETS_ROLE_CONFIG_NAMESPACE

Show more

string

Whether the role is cluster wide or not. By default, it’s not a cluster wide role.

Environment variable: QUARKUS_KUBERNETES_CONFIG_SECRETS_ROLE_CONFIG_CLUSTER_WIDE

Show more

boolean

false

If the current role is meant to be generated or not. If not, it will only be used to generate the role binding resource.

Environment variable: QUARKUS_KUBERNETES_CONFIG_SECRETS_ROLE_CONFIG_GENERATE

Show more

boolean

true

If set to true, the application will attempt to look up the configuration from the API server

Environment variable: QUARKUS_KUBERNETES_CONFIG_ENABLED

Show more

boolean

false

If set to true, the application will not start if any of the configured config sources cannot be located

Environment variable: QUARKUS_KUBERNETES_CONFIG_FAIL_ON_MISSING_CONFIG

Show more

boolean

true

ConfigMaps to look for in the namespace that the Kubernetes Client has been configured for. ConfigMaps defined later in this list have a higher priority that ConfigMaps defined earlier in this list. Furthermore, any Secrets defined in secrets, will have higher priorities than all ConfigMaps.

Environment variable: QUARKUS_KUBERNETES_CONFIG_CONFIG_MAPS

Show more

list of string

Secrets to look for in the namespace that the Kubernetes Client has been configured for. If you use this, you probably want to enable quarkus.kubernetes-config.secrets.enabled. Secrets defined later in this list have a higher priority that ConfigMaps defined earlier in this list. Furthermore, these Secrets have a higher priorities than all ConfigMaps defined in configMaps.

Environment variable: QUARKUS_KUBERNETES_CONFIG_SECRETS

Show more

list of string

Namespace to look for config maps and secrets. If this is not specified, then the namespace configured in the kubectl config context is used. If the value is specified and the namespace doesn’t exist, the application will fail to start.

Environment variable: QUARKUS_KUBERNETES_CONFIG_NAMESPACE

Show more

string