やりたいこと
Red Hat build of Keycloak(Keycloakの商用版)にてAdmin API経由でユーザを作成した際にその応答結果から新規作成されたユーザのユーザーID(id)を取得する。
環境情報
- Red Hat Enterprise Linux : 9.3 (Plow)
- rhbk-22.0.8
- curl 7.76.1 (x86_64-redhat-linux-gnu)
やり方
ユーザー作成時のcurlにて-Dオプションを利用してファイルに出力をさせると
$ curl -D location.txt --request POST 'http://localhost:8080/admin/realms/master/users' --header 'Content-Type: application/json' --header "Authorization: Bearer $AT" --data-raw '{"enabled":"true", "username":"xx","credentials":[{"type":"password","value":"xx","temporary":false}]}'出力したファイルのLocation欄にユーザのIDが格納されている。
$ cat location.txt HTTP/1.1 201 Created Referrer-Policy: no-referrer X-Frame-Options: SAMEORIGIN Strict-Transport-Security: max-age=31536000; includeSubDomains X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Location: http://localhost:8080/admin/realms/master/users/xx-xx-xx-xx-xx content-length: 0
以下、補足です。
補足
ユーザ名を引数としてリストしたユーザ一覧から以下のようにidを取得することも可能ですが、APIの発行数が増えてしまいます。
jq -r '.[] | select(.username == "hogehoge") | .id'
よってユーザのidだけを取得したい場合はLocationから情報を抜き出す方が便利です。
一点注意が必要なのは、出力されるファイルはデフォルトだと特殊な改行が入っています。
$ file location.txt location.txt: ASCII text, with CRLF line terminators
このようなファイルを単純に処理すると想定外の結果になる場合があるので、trコマンド等で処理をする必要があります。
$ tr -d '\r' < location.txt > new_location.txt $ file new_location.txt new_location.txt: ASCII text
以上、ご参考になれば幸いです。