Paco Abato
Paco Abato

Reputation: 4065

How to pass DB connection parameters to Keycloak on a dokerized environment

I'm working with a Keycloak server that runs inside a Docker container.

I developed an User Storage Provider to connect to the client DB in search of users info and login validation.

I wrote the DB connection properties inside the code but now it's time to do it correctly like providing that info to the Docker container when it starts and getting this info from code.

I guess that my UserStorageProviderFactory's init(Config.Scope config) method is the place where to look for these parameters. There the config parameter contains the info from the file standalone.xml but I would need to pass the connection parameters to Docker on startup so they can be easily modified.

How can I get it this way?

Upvotes: 3

Views: 2784

Answers (2)

Xiangjiaox
Xiangjiaox

Reputation: 306

You can use a jboss-cli script to add your UserStorageProvider to the standalone/-ha.xml with properties that can be set by environment variables which you pass to the container.

Example:

Say we have a spi.cli script with the following:

/subsystem=keycloak-server/spi=my-spi/provider=my-custom-auth-provider:add(enabled=true,properties={"my.custom.property", "${env.MY_ENV:myDefaultValue}"})

This can be put in /opt/jboss/startup-scripts folder in the container to automatically run on startup, see Keycloak docker documentation.

When run it will generate the following in standalone:

<spi name="my-spi">
    <provider enabled="true" name="my-custom-auth-provider">
        <properties>
            <property name="my.custom.property" value="${env.MY_ENV:myDefaultValue}"/>
        </properties>
    </provider>
</spi>

These properties can then be accessed in code using Config.Scope in the init method. E.g config.get("my.custom-property").

This will then retrieve the value passed to the container, -e MY_ENV=test_value.

Upvotes: 3

Paco Abato
Paco Abato

Reputation: 4065

The Docker container must be run with -e option like:

-e ENV_VAR_1=env_var_value1

It may containt as much -e options as needed. Other way is to use --env-file option to append the variables contained in a file.

Then in the User Storage Provider code you can check the value of the environment variable like:

System.getenv("ENV_VAR_1")

Upvotes: 1

Related Questions