Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable
Secure database connection strings in Spring microservices using environment variables and placeholder expressions for the hostname using the properties file.
Join the DZone community and get the full member experience.
Join For FreeManaging database connection strings securely for any microservice is critical; often, we secure the username and password using the environment variables and never factor in masking or hiding the database hostname. In reader and writer database instances, there would be a mandate in some organizations not to disclose the hostname and pass that through an environment variable at runtime during the application start. This article discusses configuring the hostname through environment variables in the properties file.
Database Configurations Through Environment Variables
We would typically configure the default connection string for Spring microservices in the below manner, with the database username and password getting passed as the environment variables.
server.port=8081
server.servlet.context-path=/api/e-sign/v1
spring.esign.datasource.jdbc-url=jdbc:mysql://localhost:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false
spring.esign.datasource.username=${DB_USER_NAME}
spring.esign.datasource.password=${DB_USER_PASSWORD}
spring.esign.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.esign.datasource.minimumIdle=5
spring.esign.datasource.maxLifetime=120000
If our microservice connects to a secure database with limited access and the database administrator or the infrastructure team does not want you to provide the database hostname, then we have an issue. Typically, the production database hostname would be something like below:
spring.esign.datasource.jdbc-url=jdbc:mysql://prod-db.fabrikam.com:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false
spring.esign.datasource.username=${DB_USER_NAME}
spring.esign.datasource.password=${DB_USER_PASSWORD}
Using @Configuration Class
In this case, the administrator or the cloud infrastructure team wants them to provide the hostname as an environment variable at runtime when the container starts. One of the options is to build and concatenate the connection string in the configuration class as below:
@Configuration
public class DatabaseConfig {
private final Environment environment;
public DatabaseConfig(Environment environment) {
this.environment = environment;
}
@Bean
public DataSource databaseDataSource() {
String hostForDatabase = environment.getProperty("ESIGN_DB_HOST", "localhost:3306");
String dbUserName = environment.getProperty("DB_USER_NAME", "user-name");
String dbUserPassword = environment.getProperty("DB_USER_PASSWORD", "user-password");
String url = String.format("jdbc:mysql://%s/e-sign?allowPublicKeyRetrieval=true&useSSL=false", hostForDatabase);
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(dbUserName); // Replace with your actual username
dataSource.setPassword(dbUserPassword); // Replace with your actual password
return dataSource;
}
}
The above approach would work, but we need to use the approach with application.properties
, which is easy to use and quite flexible. The properties file allows you to collate all configurations in a centralized manner, making it easier to update and manage. It also improves readability by separating configuration from code. The DevOps team can update the environment variable values without making code changes.
Environment Variable for Database Hostname
Commonly, we use environment variables for database username and password and use the corresponding expression placeholder expressions ${}
in the application properties file.
spring.esign.datasource.username=${DB_USER_NAME}
spring.esign.datasource.password=${DB_USER_PASSWORD}
However, for the database URL, we need to use the environment variable only for the hostname and not for the connection string, as each connection string for different microservices would have different parameters. So, to address this, Spring allows you to have the placeholder expression within the connection string shown below; this gives flexibility and the ability to stick with the approach of using the application.properties
file instead of doing it through the database configuration class.
spring.esign.datasource.jdbc-url=jdbc:mysql://${ESIGN_DB_HOST}:3306/e-sign?allowPublicKeyRetrieval=true&useSSL=false
Once we have decided on the above approach and if we need to troubleshoot any issue for whatever reason in lower environments, we can then use the ApplicationListener
interface to see the resolved URL:
@Component
public class ApplicationReadyLogger implements ApplicationListener<ApplicationReadyEvent> {
private final Environment environment;
public ApplicationReadyLogger(Environment environment) {
this.environment = environment;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
String jdbcUrl = environment.getProperty("spring.esign.datasource.jdbc-url");
System.out.println("Resolved JDBC URL: " + jdbcUrl);
}
}
If there is an issue with the hostname configuration, it will show as an error when the application starts. However, after the application has been started, thanks to the above ApplicationReadyLogger
implementation, we can see the database URL in the application logs. Please note that we should not do this in production environments where the infrastructure team wants to maintain secrecy around the database writer hostname.
Using the above steps, we can configure the database hostname as an environment variable in the connection string inside the application.properties
file.
Conclusion
Using environment variables for database hostnames to connect to data-sensitive databases can enhance security and flexibility and give the cloud infrastructure and DevOps teams more power. Using the placeholder expressions ensures that our configuration remains clear and maintainable.
Opinions expressed by DZone contributors are their own.
Comments