From 1e7802dc62b28d870cd31d12eeefb7e5ebfb998e Mon Sep 17 00:00:00 2001
From: David Kirwan <dkirwan@redhat.com>
Date: Feb 16 2023 06:57:07 +0000
Subject: basic implementation of fas2discourse_retrieve_discourse_groups library


Signed-off-by: David Kirwan <dkirwan@redhat.com>

---

diff --git a/roles/fas2discourseconfig/defaults/main.yml b/roles/fas2discourseconfig/defaults/main.yml
index f6b8124..b87be2e 100644
--- a/roles/fas2discourseconfig/defaults/main.yml
+++ b/roles/fas2discourseconfig/defaults/main.yml
@@ -4,3 +4,5 @@ fas2discourse_keytab_path: "/etc/fas2discourse"
 fas2discourse_principal: "fas2discourse/fas2discourse.hostname@FEDORAPROJECT.ORG"
 f2d_namespace: "fas2discourse-operator"
 f2d_secret: "fas2discourse-operator-k8s-secret"
+discourse_host: "OVERRIDEME"
+discourse_api: "OVERRIDEME"
diff --git a/roles/fas2discourseconfig/library/fas2discourse_retrieve_discourse_data.py b/roles/fas2discourseconfig/library/fas2discourse_retrieve_discourse_data.py
deleted file mode 100644
index 63a686f..0000000
--- a/roles/fas2discourseconfig/library/fas2discourse_retrieve_discourse_data.py
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/python
-
-# Copyright: (c) 2018, Terry Jones <terry.jones@example.org>
-# GNU General Public License v3.0+ (see COPYING or
-# https://www.gnu.org/licenses/gpl-3.0.txt)
-
-import json
-import requests
-
-from ansible.module_utils.basic import AnsibleModule
-from requests_kerberos import HTTPKerberosAuth
-
-__metaclass__ = type
-
-DOCUMENTATION = r"""
----
-module: fas2discourse_retrieve_discourse_data
-
-short_description: Retrieve discourse groups.
-
-version_added: "0.0.1"
-
-description: This module retrieves discourse groups.
-
-options:
-     discourse_groups:
-        description: These are the groups retrieved from the discouse.
-        required: true
-        type: str
-
-author:
-    - David Kirwan (dkirwan@redhat.com)
-    - Lenka Segura (lsegura@redhat.com)
-    - Patrik Polakovic (ppolakov@redhat.com)
-"""
-
-EXAMPLES = r"""
-- name: Retrieve discourse groups.
-  fas2discourse_retrieve_discourse_data:
-  register: fas2discourse_discourse_response
-"""
-
-RETURN = r"""
-# These are examples of possible return values, and in general should use other names for return
-# values.
-discourse_groups:
-    description: All the discourse groups.
-    type: str
-    returned: always
-    sample:
-{
-        "groups":[{"group": "design"},
-                  {"group": "editors"}]
-}
-
-msg:
-    description: The output message that the module generates.
-    type: str
-    returned: always
-    sample: 'Successfully retrieved groups from Dicourse.'
-"""
-
-
-# Helper function to create the http requests
-def get_http_client():
-    session = requests.Session()
-    return session
-
-
-# Helper function to retrieve fasjson groups
-def get_groups(http_client):
-    response = http_client.get("%sgroups.json" % ("https://discussion.fedoraproject.org/"))
-    if response.ok:
-        return response.json()
-
-
-def run_module():
-    # define available arguments/parameters a user can pass to the module
-    module_args = dict(
-        discourse_groups=dict(type="str", required=True),
-    )
-
-    # seed the result dict in the object
-    # we primarily care about changed and state
-    # changed is if this module effectively modified the target
-    # state will include any data that you want your module to pass back
-    # for consumption, for example, in a subsequent task
-    result = dict(changed=False, original_message="", message="")
-
-    # the AnsibleModule object will be our abstraction working with Ansible
-    # this includes instantiation, a couple of common attr would be the
-    # args/params passed to the execution, as well as if the module
-    # supports check mode
-    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
-
-    # if the user is working with this module in only check mode we do not
-    # want to make any changes to the environment, just return the current
-    # state with no modifications
-    if module.check_mode:
-        module.exit_json(**result)
-
-    # manipulate or modify the state as needed (this is going to be the
-    # part where your module will do what it needs to do)
-    discourse_api = module.params["discourse_api"]
-
-    try:
-        http_client = get_http_client()
-        groups_response = get_groups(http_client)
-
-        discourse_groups = []
-        for v in groups_response["groups"]:
-            dicourse_groups.append(v["name"])
-
-
-        result["discourse_groups"] = json.dumps(discourse_groups)
-        result["changed"] = True
-        result["msg"] = "Successfully retrieved groups from Discourse."
-    except Exception:
-        raise
-
-    # in the event of a successful module execution, you will want to
-    # simple AnsibleModule.exit_json(), passing the key/value results
-    module.exit_json(**result)
-
-
-def main():
-    run_module()
-
-
-if __name__ == "__main__":
-    main()
diff --git a/roles/fas2discourseconfig/library/fas2discourse_retrieve_discourse_groups.py b/roles/fas2discourseconfig/library/fas2discourse_retrieve_discourse_groups.py
new file mode 100644
index 0000000..d83b843
--- /dev/null
+++ b/roles/fas2discourseconfig/library/fas2discourse_retrieve_discourse_groups.py
@@ -0,0 +1,124 @@
+#!/usr/bin/python
+
+# Copyright: (c) 2018, Terry Jones <terry.jones@example.org>
+# GNU General Public License v3.0+ (see COPYING or
+# https://www.gnu.org/licenses/gpl-3.0.txt)
+
+import json
+import requests
+
+from ansible.module_utils.basic import AnsibleModule
+from requests_kerberos import HTTPKerberosAuth
+
+__metaclass__ = type
+
+DOCUMENTATION = r"""
+---
+module: fas2discourse_retrieve_discourse_groups
+
+short_description: Retrieve discourse groups.
+
+version_added: "0.0.1"
+
+description: This module retrieves discourse groups.
+
+options:
+     discourse_groups:
+        description: These are the groups retrieved from the discouse.
+        required: true
+        type: str
+
+author:
+    - David Kirwan (dkirwan@redhat.com)
+    - Lenka Segura (lsegura@redhat.com)
+    - Patrik Polakovic (ppolakov@redhat.com)
+"""
+
+EXAMPLES = r"""
+- name: Retrieve discourse groups.
+  fas2discourse_retrieve_discourse_groups:
+    discourse_api: "{{ discourse_api }}"
+    discourse_host: "{{ discourse_host }}"
+  register: fas2discourse_discourse_response
+"""
+
+RETURN = r"""
+# These are examples of possible return values, and in general should use other names for return
+# values.
+
+discourse_groups:
+    description: The Discourse groups.
+    type: dict
+    returned: always
+    sample: '{"groups":[{"id":51,"automatic":false,"name":"community-blog","user_count":2,"mentionable_level":3,"messageable_level":0,"visibility_level":0,"primary_group":false,"title":"","grant_trust_level":1,"flair_url":"https://redhat.discourse-cdn.com/fedoraproject/original/2X/2/28d0975bef06287ee5f04d0a9e576de172103298.png","flair_bg_color":"","flair_color":"","bio_cooked":null,"bio_excerpt":null,"public_admission":false,"public_exit":false,"allow_membership_requests":false,"full_name":"Community Blog Editors","default_notification_level":3,"membership_request_template":null,"members_visibility_level":0,"can_see_members":true,"publish_read_state":false}]}'
+
+msg:
+    description: The output message that the module generates.
+    type: str
+    returned: always
+    sample: 'Successfully retrieved groups from Dicourse.'
+"""
+
+
+# Helper function to retrieve fasjson groups
+def get_groups(discourse_host, discourse_api):
+    url = "%s/groups.json" % (discourse_host)
+    headers = {"Api-Key": "%s" % (discourse_api), "Api-Username" : "system"}
+    response = requests.get(url, headers=headers)
+    return response
+
+
+def run_module():
+    # define available arguments/parameters a user can pass to the module
+    module_args = dict(
+        discourse_api=dict(type="str", required=True),
+        discourse_host=dict(type="str", required=True),
+    )
+
+    # seed the result dict in the object
+    # we primarily care about changed and state
+    # changed is if this module effectively modified the target
+    # state will include any data that you want your module to pass back
+    # for consumption, for example, in a subsequent task
+    result = dict(changed=False, original_message="", message="")
+
+    # the AnsibleModule object will be our abstraction working with Ansible
+    # this includes instantiation, a couple of common attr would be the
+    # args/params passed to the execution, as well as if the module
+    # supports check mode
+    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
+
+    # if the user is working with this module in only check mode we do not
+    # want to make any changes to the environment, just return the current
+    # state with no modifications
+    if module.check_mode:
+        module.exit_json(**result)
+
+    # manipulate or modify the state as needed (this is going to be the
+    # part where your module will do what it needs to do)
+    discourse_api = module.params["discourse_api"]
+    discourse_host = module.params["discourse_host"]
+
+    try:
+        discourse_groups = []
+        resp = get_groups(discourse_host, discourse_api)
+        if resp.ok:
+            discourse_groups = json.dumps(resp.json())
+
+        result["discourse_groups"] = discourse_groups
+        result["changed"] = True
+        result["msg"] = "Successfully retrieved groups from Discourse."
+    except Exception:
+        raise
+
+    # in the event of a successful module execution, you will want to
+    # simple AnsibleModule.exit_json(), passing the key/value results
+    module.exit_json(**result)
+
+
+def main():
+    run_module()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/roles/fas2discourseconfig/tasks/main.yml b/roles/fas2discourseconfig/tasks/main.yml
index 0ae01f9..261fe8e 100644
--- a/roles/fas2discourseconfig/tasks/main.yml
+++ b/roles/fas2discourseconfig/tasks/main.yml
@@ -4,4 +4,4 @@
 - include_tasks: retrieve_discourse_groups.yml
 - include_tasks: kerberos_auth.yml
 - include_tasks: retrieve_ipa_groups.yml
