From 9662a8791e53bac40a3a37aa3f5bee3076f7d447 Mon Sep 17 00:00:00 2001
From: Joshua Hügli <joshua@trafficteam.ch>
Date: Tue, 12 Nov 2019 13:42:41 -0700
Subject: add data-server dns entry as new metadata server detection

---
 cloudinit/sources/DataSourceCloudStack.py | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)

diff --git a/cloudinit/sources/DataSourceCloudStack.py b/cloudinit/sources/DataSourceCloudStack.py
index f185dc71..e333cb50 100644
--- a/cloudinit/sources/DataSourceCloudStack.py
+++ b/cloudinit/sources/DataSourceCloudStack.py
@@ -13,7 +13,7 @@
 # This file is part of cloud-init. See LICENSE file for license information.
 
 import os
-from socket import inet_ntoa
+from socket import inet_ntoa, getaddrinfo, gaierror
 from struct import pack
 import time
 
@@ -156,6 +156,17 @@ class DataSourceCloudStack(sources.DataSource):
         return self.metadata['availability-zone']
 
 
+def get_data_server():
+    # Returns the metadataserver from dns
+    try:
+        addrinfo = getaddrinfo("data-server.", 80)
+    except gaierror:
+        LOG.debug("DNS Entry data-server not found")
+        return None
+    else:
+        return addrinfo[0][4][0]  # return IP
+
+
 def get_default_gateway():
     # Returns the default gateway ip address in the dotted format.
     lines = util.load_file("/proc/net/route").splitlines()
@@ -218,7 +229,14 @@ def get_vr_address():
     # If no virtual router is detected, fallback on default gateway.
     # See http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/4.8/virtual_machines/user-data.html # noqa
 
-    # Try networkd first...
+    # Try data-server DNS entry first
+    latest_address = get_data_server()
+    if latest_address:
+        LOG.debug("Found metadata server '%s' via data-server DNS entry",
+                  latest_address)
+        return latest_address
+
+    # Try networkd second...
     latest_address = dhcp.networkd_get_option_from_leases('SERVER_ADDRESS')
     if latest_address:
         LOG.debug("Found SERVER_ADDRESS '%s' via networkd_leases",
-- 
cgit v1.2.3