<p>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.</p>
<p>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.</p>
<p>How can I link the CMs and Secrets from K8s to the application. How should I set placeholders in application.properties file?</p>
<p>Does defining the CM and Secret dependency in application deployment.yaml does everything?</p>

Mayank Singh Rathore
<p>You have two options: one can be achieved without extra dependencies and one with Spring Boot Cloud.</p>
<h2>Plain way</h2>
<p>You define enviroment variable placeholders in your <code>application.yml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}
    username: ${DB_USER}
    password: ${DB_PASSWORD}
</code></pre>
<p>You then define the environment variables in your k8s deployment:</p>
<pre class="lang-yaml prettyprint-override"><code>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
</code></pre>
<p>More on defining environment variables for containers can be found in the <a href="https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/" rel="nofollow noreferrer">k8s documentation</a>.</p>
<h2>Spring Boot Cloud Kubernetes</h2>
<p>There is a whole section in the reference called <a href="https://docs.spring.io/spring-cloud-kubernetes/docs/current/reference/html/#configmap-propertysource" rel="nofollow noreferrer">Using a ConfigMap PropertySource</a> and <a href="https://docs.spring.io/spring-cloud-kubernetes/docs/current/reference/html/#secrets-propertysource" rel="nofollow noreferrer">Secrets PropertySource</a>. I suggest you go and look it up there.</p>
