From 718291d5734f2e7e32451458b0c1e09edba83d84 Mon Sep 17 00:00:00 2001 From: Shay Nehmad Date: Thu, 2 Jan 2020 12:16:48 +0200 Subject: [PATCH] Tested the AzureInstance class Tested on Azure instance and non-cloud instace. Seems to work :leo:. Unit tests aren't relevant here --- monkey/common/cloud/azure/azure_instance.py | 35 +++++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/monkey/common/cloud/azure/azure_instance.py b/monkey/common/cloud/azure/azure_instance.py index 2c949aa2c..a58e0e126 100644 --- a/monkey/common/cloud/azure/azure_instance.py +++ b/monkey/common/cloud/azure/azure_instance.py @@ -1,27 +1,50 @@ +import logging 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): """ 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): + """ + 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: response = requests.get(AZURE_METADATA_SERVICE_URL, headers={"Metadata": "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: - self.on_azure = True + logger.debug("On Azure. Trying to parse metadata.") self.try_parse_response(response) else: - self.on_azure = False - except ConnectionError: + logger.warning("On Azure, but metadata response not ok: {}".format(response.status_code)) + except requests.RequestException: + logger.debug("Failed to get response from Azure metadata service: This instance is not on Azure.") self.on_azure = False def try_parse_response(self, response): - # TODO implement - get fields from metadata like region etc. - pass + try: + 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): return self.on_azure