New module: keycloak_group (#35637)

* Initial implementation of groups module.

Not all parameters are supported, yet.

* Clarify read-only status of realmRoles, clientRoles and access attributes

* Fix testing failures

* Fix additional style issues.

* Minor updates and fixes after review feedback

* Simplify return values after feedback

This removes the 'proposed' and 'end_state' return values, replacing them instead with just 'group'. 'group' is the representation of the group after the module completes.

Also update the dates, and the Ansible version

* Corrections after module validation

* Further documentation updates after feedback

Minor whitespace adjustments also

* Add delegate_to: localhost stanzas to examples
This commit is contained in:
adamgoossens 2019-04-11 05:58:20 +10:00 committed by ansibot
parent 7bb19f1b4d
commit dd3de27cc8
2 changed files with 491 additions and 0 deletions

View file

@ -43,6 +43,8 @@ URL_REALM_ROLES = "{url}/admin/realms/{realm}/roles"
URL_CLIENTTEMPLATE = "{url}/admin/realms/{realm}/client-templates/{id}"
URL_CLIENTTEMPLATES = "{url}/admin/realms/{realm}/client-templates"
URL_GROUPS = "{url}/admin/realms/{realm}/groups"
URL_GROUP = "{url}/admin/realms/{realm}/groups/{groupid}"
def keycloak_argument_spec():
@ -339,3 +341,134 @@ class KeycloakAPI(object):
except Exception as e:
self.module.fail_json(msg='Could not delete client template %s in realm %s: %s'
% (id, realm, str(e)))
def get_groups(self, realm="master"):
""" Fetch the name and ID of all groups on the Keycloak server.
To fetch the full data of the group, make a subsequent call to
get_group_by_groupid, passing in the ID of the group you wish to return.
:param realm: Return the groups of this realm (default "master").
"""
groups_url = URL_GROUPS.format(url=self.baseurl, realm=realm)
try:
return json.load(open_url(groups_url, method="GET", headers=self.restheaders,
validate_certs=self.validate_certs))
except Exception as e:
self.module.fail_json(msg="Could not fetch list of groups in realm %s: %s"
% (realm, str(e)))
def get_group_by_groupid(self, gid, realm="master"):
""" Fetch a keycloak group from the provided realm using the group's unique ID.
If the group does not exist, None is returned.
gid is a UUID provided by the Keycloak API
:param gid: UUID of the group to be returned
:param realm: Realm in which the group resides; default 'master'.
"""
groups_url = URL_GROUP.format(url=self.baseurl, realm=realm, groupid=gid)
try:
return json.load(open_url(groups_url, method="GET", headers=self.restheaders,
validate_certs=self.validate_certs))
except HTTPError as e:
if e.code == 404:
return None
else:
self.module.fail_json(msg="Could not fetch group %s in realm %s: %s"
% (gid, realm, str(e)))
except Exception as e:
self.module.fail_json(msg="Could not fetch group %s in realm %s: %s"
% (gid, realm, str(e)))
def get_group_by_name(self, name, realm="master"):
""" Fetch a keycloak group within a realm based on its name.
The Keycloak API does not allow filtering of the Groups resource by name.
As a result, this method first retrieves the entire list of groups - name and ID -
then performs a second query to fetch the group.
If the group does not exist, None is returned.
:param name: Name of the group to fetch.
:param realm: Realm in which the group resides; default 'master'
"""
groups_url = URL_GROUPS.format(url=self.baseurl, realm=realm)
try:
all_groups = self.get_groups(realm=realm)
for group in all_groups:
if group['name'] == name:
return self.get_group_by_groupid(group['id'], realm=realm)
return None
except Exception as e:
self.module.fail_json(msg="Could not fetch group %s in realm %s: %s"
% (name, realm, str(e)))
def create_group(self, grouprep, realm="master"):
""" Create a Keycloak group.
:param grouprep: a GroupRepresentation of the group to be created. Must contain at minimum the field name.
:return: HTTPResponse object on success
"""
groups_url = URL_GROUPS.format(url=self.baseurl, realm=realm)
try:
return open_url(groups_url, method='POST', headers=self.restheaders,
data=json.dumps(grouprep), validate_certs=self.validate_certs)
except Exception as e:
self.module.fail_json(msg="Could not create group %s in realm %s: %s"
% (grouprep['name'], realm, str(e)))
def update_group(self, grouprep, realm="master"):
""" Update an existing group.
:param grouprep: A GroupRepresentation of the updated group.
:return HTTPResponse object on success
"""
group_url = URL_GROUP.format(url=self.baseurl, realm=realm, groupid=grouprep['id'])
try:
return open_url(group_url, method='PUT', headers=self.restheaders,
data=json.dumps(grouprep), validate_certs=self.validate_certs)
except Exception as e:
self.module.fail_json(msg='Could not update group %s in realm %s: %s'
% (grouprep['name'], realm, str(e)))
def delete_group(self, name=None, groupid=None, realm="master"):
""" Delete a group. One of name or groupid must be provided.
Providing the group ID is preferred as it avoids a second lookup to
convert a group name to an ID.
:param name: The name of the group. A lookup will be performed to retrieve the group ID.
:param groupid: The ID of the group (preferred to name).
:param realm: The realm in which this group resides, default "master".
"""
if groupid is None and name is None:
# prefer an exception since this is almost certainly a programming error in the module itself.
raise Exception("Unable to delete group - one of group ID or name must be provided.")
# only lookup the name if groupid isn't provided.
# in the case that both are provided, prefer the ID, since it's one
# less lookup.
if groupid is None and name is not None:
for group in self.get_groups(realm=realm):
if group['name'] == name:
groupid = group['id']
break
# if the group doesn't exist - no problem, nothing to delete.
if groupid is None:
return None
# should have a good groupid by here.
group_url = URL_GROUP.format(realm=realm, groupid=groupid, url=self.baseurl)
try:
return open_url(group_url, method='DELETE', headers=self.restheaders,
validate_certs=self.validate_certs)
except Exception as e:
self.module.fail_json(msg="Unable to delete group %s: %s" % (groupid, str(e)))