From 5ea2c13453b1751fdf9b2ca2e155f7bd919c7924 Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Wed, 8 May 2019 18:29:07 +0200
Subject: [PATCH] Save ansible var when setting boot profile

The csentry_autoinstall_boot_profile variable shall be saved to setup the
DHCP option.
The DHCP shall be updated when a change occurs.

JIRA INFRA-1016 #action In Progress
---
 app/network/views.py |  8 ++++++++
 app/utils.py         | 21 +++++++++++++++++++++
 2 files changed, 29 insertions(+)

diff --git a/app/network/views.py b/app/network/views.py
index 3a8aa6c..8909f56 100644
--- a/app/network/views.py
+++ b/app/network/views.py
@@ -193,6 +193,14 @@ def view_host(name):
                 task = utils.trigger_set_network_boot_profile(
                     host, boot_profile=boot_profile
                 )
+                if boot_profile != "localboot":
+                    # For localboot, there is no need to update the variable
+                    # csentry_autoinstall_boot_profile is used for DHCP options
+                    if utils.update_ansible_vars(
+                        host, {"csentry_autoinstall_boot_profile": boot_profile}
+                    ):
+                        # If a change occured, force DHCP update
+                        utils.trigger_core_services_update()
                 db.session.commit()
                 current_app.logger.info(
                     f"Set network boot profile to {boot_profile} for {name} requested: task {task.id}"
diff --git a/app/utils.py b/app/utils.py
index c1f2c66..3fa9bbf 100644
--- a/app/utils.py
+++ b/app/utils.py
@@ -501,3 +501,24 @@ def retrieve_data_for_datatables(values, model):
 def minutes_ago(minutes):
     """Return the datetime x minutes ago"""
     return datetime.datetime.utcnow() - datetime.timedelta(minutes=minutes)
+
+
+def update_ansible_vars(host, vars):
+    """Update the host ansible_vars
+
+    Return False if no variables were changed, True otherwise
+    """
+    if host.ansible_vars:
+        local_ansible_vars = host.ansible_vars.copy()
+        local_ansible_vars.update(vars)
+        if local_ansible_vars == host.ansible_vars:
+            # No change
+            return False
+        else:
+            host.ansible_vars.update(vars)
+            # If we don't flag the field as modified, it's not saved to the database
+            # Probably because we update an existing dictionary
+            sa.orm.attributes.flag_modified(host, "ansible_vars")
+    else:
+        host.ansible_vars = vars
+    return True
-- 
GitLab