How to mount the kubernetes secret(DB credentials) in tomcat context.xml

1k views Asked by At

I am trying to mount the DB credentials stored in kubernetes secret in tomcat context.xml I am able to print the value as follows

echo "${DB_USERNAME}"

XXXX

I have a secret db-credentials as follows.

 apiVersion: v1
 kind: Secret
 metadata:
    name: db-credentials
 type: Opaque
 data:
    username: XXXX
    password: XXXX

I have mounted the secret in deployment.xml and as follows

    containers:
    - name: java
      image: XXXXXXXX:v1.1
      imagePullPolicy: Always
      restartPolicy: OnFailure
      env:
      - name: DB_USERNAME
        valueFrom:
         secretKeyRef:
          name: db-credentials
          key: username
     - name: DB_PASSWORD
       valueFrom:
        secretKeyRef:
          name: db-credentials
          key: password
     volumeMounts:
     - name: shared-data
       mountPath: /usr/local/tomcat/log

my tomcat context.xml as follows

<?xml version='1.0' encoding='utf-8'?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Resource name="jdbc/XXX" 
        auth="Container"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" 
        username="${DB_USERNAME}"
        password="${DB_PASSWORD}"
        driverClassName="org.postgresql.Driver"
        url="jdbc:postgresql://XXXX:XXXX/XXXX"
        maxActive="100"
        maxIdle="50"
        minIdle="10"
        testWhileIdle="true"
        maxWait="30000"  
        maxAge="60000"
        removeAbandoned="true" 
        removeAbandonedTimeout="600" />
</Context>

I am getting as follows

    javax.naming.NamingException: FATAL: password authentication failed for user "${DB_USERNAME}"
    at org.apache.naming.NamingContext.lookup(NamingContext.java:858)
    
1

There are 1 answers

0
rakesh On

create a file setenv.sh in /otp/tomcat/bin

add the following lines

export JAVA_OPTS="$JAVA_OPTS -DDB_USERNAME=${DB_USERNAME}"
export JAVA_OPTS="$JAVA_OPTS -DDB_PASSWORD=${DB_PASSWORD}"

restart the tomcat will solve the issue.