read kubernetes secrets mounted as volume in application.properties spring boot application

8/31/2021

I created kubenertes secret

echo -n 'myusername' > username.txt
echo -n 'pa55word' > password.txt
kubectl create secret generic esb-database-secret-vol --from-file=username.txt --from-file=password.txt

I created pod manifest as

spec:
  containers:
  - image: data-api-0.0.1.jar
    ports:
    - containerPort: 8080
    name: esb-data-api
    imagePullPolicy: Never
    resources: {}
    volumeMounts:
    - name: esb-secret-vol
      mountPath: "/etc/confidential"
      readOnly: true
  volumes:
  - name: esb-secret-vol
    secret:
      secretName: esb-database-secret-vol

I verified that secrets now available in pod /etc/confidential folder

How does these values be available in application.properties so that I can get DB connection

spring.datasource.url=jdbc:sqlserver://mycompany.com;databaseName=My_DB
# need to read from /etc/confidential/username.txt
spring.datasource.username=??????
# need to read from /etc/confidential/password.txt  
spring.datasource.password=??????
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
-- user3058642
kubernetes
kubernetes-secrets
spring-boot
spring-cloud

1 Answer

8/31/2021

You have several options:

  1. Provide the data already in properly written properties files
  2. Use an init container to use the secret data and create properties files using a shell script

The first approach would look like

echo 'spring.datasource.username=myusername' >> app.properties
echo 'spring.datasource.password=pa55word' >> app.properties
kubectl create secret generic esb-database-secret-vol --from-file=app.properties

You would later mount the secret as application.properties in the container.

-- Thomas
Source: StackOverflow