Read k8s secrets as env varaible in Java spring application.properties

I have to pass env variables in JAVA SpringBoot Application.

I have created k8s secrets. I am passing them in k8s deployment YAML as env variables USER_NAME and USER_PWD.

But How to read these env variables in the application.properties file. I have tried ${USER_NAME} but it's not working.

Ex. from application.properties file.

spring.datasource.username=${USER_NAME}

Upvotes: 1

Views: 3130

Answers (2)

Thank you, It is solved now.

I needed to pass the variables while running the JAR as well.

Ex. from application.properties file.

spring.datasource.username=${USER_NAME}

and in Dockerfile

ENTRYPOINT exec java -DUSER_NAME=$USER_NAME -DUSER_PWD=$USER_PWD -jar jar-name.jar

Upvotes: 1

user8794331
user8794331

Reputation: 31

Your Deployment yml should be like this

kind: Deployment
apiVersion: apps/v1
metadata:
  name: 
spec:
    ...
    spec:
      containers:
        ...
        env:
         - name: spring.datasource.password
           valueFrom:
            secretKeyRef:
             name: your-secret-name
             key: your-secret-key

Kubernetes will add your spring.datasource.password and its value to your pod environment variable.

To make Spring boot use it you should add the property spring.datasource.password in your application.properties or application.yml.

Upvotes: 1

Related Questions