Tested the AzureInstance class

Tested on Azure instance and non-cloud instace. Seems to work . Unit tests aren't relevant here
This commit is contained in:
Shay Nehmad 2020-01-02 12:16:48 +02:00
parent 81b44f0ebb
commit 718291d573
1 changed files with 29 additions and 6 deletions

View File

@ -1,27 +1,50 @@
import logging
import requests import requests
AZURE_METADATA_SERVICE_URL = "http://169.254.169.254/metadata/instance?api-version=2019-06-04" LATEST_AZURE_METADATA_API_VERSION = "2019-06-04"
AZURE_METADATA_SERVICE_URL = "http://169.254.169.254/metadata/instance?api-version=%s" % LATEST_AZURE_METADATA_API_VERSION
logger = logging.getLogger(__name__)
class AzureInstance(object): class AzureInstance(object):
""" """
Access to useful information about the current machine if it's an Azure VM. Access to useful information about the current machine if it's an Azure VM.
Based on Azure metadata service: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service
""" """
def __init__(self): def __init__(self):
"""
Determines if on Azure and if so, gets some basic metadata on this instance.
"""
self.instance_name = None
self.instance_id = None
self.location = None
self.on_azure = False
try: try:
response = requests.get(AZURE_METADATA_SERVICE_URL, headers={"Metadata": "true"}) response = requests.get(AZURE_METADATA_SERVICE_URL, headers={"Metadata": "true"})
if response:
self.on_azure = True self.on_azure = True
# If not on cloud, the metadata URL is non-routable and the connection will fail.
# If on AWS, should get 404 since the metadata service URL is different, so bool(response) will be false.
if response:
logger.debug("On Azure. Trying to parse metadata.")
self.try_parse_response(response) self.try_parse_response(response)
else: else:
self.on_azure = False logger.warning("On Azure, but metadata response not ok: {}".format(response.status_code))
except ConnectionError: except requests.RequestException:
logger.debug("Failed to get response from Azure metadata service: This instance is not on Azure.")
self.on_azure = False self.on_azure = False
def try_parse_response(self, response): def try_parse_response(self, response):
# TODO implement - get fields from metadata like region etc. try:
pass response_data = response.json()
self.instance_name = response_data["compute"]["name"]
self.instance_id = response_data["compute"]["vmId"]
self.location = response_data["compute"]["location"]
except KeyError:
logger.exception("Error while parsing response from Azure metadata service.")
def is_azure_instance(self): def is_azure_instance(self):
return self.on_azure return self.on_azure