How do I pass an environment variable to the application.conf using the Datastax Java Cassandra Driver

148 views Asked by At

I have the current application.conf...

datastax-java-driver {
  basic.contact-points = ["192.168.23.1:9042"]
  basic {
    load-balancing-policy {
      local-datacenter = datacenter1
    }
  }
  advanced.metrics {
    factory.class = MicrometerMetricsFactory
  }
  advanced.request.warn-if-set-keyspace = false
  advanced.auth-provider {
    class = PlainTextAuthProvider
    username = cassandra
    password = cassandra
  }
  profiles {
    slow {
      basic.request.timeout = 10 seconds
    }
  }
}

I also have a env var with the IP address DOCKER_IP. I tried

basic.contact-points = ["${DOCKER_IP}:9042"]

But it didn't work and instead defaulted to the local computer.

2

There are 2 answers

0
absurdfarce On

The answer offered by @Madhavan above is absolutely correct. For sake of completeness I wanted to expand on it just a bit.

The Java driver uses the Typesafe Config lib to perform it's configuration. That lib provides a couple different methods for overriding config values at runtime. Out of the box you can override any config value by providing a system property that exactly matches the config name. So to override the specified contact points you could use the following flag when invoking the JVM:

-Ddatastax-java-driver.basic.contact-points.1='1.2.3.4:9042'

The ".1" suffix is added here because "contact-points" is an array of values; see the docs for more detail.

The second option is to enable environment variable overrides for config values and then provide the appropriate env var. To enable this feature you should provide the following system property:

-Dconfig.override_with_env_vars=true

You can then provide the value for any config variable via an environment variable. For example, to accomplish the same replacement specified above you might use the following env var:

CONFIG_FORCE_datastax__java__driver_basic_contact__points_0="1.2.3.4:9042"

You can find additional information about the "CONFIG_FORCE_" prefix and the rules around translating config property names into environment variables in the Typesafe Config docs referenced above.

1
Madhavan On

@clunven suggested that it is possible and here is an example where it is done.

TL;DR

set it as contact-points = [${CASSANDRA_CONTACT_POINTS}] and the env variable is set as CASSANDRA_CONTACT_POINTS: "cassandra:9042" as an example.