From e27f9fc99ae0acff66c4e5cc3dd7f323e9cbd19a Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Wed, 28 Nov 2018 17:54:44 +0100
Subject: [PATCH] Return host fqdn in Ansible groups

JIRA INFRA-640
---
 app/models.py               | 2 +-
 app/network/forms.py        | 4 +++-
 app/templates/_helpers.html | 6 +++---
 app/utils.py                | 4 ++--
 4 files changed, 9 insertions(+), 7 deletions(-)

diff --git a/app/models.py b/app/models.py
index 89d11fe..62de3ca 100644
--- a/app/models.py
+++ b/app/models.py
@@ -1031,7 +1031,7 @@ class AnsibleGroup(CreatedMixin, db.Model):
                 "name": self.name,
                 "vars": self.vars,
                 "type": self.type.name,
-                "hosts": [str(host) for host in self.hosts],
+                "hosts": [host.fqdn for host in self.hosts],
                 "children": [str(child) for child in self.children],
             }
         )
diff --git a/app/network/forms.py b/app/network/forms.py
index a8ea9de..b91962a 100644
--- a/app/network/forms.py
+++ b/app/network/forms.py
@@ -265,4 +265,6 @@ class AnsibleGroupForm(CSEntryForm):
         self.children.choices = utils.get_model_choices(
             models.AnsibleGroup, attr="name"
         )
-        self.hosts.choices = utils.get_model_choices(models.Host, attr="name")
+        self.hosts.choices = utils.get_model_choices(
+            models.Host, attr="fqdn", order_by="name"
+        )
diff --git a/app/templates/_helpers.html b/app/templates/_helpers.html
index d201040..4c1f01a 100644
--- a/app/templates/_helpers.html
+++ b/app/templates/_helpers.html
@@ -39,13 +39,13 @@
 {% if active %}active{% endif %}
 {%- endmacro %}
 
-{% macro link_to_host(name) -%}
-  <a href="{{ url_for('network.view_host', name=name) }}">{{ name }}</a>
+{% macro link_to_host(host) -%}
+  <a href="{{ url_for('network.view_host', name=host.name) }}">{{ host.fqdn|default(host.name) }}</a>
 {%- endmacro %}
 
 {% macro link_to_hosts(hosts) -%}
   {% for host in hosts %}
-    {{ link_to_host(host.name) }}
+    {{ link_to_host(host) }}
   {% endfor %}
 {%- endmacro %}
 
diff --git a/app/utils.py b/app/utils.py
index 6dc8d71..bda6689 100644
--- a/app/utils.py
+++ b/app/utils.py
@@ -130,14 +130,14 @@ def get_choices(iterable, allow_blank=False, allow_null=False):
     return choices
 
 
-def get_model_choices(model, allow_none=False, attr="name", query=None):
+def get_model_choices(model, allow_none=False, attr="name", query=None, order_by=None):
     """Return a list of (value, label)"""
     choices = []
     if allow_none:
         choices = [(None, "")]
     if query is None:
         query = model.query
-    query = query.order_by(getattr(model, attr))
+    query = query.order_by(getattr(model, order_by or attr))
     choices.extend(
         [(str(instance.id), getattr(instance, attr)) for instance in query.all()]
     )
-- 
GitLab