如何让keycloak导出领域用户然后退出

Sha*_*att 4 export realm keycloak

我们在 AWS ECS 中运行 Keycloak docker 映像,我们需要一种使用 ansible 导出领域和所有用户以实现自动化目的的方法。我们可以使用 ansible 运行以下命令来运行导出

docker exec -i 702f2fd7858d \
  /bin/bash -c "export JDBC_PARAMS=?currentSchema=keycloak_service && 
  /opt/jboss/keycloak/bin/standalone.sh \
  -Djboss.socket.binding.port-offset=100 \
  -Dkeycloak.migration.action=export \
  -Dkeycloak.migration.provider=singleFile \
  -Dkeycloak.migration.realmName=API \
  -Dkeycloak.migration.usersExportStrategy=REALM_FILE \
  -Dkeycloak.migration.file=/tmp/my_realm.json"
Run Code Online (Sandbox Code Playgroud)

但 docker 容器在导​​出后继续运行。由于我们使用适用于 Docker 的 AWS 日志驱动程序阻止访问任何日志,因此我们无法 grep 查找导出过程完成的日志。遗憾的是,Keycloak REST API 不支持将用户包含在现有的部分导出端点中,或者至少具有触发将包含用户的领域导出到已安装的归档系统的端点。

Sim*_*ürg 15

几天前我遇到了同样的问题并实施了一个可行的解决方案:

# backup-keycloak.sh

# Copy the export bash script to the (already running) keycloak container
# to perform an export
docker cp docker-exec-cmd.sh keycloak:/tmp/docker-exec-cmd.sh
# Execute the script inside of the container
docker exec -it keycloak /tmp/docker-exec-cmd.sh
# Grab the finished export from the container
docker cp keycloak:/tmp/realms-export-single-file.json .
Run Code Online (Sandbox Code Playgroud)

在容器内执行导出的 Bash 脚本如下:

# docker-exec-cmd.sh

set -o errexit
set -o errtrace
set -o nounset
set -o pipefail

# If something goes wrong, this script does not run forever, but times out
TIMEOUT_SECONDS=300
# Logfile for the keycloak export instance
LOGFILE=/tmp/standalone.sh.log
# destionation export file
JSON_EXPORT_FILE=/tmp/realms-export-single-file.json

# Remove files from old backups inside the container
# You could also move the files or change the name with timestamp prefix
rm -f ${LOGFILE} ${JSON_EXPORT_FILE}

# Start a new keycloak instance with exporting options enabled.
# Use the port offset argument to prevent port conflicts
# with the "real" keycloak instance.
timeout ${TIMEOUT_SECONDS}s \
    /opt/jboss/keycloak/bin/standalone.sh \
        -Dkeycloak.migration.action=export \
        -Dkeycloak.migration.provider=singleFile \
        -Dkeycloak.migration.file=${JSON_EXPORT_FILE} \
        -Djboss.socket.binding.port-offset=99 \
    > ${LOGFILE} &

# Grab the keycloak export instance process id
PID="${!}"

# Wait for the export to finish
# It will wait till it sees the string, which indicates
# a successful finished backup.
# If it will take too long (>TIMEOUT_SECONDS), it will be stopped.
timeout ${TIMEOUT_SECONDS}s \
    grep -m 1 "Export finished successfully" <(tail -f ${LOGFILE})

# Stop the keycloak export instance
kill ${PID}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的解决方案。非常感谢。 (2认同)
  • 警告:如果您要导入大量用户,则实例可能会在脚本本身超时之前超时(默认 300 秒)。为了避免这种情况,您还应该添加标志 -Djboss.as.management.blocking.timeout=${TIMEOUT_SECONDS} (2认同)