Quantcast
Channel: All – akquinet – Blog
Viewing all articles
Browse latest Browse all 133

Dynamic container configuration (using KeyCloak as an example)

$
0
0

Docker images often are parameterized through startup arguments or environment variables. There are often situations however, where certain aspects cannot be configured this way. Instead, you either have to create images for all possible configurations, or implement an extended configuration strategy.

In this article we show how to parameterize a KeyCloak container with dynamic redirect URIs at startup. The general approach may be used for other applications as well.

KeyCloak

A KeyCloak realm needs to be configured with valid “redirect URIs”, i.e. a list of plain URIs or patterns the browser may be redirected to after successful login. In a containerized environment these URIs usually cannot be configured statically, if you do not want to restrict the application to hard-coded patterns.

What we do is to extend the standard startup process by adding our own entrypoint.sh script in the Dockerfile:

FROM quay.io/keycloak/keycloak:24.0.4
...
VOLUME /opt/keycloak/startup-scripts
ENTRYPOINT ["/opt/keycloak/bin/entrypoint.sh"]

This script mainly contains code to start the dynamic configuration in background (and give KeyCloak some time to startup itself):

#!/usr/bin/env bash

(sleep 10 ; /opt/keycloak/bin/startup_scripts.sh) &

exec /opt/keycloak/bin/kc.sh "$@"

We simply try to login to KC’s admin console and wait for this command to succeed.

waitForKeyCloak() {
  local start="Failed"

  while [[ $start =~ "Failed" || $start =~ "null" || $start =~ "404" || $start =~ "Invalid" ]]; do
    ./kcadm.sh config credentials --server "http://localhost:8080/auth" --realm master --user admin --password 'secret!' &> /tmp/start
    start=$(</tmp/start)

    sleep 5
  done
}

Configure redirect URIs

Finally, we run our script (placed in the mounted volume) that configures KeyCloak using an environment variable defined at startup, e.g. in a docker-compose.yml file.

#!/bin/bash

redirectUris="[\"https://localhost:11143/*\", \"https://${HOST_HOSTNAME,,}:11143/*\"]"

echo "******************* Configure Redirect URIs ${redirectUris} *******************"

./kcadm.sh update -r myrealm clients/myclient -s rootUrl="https:///${HOST_HOSTNAME,,}:14043"
./kcadm.sh update -r myrealm clients/myclient -s adminUrl="https:///${HOST_HOSTNAME,,}/auth/admin"
./kcadm.sh update clients/myclient -r myrealm -s redirectUris="$redirectUris"

echo "******************* Redirect URIs configured *******************"

Viewing all articles
Browse latest Browse all 133

Trending Articles