1

I have to inject DB URL, DB Username and Password variables into a Java Spring Boot Application. I know that these properties reside in the application.properties file under res/ folder.

Now as a design change I want to adopt K8s ConfigMaps and Secrets to be used in place of hardcoding in the the application.properties file.

How can I link the CMs and Secrets from K8s to the application. How should I set placeholders in application.properties file?

Does defining the CM and Secret dependency in application deployment.yaml does everything?

2 Answers2

2

You have two options: one can be achieved without extra dependencies and one with Spring Boot Cloud.

Plain way

You define enviroment variable placeholders in your application.yml:

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}
    username: ${DB_USER}
    password: ${DB_PASSWORD}

You then define the environment variables in your k8s deployment:

env:
    - name: DB_HOST
      valueFrom:
        configMapKeyRef:
          name: your-config-map
          key: dbHost
    - name: DB_PORT
      valueFrom:
        configMapKeyRef:
          name: your-config-map
          key: dbPort
    - name: DB_NAME
      valueFrom:
        configMapKeyRef:
          name: your-config-map
          key: dbName
    - name: DB_USER
      valueFrom:
        secretKeyRef:
          name: your-secret
          key: dbUser
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: your-secret
          key: dbPassword

More on defining environment variables for containers can be found in the k8s documentation.

Spring Boot Cloud Kubernetes

There is a whole section in the reference called Using a ConfigMap PropertySource and Secrets PropertySource. I suggest you go and look it up there.

times29
  • 2,782
  • 2
  • 21
  • 40
1

First you need to enable spring.cloud.kubernetes.secrets.enabled then you can use Kubernetes Secrets via SecretsPropertySource.

You can use secret name via: -Dspring.cloud.kubernetes.secrets.name=my-secret where my-sercret is name of a secret which is defined in kubernetes. or you can access it in multiple other methods described in the Documentation.

Aref Riant
  • 582
  • 3
  • 14