-- include_tasks: sync_group_membership.yml 
+- include_tasks: sync_group_membership.yml
diff --git a/roles/fas2discourseconfig/tasks/retrieve_discourse_groups.yml b/roles/fas2discourseconfig/tasks/retrieve_discourse_groups.yml
index 85bf322..694dc4c 100644
--- a/roles/fas2discourseconfig/tasks/retrieve_discourse_groups.yml
+++ b/roles/fas2discourseconfig/tasks/retrieve_discourse_groups.yml
@@ -2,17 +2,14 @@
 # tasks file for fas2discourse
 
 - name: Retrieve discourse groups
-  fas2discourse_retrieve_discourse_data:
-  register: discourse_response
+  fas2discourse_retrieve_discourse_groups:
+    discourse_host: "{{ discourse_host }}"
+    discourse_api: "{{ discourse_api }}"
+  register: fas2discourse_retrieve_discourse_groups_response
 
-- name: Set fact
-  set_fact:
-    fas2discourse_discourse_response: "{{ discourse_response }}"
 
 - name: Prints the groups
   ansible.builtin.debug:
     msg:
-    - "Groups found: {{ fas2discourse_discourse_response['matched_groups'] }}"
+    - "{{ fas2discourse_retrieve_discourse_groups_response['discourse_groups'] }}"
 
-- name: Write groups to json file
-  copy: content="{{ fas2discourse_discourse_response['matched_groups'] }}" dest=/tmp/groups.json

