From ae286f5226bf3aff82bb3600ff5c4118e97c53c3 Mon Sep 17 00:00:00 2001
From: Thomas Woerner <twoerner@redhat.com>
Date: Wed, 19 Jan 2022 14:20:13 +0100
Subject: [PATCH] ipahostgroup: Ensure host members are lowercase and FQDN

The host members of ipahostgroup need to be lowercase and FQDN to be
able to do a proper comparison with exising hosts in the hostgroup.

Fixes: #666 (ipahostgroup not idempotent and with error)
---
 plugins/modules/ipahostgroup.py    | 11 ++++++++++-
 tests/hostgroup/test_hostgroup.yml | 13 +++++++++++++
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/plugins/modules/ipahostgroup.py b/plugins/modules/ipahostgroup.py
index 285fe51d..57dad3dc 100644
--- a/plugins/modules/ipahostgroup.py
+++ b/plugins/modules/ipahostgroup.py
@@ -139,7 +139,7 @@ RETURN = """
 
 from ansible.module_utils.ansible_freeipa_module import \
     IPAAnsibleModule, compare_args_ipa, gen_add_del_lists, gen_add_list, \
-    gen_intersection_list
+    gen_intersection_list, ensure_fqdn
 
 
 def find_hostgroup(module, name):
@@ -281,6 +281,15 @@ def main():
             ansible_module.fail_json(
                 msg="Renaming hostgroups is not supported by your IPA version")
 
+        # If hosts are given, ensure that the hosts are FQDN and also
+        # lowercase to be able to do a proper comparison to exising hosts
+        # in the hostgroup.
+        # Fixes #666 (ipahostgroup not idempotent and with error)
+        if host is not None:
+            default_domain = ansible_module.ipa_get_domain()
+            host = [ensure_fqdn(_host, default_domain).lower()
+                    for _host in host]
+
         commands = []
 
         for name in names:
diff --git a/tests/hostgroup/test_hostgroup.yml b/tests/hostgroup/test_hostgroup.yml
index 076f76d1..d8a7305d 100644
--- a/tests/hostgroup/test_hostgroup.yml
+++ b/tests/hostgroup/test_hostgroup.yml
@@ -133,6 +133,19 @@
     register: result
     failed_when: result.changed or result.failed
 
+  - name: Ensure hosts db1 and db2 (no FQDN) are member of host-group databases again
+    ipahostgroup:
+      ipaadmin_password: SomeADMINpassword
+      ipaapi_context: "{{ ipa_context | default(omit) }}"
+      name: databases
+      state: present
+      host:
+      - db1
+      - db2
+      action: member
+    register: result
+    failed_when: result.changed or result.failed
+
   - name: Ensure host-group mysql-server is member of host-group databases
     ipahostgroup:
       ipaadmin_password: SomeADMINpassword
-- 
GitLab