Currently there is no module to create a Keycloak realm with Ansible. There is a PR but it is stucked since half a year or so. So I though, there is a Keycloak REST API (https://www.keycloak.org/docs-api/9.0/rest-api/index.html#_realms_admin_resource) and I could call it with uri
to create a Token and then send a JSON RealmRepresentation via REST. So I tried this:
- name: "Create Token for service Keycloak"
uri:
url: "https://keycloak-server/auth/realms/master/protocol/openid-connect/token"
method: POST
body_format: form-urlencoded
body:
username: "admin"
password: "password"
grant_type: "password"
client_id: "admin-cli"
register: keycloak_token
- name: "Create Realm for service Keycloak"
uri:
url: "https://keycloak-server/auth/"
method: POST
src: "realm.json"
remote_src: "no"
headers:
Content-type: "application/json"
Accept: "application/json"
Authorization: "Bearer {{ keycloak_token.json.access_token }}"
register: keycloak_realm_create
The token is available within keycloak_token.json.access_token
and it is correct.
As realm.json
I tested a minimal JSON (because all attributes in RealmRepresentation are marked as optional):
{
"id": "myrealm",
"realm": "myrealm",
"displayName": "My Realm",
"enabled": true,
"sslRequired": "external",
"registrationAllowed": false,
"loginWithEmailAllowed": true,
"duplicateEmailsAllowed": false,
"resetPasswordAllowed": false,
"editUsernameAllowed": false,
"bruteForceProtected": true
}
or a complete JSON export from Keycloak via WebUI (export realm).
But in any case the following error happens:
fatal: [localhost]: FAILED! => {
"changed": false,
"connection": "close",
"content": "{\"error\":\"RESTEASY003065: Cannot consume content type\"}",
"content_length": "55",
"content_type": "application/json",
"elapsed": 0,
"json": {"error": "RESTEASY003065: Cannot consume content type"},
"msg": "Status code was 415 and not [200]: HTTP Error 415: Unsupported Media Type",
"redirected": false,
"status": 415,
"url": "https://keycloak-server/auth/"
}
The documentation says it must be a POST
to /
and it consumes application/json
. So, I'm not sure - is the URL correct? If I try https://keycloak-server/auth/realms/
, I'm getting a 404. If I remove the Content-type
- I'm getting a 406 with "Not acceptable". If I remove Accepts too, I'm getting a HTML page.
So - what is wrong?
https://keycloak-server/auth/admin/realms
? What happens if you try with CURL something like thiscurl -v -X POST \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d @realm.json \ $KCHOST/auth/admin/realms
? – JSapkota Mar 18 '20 at 1:17/admin/
between auth and realms, it works. I'll write an answer with a complete example. – TRW Mar 19 '20 at 7:18