From a44eb7ea5421050b23b60cf00c7d7f5726ba1590 Mon Sep 17 00:00:00 2001
From: Bombar Maxime <bombar@crans.org>
Date: Sun, 26 Apr 2020 14:49:29 +0200
Subject: [PATCH] [re2o_lookup] Adapt get_role from bcfg2/ip.py

---
 lookup_plugins/re2oapi.py | 28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)

diff --git a/lookup_plugins/re2oapi.py b/lookup_plugins/re2oapi.py
index 06dffb53..a8b64db6 100644
--- a/lookup_plugins/re2oapi.py
+++ b/lookup_plugins/re2oapi.py
@@ -12,6 +12,7 @@ import datetime
 import requests
 import stat
 import json
+import collections
 
 from ansible.module_utils._text import to_native
 from ansible.plugins.lookup import LookupBase
@@ -309,6 +310,10 @@ class LookupModule(LookupBase):
        - dnszones: Queries the re2o API and returns the list of all dns zones
                    nicely formatted to be rendered in a template.
 
+       - get_role, role_name: Works in pair. Fails if role_name not provided.
+                              Queries the re2o API and returns the list of
+                              all machines whose role_type is role_name.
+
     If a term is not in the previous list, make a raw query to the API
     with endpoint term.
 
@@ -361,10 +366,25 @@ class LookupModule(LookupBase):
                             api_password, use_tls=True)
 
         res = []
-        for term in terms:
+        dterms = collections.deque(terms)
+        machines_roles = None # TODO : Cache this.
+        display.vvv("Lookup terms are {}".format(terms))
+        while dterms:
+            term = dterms.popleft()
             display.v("\nLookup for {} \n".format(term))
             if term == 'dnszones':
                 res.append(self._getzones(api_client))
+            elif term == 'get_role':
+                try:
+                    role_name = dterms.popleft()
+                    roles, machines_roles = self._get_role(api_client,
+                                                           role_name,
+                                                           machines_roles,
+                                                           )
+                    res.append(roles)
+                except IndexError:
+                    display.v("Error in re2oapi : No role_name provided")
+                    raise AnsibleError("role_name not found in arguments.")
             else:
                 try:
                     res.append(self._rawquery(api_client, term))
@@ -384,3 +404,9 @@ class LookupModule(LookupBase):
     def _rawquery(self, api_client, endpoint):
         display.v("Make a raw query to endpoint {}".format(endpoint))
         return api_client.list(endpoint)
+
+    def _get_role(self, api_client, role_name, machines_roles):
+        if machines_roles is None:
+            machines_roles = api_client.list("machines/role")
+        return list(filter(lambda machine: machine["role_type"] == role_name,
+                           machines_roles)), machines_roles