How to pass the DB AWS secret into tomcat context.xml?

2.5k views Asked by At

I have a context.xml where I am connecting to DB.

<?xml version='1.0' encoding='utf-8'?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

<Resource name="jdbc/SS" 
        auth="Container"
        type="javax.sql.DataSource"
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" 
        username="a***b"
        password="C********1"
        driverClassName="org.postgresql.Driver"
        url="jdbc:postgresql://**********:****/a***b"
        maxActive="100"
        maxIdle="50"
        minIdle="10"
        testWhileIdle="true"
        maxWait="30000"  
        maxAge="60000"
        removeAbandoned="true" 
        removeAbandonedTimeout="600" />
</Context>

I need to get the DB credentials from the secret manager and pass the values into the context.xml by replacing the hardcoded DB credentials.

Is there any way to achieve this?

1

There are 1 answers

1
Dudi Boy On

If you want to load the DB credential dynamically. It is possible to only for the time Tomcat is loading context.xml once (because Tomcat read environment variable only once at startup).

Notice that at runtime, whenever contxt.xml change the relevant web application reloads. Tomcat is not restarted.

So the trick is to deliver DB credentials as JVM parameter/argument, like the above ${catalina.base}

There are 3 stages:

  1. Declare and set value to the environment variable:

    export DB_CREDENTIALS='*****'
    

    Good place is at Tomcat's user login script.bash_profile, or Tomcat environments setenv.sh

  2. Create a JVM parameter (system variable) for environment variable: add the following line to setenv.sh before the last line.

    -Denvironment.db.credentials=${DB_CREDENTIALS} \
    
  3. Use/call the declared JVM parameter in context.xml. For example:

    url="jdbc:postgresql://**********:****/${environment.db.credentials}"