implement kcadm and changes to allow kcadm.sh to authenticate

in order to run kcadm.sh commands the script must authenticate to the REST API.
this commit includes an init_kc command that replaces the bootstrap user with
a permanent admin user (whose password is a docker swarm secret) that can be
used to authenticate before running kcadm commands. this reuses the secret
'admin_password' that was previously used as the password for the bootstrap
admin user.
This commit is contained in:
2026-03-31 12:56:03 -04:00
parent a5c314f891
commit c6eb27e10c
3 changed files with 33 additions and 2 deletions

View File

@ -5,7 +5,9 @@ DOMAIN=keycloak.example.com
#EXTRA_DOMAINS=', `www.keycloak.example.com`'
LETS_ENCRYPT_ENV=production
BOOTSTRAP_PASSWORD=
ADMIN_USERNAME=admin
ADMIN_EMAIL=
WELCOME_THEME=keycloak
COMPOSE_FILE="compose.yml"

28
abra.sh Normal file
View File

@ -0,0 +1,28 @@
#!/bin/bash
run_kcadm() {
bin/sh -c "/opt/keycloak/bin/kcadm.sh $@"
}
login_kcadm() {
KC_PW=$(cat /run/secrets/admin_password)
run_kcadm "config credentials --server http://localhost:8080 --realm master --user ${ADMIN_USERNAME} --password ${KC_PW}"
}
init_kc() {
run_kcadm "config credentials --server http://localhost:8080 --realm master --user admin_bootstrap --password ${BOOTSTRAP_PASSWORD}"
# CREATE NEW ADMIN USER
ADMIN_PW=$(cat /run/secrets/admin_password)
run_kcadm "create users -r master -s username=${ADMIN_USERNAME} -s email='${ADMIN_EMAIL}' -s emailVerified=true -s enabled=true"
run_kcadm "set-password -r master --username ${ADMIN_USERNAME} --new-password ${ADMIN_PW}"
run_kcadm "add-roles --uusername ${ADMIN_USERNAME} --rolename admin"
# AUTHENTICATE WITH NEW ADMIN USER
run_kcadm "config credentials --server http://localhost:8080 --realm master --user admin --password ${ADMIN_PW}"
# DEMOTE BOOTSTRAP ADMIN IN CASE WE CAN'T DELETE
run_kcadm "remove-roles -r master --uusername ${KEYCLOAK_ADMIN} --rolename admin --rolename default-roles-master"
# JSON MUNGING
BOOTSTRAP_ID=$(run_kcadm "get users -q username=admin_bootstrap --limit 1 --fields id | grep id | cut -d : -f2 | tr -d [:space:]")
run_kcadm "delete -r master users/${BOOTSTRAP_ID}"
}

View File

@ -2,7 +2,7 @@ services:
app:
image: "keycloak/keycloak:26.5.4"
entrypoint: >
bash -c "KEYCLOAK_ADMIN_PASSWORD=\"$$(cat /run/secrets/admin_password)\" KC_DB_PASSWORD=\"$$(cat /run/secrets/db_password)\" /opt/keycloak/bin/kc.sh start"
bash -c "KEYCLOAK_ADMIN_PASSWORD=\"$$BOOTSTRAP_PASSWORD\" KC_DB_PASSWORD=\"$$(cat /run/secrets/db_password)\" /opt/keycloak/bin/kc.sh start"
networks:
- proxy
- internal
@ -16,7 +16,8 @@ services:
- KC_HOSTNAME=https://${DOMAIN}
- KC_PROXY=edge
- KC_SPI_CONNECTIONS_JPA_LEGACY_MIGRATION_STRATEGY=update
- KEYCLOAK_ADMIN=${ADMIN_USERNAME}
# admin_bootstrap will be superceded by $ADMIN_USERNAME on init_kc
- KEYCLOAK_ADMIN=admin_bootstrap
- KEYCLOAK_WELCOME_THEME=${WELCOME_THEME}
- KC_PROXY_HEADERS=xforwarded
- KC_HTTP_ENABLED=true