Merge pull request #377 from snecklifter/feat/keycloak-organization-module

Add keycloak_organization and keycloak_organization_info modules
This commit is contained in:
Harsha Cherukuri
2026-08-13 13:55:33 -04:00
committed by GitHub
5 changed files with 802 additions and 0 deletions
+2
View File
@@ -23,6 +23,8 @@ action_groups:
- keycloak_component_info
- keycloak_group
- keycloak_identity_provider
- keycloak_organization
- keycloak_organization_info
- keycloak_realm
- keycloak_realm_info
- keycloak_realm_key
+153
View File
@@ -46,6 +46,8 @@
- keycloak_component_info
- keycloak_group
- keycloak_identity_provider
- keycloak_organization
- keycloak_organization_info
- keycloak_realm
- keycloak_realm_info
- keycloak_realm_key
@@ -264,6 +266,157 @@
- custom_realm_attributes_result.end_state.attributes["custom-realm-attribute-2"] is not defined
- custom_realm_attributes_result.end_state.attributes["custom-realm-attribute-3"] == "custom-attribute-3"
# --- Organization module tests ---
- name: keycloak_realm — enable organizations on ephemeral realm
middleware_automation.keycloak.keycloak_realm:
id: "{{ ephemeral_realm }}"
realm: "{{ ephemeral_realm }}"
organizations_enabled: true
state: present
- name: keycloak_organization — create organization
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org
description: Molecule test organization
enabled: true
domains:
- name: molecule.example.com
state: present
register: org_create_result
- name: Assert organization was created
ansible.builtin.assert:
that:
- org_create_result is changed
- org_create_result.end_state.name == "molecule-org"
- org_create_result.end_state.description == "Molecule test organization"
- org_create_result.end_state.enabled == true
- org_create_result.end_state.id is defined
- name: keycloak_organization — create organization (idempotency)
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org
description: Molecule test organization
enabled: true
domains:
- name: molecule.example.com
state: present
register: org_create_idempotent_result
- name: Assert organization creation is idempotent
ansible.builtin.assert:
that:
- org_create_idempotent_result is not changed
- name: keycloak_organization — update organization description
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org
description: Updated molecule test organization
state: present
register: org_update_result
- name: Assert organization was updated
ansible.builtin.assert:
that:
- org_update_result is changed
- org_update_result.end_state.description == "Updated molecule test organization"
- name: keycloak_organization — update organization (idempotency)
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org
description: Updated molecule test organization
state: present
register: org_update_idempotent_result
- name: Assert organization update is idempotent
ansible.builtin.assert:
that:
- org_update_idempotent_result is not changed
- name: keycloak_organization_info — query organization by name
middleware_automation.keycloak.keycloak_organization_info:
realm: "{{ ephemeral_realm }}"
name: molecule-org
register: org_info_result
- name: Assert organization info returns the created org
ansible.builtin.assert:
that:
- org_info_result is not changed
- org_info_result.organizations | length == 1
- org_info_result.organizations[0].name == "molecule-org"
- name: keycloak_organization_info — list all organizations
middleware_automation.keycloak.keycloak_organization_info:
realm: "{{ ephemeral_realm }}"
register: org_info_all_result
- name: Assert organization list is non-empty
ansible.builtin.assert:
that:
- org_info_all_result.organizations | length >= 1
- name: keycloak_organization — create organization with attributes
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org-attrs
description: Organization with attributes
attributes:
department: engineering
tags:
- test
- molecule
state: present
register: org_attrs_result
- name: Assert organization with attributes was created
ansible.builtin.assert:
that:
- org_attrs_result is changed
- org_attrs_result.end_state.attributes.department == ["engineering"]
- org_attrs_result.end_state.attributes.tags == ["test", "molecule"]
- name: keycloak_organization — delete organization with attributes
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org-attrs
state: absent
register: org_attrs_delete_result
- name: Assert organization with attributes was deleted
ansible.builtin.assert:
that:
- org_attrs_delete_result is changed
- name: keycloak_organization — delete organization
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org
state: absent
register: org_delete_result
- name: Assert organization was deleted
ansible.builtin.assert:
that:
- org_delete_result is changed
- name: keycloak_organization — delete organization (idempotency)
middleware_automation.keycloak.keycloak_organization:
realm: "{{ ephemeral_realm }}"
name: molecule-org
state: absent
register: org_delete_idempotent_result
- name: Assert organization deletion is idempotent
ansible.builtin.assert:
that:
- org_delete_idempotent_result is not changed
- name: keycloak_realm_localization — set locale override
middleware_automation.keycloak.keycloak_realm_localization:
parent_id: "{{ target_realm }}"
@@ -155,6 +155,9 @@ URL_AUTHZ_RESOURCES = "{url}/admin/realms/{realm}/clients/{client_id}/authz/reso
URL_AUTHZ_CUSTOM_POLICY = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/policy/{policy_type}"
URL_AUTHZ_CUSTOM_POLICIES = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/policy"
URL_ORGANIZATIONS = "{url}/admin/realms/{realm}/organizations"
URL_ORGANIZATION = "{url}/admin/realms/{realm}/organizations/{id}"
def keycloak_argument_spec() -> dict[str, t.Any]:
"""
@@ -3508,6 +3511,92 @@ class KeycloakAPI:
return self.get_client_role_scope_from_realm(clientid, realm)
def get_organizations(self, search_filter=None, realm: str = "master"):
"""Fetch representations for organizations in a realm.
:param search_filter: Optional query string to append (e.g. 'search=foo&exact=true').
:param realm: Realm to be queried; default 'master'.
:return: List of organization representations.
"""
orgs_url = URL_ORGANIZATIONS.format(url=self.baseurl, realm=realm)
if search_filter:
orgs_url = f"{orgs_url}?{search_filter}"
try:
return self._request_and_deserialize(orgs_url, method="GET")
except ValueError as e:
self.module.fail_json(
msg=f"API returned incorrect JSON when trying to obtain list of organizations for realm {realm}: {e}"
)
except Exception as e:
self.fail_request(e, msg=f"Could not obtain list of organizations for realm {realm}: {e}")
def get_organization_by_id(self, org_id, realm: str = "master"):
"""Fetch an organization by its UUID.
If the organization does not exist, None is returned.
:param org_id: UUID of the organization to fetch.
:param realm: Realm in which the organization resides; default 'master'.
"""
org_url = URL_ORGANIZATION.format(url=self.baseurl, realm=realm, id=org_id)
try:
return self._request_and_deserialize(org_url, method="GET")
except HTTPError as e:
if e.code == HTTPStatus.NOT_FOUND:
return None
else:
self.fail_request(e, msg=f"Could not fetch organization {org_id} in realm {realm}: {e}")
except Exception as e:
self.fail_request(e, msg=f"Could not fetch organization {org_id} in realm {realm}: {e}")
def get_organization_by_name(self, name, realm: str = "master"):
"""Fetch an organization by name using search API with exact matching.
Returns the full representation (fetched by ID) or None if not found.
:param name: Name of the organization to fetch.
:param realm: Realm in which the organization resides; default 'master'.
"""
search_url = URL_ORGANIZATIONS.format(url=self.baseurl, realm=realm)
search_url = f"{search_url}?search={quote(name, safe='')}&exact=true"
try:
orgs = self._request_and_deserialize(search_url, method="GET")
if not orgs:
return None
return self.get_organization_by_id(orgs[0]["id"], realm=realm)
except Exception as e:
self.fail_request(e, msg=f"Could not fetch organization {name} in realm {realm}: {e}")
def create_organization(self, orgrep, realm: str = "master"):
"""Create an organization.
:param orgrep: Organization representation of the organization to be created.
:param realm: Realm in which this organization resides, default "master".
:return: HTTPResponse object on success.
"""
orgs_url = URL_ORGANIZATIONS.format(url=self.baseurl, realm=realm)
try:
return self._request(orgs_url, method="POST", data=json.dumps(orgrep))
except Exception as e:
self.fail_request(e, msg=f"Could not create organization {orgrep.get('name')} in realm {realm}: {e}")
def update_organization(self, orgrep, realm: str = "master"):
"""Update an existing organization.
:param orgrep: Organization representation of the organization to be updated.
:param realm: Realm in which this organization resides, default "master".
:return: HTTPResponse object on success.
"""
org_url = URL_ORGANIZATION.format(url=self.baseurl, realm=realm, id=orgrep["id"])
try:
return self._request(org_url, method="PUT", data=json.dumps(orgrep))
except Exception as e:
self.fail_request(e, msg=f"Could not update organization {orgrep.get('name')} in realm {realm}: {e}")
def delete_organization(self, org_id, realm: str = "master"):
"""Delete an organization by UUID.
:param org_id: UUID of the organization to delete.
:param realm: Realm in which this organization resides, default "master".
"""
org_url = URL_ORGANIZATION.format(url=self.baseurl, realm=realm, id=org_id)
try:
return self._request(org_url, method="DELETE")
except Exception as e:
self.fail_request(e, msg=f"Could not delete organization {org_id} in realm {realm}: {e}")
def fail_request(self, e: Exception, msg: str, **kwargs: t.Any) -> t.NoReturn:
"""Triggers a module failure. This should be called
when an exception occurs during/after a request.
+416
View File
@@ -0,0 +1,416 @@
# Copyright (c) 2025, Chris Brown
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
from __future__ import annotations
__metaclass__ = type
DOCUMENTATION = r"""
module: keycloak_organization
short_description: Allows administration of Keycloak organizations using Keycloak API
version_added: "3.1.0"
description:
- This module allows you to add, remove or modify Keycloak organizations using the Keycloak REST API.
It requires access to the REST API using OpenID Connect; the user connecting and the client being
used must have the requisite access rights. In a default Keycloak installation, admin-cli and an
admin user would work, as would a separate client definition with the scope tailored to your needs
and a user having the expected roles.
- The names of module options are snake_cased versions of the camelCase ones found in the Keycloak
API and its documentation at U(https://www.keycloak.org/docs-api/latest/rest-api/index.html).
- Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and
are returned that way by this module. You may pass single values for attributes when calling the
module, and this is translated into a list suitable for the API.
- Organizations are available in Keycloak 26 and later. The realm must have organizations enabled
(C(organizations_enabled=true) in the M(middleware_automation.keycloak.keycloak_realm) module)
before this module can be used.
- When updating an organization, where possible provide the organization ID to the module. This
removes a lookup to the API to translate the name into the organization ID.
attributes:
check_mode:
support: full
diff_mode:
support: full
action_group:
version_added: "3.1.0"
options:
state:
description:
- State of the organization.
- On V(present), the organization is created if it does not yet exist, or updated with the
parameters you provide.
- On V(absent), the organization is removed if it exists.
default: 'present'
type: str
choices:
- present
- absent
realm:
type: str
description:
- The Keycloak realm under which this organization resides.
default: 'master'
id:
type: str
description:
- The unique identifier for this organization.
- This parameter is not required for updating or deleting an organization but providing it
reduces the number of API calls required.
name:
type: str
description:
- Name of the organization.
- This parameter is required when creating a new organization.
alias:
type: str
description:
- URL-friendly alias for the organization.
- If not provided during creation, defaults to the organization name if URL-safe.
- The alias is immutable once set and cannot be changed on update.
enabled:
type: bool
description:
- Whether the organization is enabled.
- Disabled organizations block member authentication.
description:
type: str
description:
- Description of the organization.
domains:
type: list
elements: dict
description:
- List of internet domains associated with the organization.
- A domain name can only belong to one organization within a realm.
suboptions:
name:
type: str
required: true
description:
- The domain name (e.g. V(example.com)).
verified:
type: bool
default: false
description:
- Whether the domain has been verified.
attributes:
type: dict
description:
- A dict of key/value pairs to set as custom attributes for the organization.
- Values may be single values (for example a string) or a list of strings.
extends_documentation_fragment:
- middleware_automation.keycloak.keycloak
- middleware_automation.keycloak.actiongroup_keycloak
- middleware_automation.keycloak.attributes
author:
- Chris Brown (@chribro)
"""
EXAMPLES = r"""
- name: Create a Keycloak organization
middleware_automation.keycloak.keycloak_organization:
name: my-org
description: My Organization
enabled: true
realm: MyRealm
state: present
auth_client_id: admin-cli
auth_keycloak_url: https://auth.example.com
auth_realm: master
auth_username: USERNAME
auth_password: PASSWORD
delegate_to: localhost
- name: Create a Keycloak organization with domains
middleware_automation.keycloak.keycloak_organization:
name: acme-corp
description: Acme Corporation
enabled: true
domains:
- name: acme.com
- name: acme.org
verified: true
realm: MyRealm
state: present
auth_client_id: admin-cli
auth_keycloak_url: https://auth.example.com
auth_realm: master
auth_username: USERNAME
auth_password: PASSWORD
delegate_to: localhost
- name: Update a Keycloak organization
middleware_automation.keycloak.keycloak_organization:
name: my-org
description: Updated description
realm: MyRealm
state: present
auth_client_id: admin-cli
auth_keycloak_url: https://auth.example.com
auth_realm: master
auth_username: USERNAME
auth_password: PASSWORD
delegate_to: localhost
- name: Delete a Keycloak organization
middleware_automation.keycloak.keycloak_organization:
name: my-org
state: absent
realm: MyRealm
auth_client_id: admin-cli
auth_keycloak_url: https://auth.example.com
auth_realm: master
auth_username: USERNAME
auth_password: PASSWORD
delegate_to: localhost
"""
RETURN = r"""
msg:
description: Message as to what action was taken.
returned: always
type: str
end_state:
description: Representation of the organization after module execution.
returned: on success
type: complex
contains:
id:
description: GUID that identifies the organization.
type: str
returned: always
sample: 23f38145-3195-462c-97e7-97041ccea73e
name:
description: Name of the organization.
type: str
returned: always
sample: my-org
alias:
description: URL-friendly alias of the organization.
type: str
returned: always
sample: my-org
enabled:
description: Whether the organization is enabled.
type: bool
returned: always
sample: true
description:
description: Description of the organization.
type: str
returned: always
sample: My Organization
domains:
description: Domains associated with the organization.
type: list
returned: always
sample: [{"name": "example.com", "verified": false}]
attributes:
description: Attributes applied to this organization.
type: dict
returned: always
sample:
attr1: ["val1", "val2"]
"""
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.middleware_automation.keycloak.plugins.module_utils.identity.keycloak.keycloak import (
KeycloakAPI,
KeycloakError,
camel,
get_token,
keycloak_argument_spec,
)
def normalise_org(org):
"""Normalise an organization representation for comparison.
Sorts domains by name to ensure order-independent comparison.
"""
if org and "domains" in org and org["domains"]:
org["domains"] = sorted(org["domains"], key=lambda d: d.get("name", ""))
return org
def main():
argument_spec = keycloak_argument_spec()
meta_args = dict(
state=dict(default="present", choices=["present", "absent"]),
realm=dict(default="master"),
id=dict(type="str"),
name=dict(type="str"),
alias=dict(type="str"),
enabled=dict(type="bool"),
description=dict(type="str"),
domains=dict(
type="list",
elements="dict",
options=dict(
name=dict(type="str", required=True),
verified=dict(type="bool", default=False),
),
),
attributes=dict(type="dict"),
)
argument_spec.update(meta_args)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_one_of=(
[
["id", "name"],
["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"],
]
),
required_together=([["auth_username", "auth_password"]]),
required_by={"refresh_token": "auth_realm"},
)
result = dict(changed=False, msg="", diff={}, end_state={})
try:
connection_header = get_token(module.params)
except KeycloakError as e:
module.fail_json(msg=str(e))
kc = KeycloakAPI(module, connection_header)
realm = module.params.get("realm")
state = module.params.get("state")
oid = module.params.get("id")
name = module.params.get("name")
attributes = module.params.get("attributes")
if attributes is not None:
for key, val in module.params["attributes"].items():
module.params["attributes"][key] = [val] if not isinstance(val, list) else val
# Parameters that map to the organization representation (excluding module-level params)
org_params = [
x
for x in module.params
if x not in list(keycloak_argument_spec().keys()) + ["state", "realm"]
and module.params.get(x) is not None
]
if oid is None:
before_org = kc.get_organization_by_name(name, realm=realm)
else:
before_org = kc.get_organization_by_id(oid, realm=realm)
if before_org is None:
before_org = {}
normalise_org(before_org)
changeset = {}
for param in org_params:
new_param_value = module.params.get(param)
if param == "alias" and before_org:
if new_param_value != before_org.get("alias"):
module.warn(
f"Organization alias is immutable and cannot be changed from '{before_org.get('alias')}' "
f"to '{new_param_value}'. The alias parameter will be ignored for this update."
)
continue
old_value = before_org.get(camel(param))
if new_param_value != old_value:
changeset[camel(param)] = new_param_value
desired_org = before_org.copy()
desired_org.update(changeset)
normalise_org(desired_org)
if not before_org:
if state == "absent":
if module._diff:
result["diff"] = dict(before="", after="")
result["changed"] = False
result["end_state"] = {}
result["msg"] = "Organization does not exist; doing nothing."
module.exit_json(**result)
result["changed"] = True
if name is None:
module.fail_json(msg="name must be specified when creating a new organization")
if module._diff:
result["diff"] = dict(before="", after=desired_org)
if module.check_mode:
module.exit_json(**result)
kc.create_organization(desired_org, realm=realm)
after_org = kc.get_organization_by_name(name, realm=realm)
result["end_state"] = normalise_org(after_org) if after_org else {}
result["msg"] = f"Organization {name} has been created with ID {after_org['id']}"
module.exit_json(**result)
else:
if state == "present":
if desired_org == before_org:
result["changed"] = False
result["end_state"] = desired_org
result["msg"] = f"No changes required to organization {before_org['name']}."
module.exit_json(**result)
result["changed"] = True
if module._diff:
result["diff"] = dict(before=before_org, after=desired_org)
if module.check_mode:
module.exit_json(**result)
kc.update_organization(desired_org, realm=realm)
after_org = kc.get_organization_by_id(desired_org["id"], realm=realm)
result["end_state"] = normalise_org(after_org) if after_org else {}
result["msg"] = f"Organization {desired_org['id']} has been updated"
module.exit_json(**result)
else:
result["changed"] = True
if module._diff:
result["diff"] = dict(before=before_org, after="")
if module.check_mode:
module.exit_json(**result)
oid = before_org["id"]
kc.delete_organization(org_id=oid, realm=realm)
result["end_state"] = {}
result["msg"] = f"Organization {before_org['name']} has been deleted"
module.exit_json(**result)
if __name__ == "__main__":
main()
@@ -0,0 +1,142 @@
# Copyright (c) 2025, Chris Brown
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
from __future__ import annotations
__metaclass__ = type
DOCUMENTATION = r"""
module: keycloak_organization_info
short_description: Retrieve organization info in Keycloak
version_added: "3.1.0"
description:
- This module retrieves information on organizations from Keycloak.
- Organizations are available in Keycloak 26 and later. The realm must have organizations enabled
before this module can be used.
attributes:
action_group:
version_added: "3.1.0"
options:
realm:
description:
- The name of the realm.
required: true
type: str
name:
description:
- Name of the organization to search for.
- If not provided, all organizations in the realm are returned.
type: str
exact:
description:
- Whether the search should be an exact match.
- Only relevant when O(name) is provided.
type: bool
default: true
extends_documentation_fragment:
- middleware_automation.keycloak.keycloak
- middleware_automation.keycloak.actiongroup_keycloak
- middleware_automation.keycloak.attributes
- middleware_automation.keycloak.attributes.info_module
author:
- Chris Brown (@chribro)
"""
EXAMPLES = r"""
- name: Retrieve a specific organization by name
middleware_automation.keycloak.keycloak_organization_info:
auth_keycloak_url: https://auth.example.com
auth_username: admin
auth_password: password
auth_realm: master
realm: MyRealm
name: my-org
- name: List all organizations in a realm
middleware_automation.keycloak.keycloak_organization_info:
auth_keycloak_url: https://auth.example.com
auth_username: admin
auth_password: password
auth_realm: master
realm: MyRealm
- name: Search organizations by partial name
middleware_automation.keycloak.keycloak_organization_info:
auth_keycloak_url: https://auth.example.com
auth_username: admin
auth_password: password
auth_realm: master
realm: MyRealm
name: acme
exact: false
"""
RETURN = r"""
organizations:
description: JSON representation of organizations.
returned: always
type: list
elements: dict
"""
from urllib.parse import quote
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.middleware_automation.keycloak.plugins.module_utils.identity.keycloak.keycloak import (
KeycloakAPI,
KeycloakError,
get_token,
keycloak_argument_spec,
)
def main():
argument_spec = keycloak_argument_spec()
meta_args = dict(
name=dict(type="str"),
realm=dict(type="str", required=True),
exact=dict(type="bool", default=True),
)
argument_spec.update(meta_args)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
result = dict(changed=False, organizations=[])
try:
connection_header = get_token(module.params)
except KeycloakError as e:
module.fail_json(msg=str(e))
kc = KeycloakAPI(module, connection_header)
realm = module.params.get("realm")
name = module.params.get("name")
exact = module.params.get("exact")
filters = []
if name:
filters.append(f"search={quote(name, safe='')}")
if exact:
filters.append("exact=true")
filter_str = "&".join(filters) if filters else None
result["organizations"] = kc.get_organizations(search_filter=filter_str, realm=realm)
module.exit_json(**result)
if __name__ == "__main__":
main()