/plugins/inventory/windows_azure.py

https://github.com/ajanthanm/ansible · Python · 232 lines · 132 code · 38 blank · 62 comment · 32 complexity · 983546ac2eee9b8c8a2f4a15a3474047 MD5 · raw file

  1. #!/usr/bin/env python
  2. '''
  3. Windows Azure external inventory script
  4. =======================================
  5. Generates inventory that Ansible can understand by making API request to
  6. Windows Azure using the azure python library.
  7. NOTE: This script assumes Ansible is being executed where azure is already
  8. installed.
  9. pip install azure
  10. Adapted from the ansible Linode plugin by Dan Slimmon.
  11. '''
  12. # (c) 2013, John Whitbeck
  13. #
  14. # This file is part of Ansible,
  15. #
  16. # Ansible is free software: you can redistribute it and/or modify
  17. # it under the terms of the GNU General Public License as published by
  18. # the Free Software Foundation, either version 3 of the License, or
  19. # (at your option) any later version.
  20. #
  21. # Ansible is distributed in the hope that it will be useful,
  22. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. # GNU General Public License for more details.
  25. #
  26. # You should have received a copy of the GNU General Public License
  27. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  28. ######################################################################
  29. # Standard imports
  30. import re
  31. import sys
  32. import argparse
  33. import os
  34. from urlparse import urlparse
  35. from time import time
  36. try:
  37. import json
  38. except ImportError:
  39. import simplejson as json
  40. try:
  41. import azure
  42. from azure import WindowsAzureError
  43. from azure.servicemanagement import ServiceManagementService
  44. except ImportError as e:
  45. print "failed=True msg='`azure` library required for this script'"
  46. sys.exit(1)
  47. # Imports for ansible
  48. import ConfigParser
  49. class AzureInventory(object):
  50. def __init__(self):
  51. """Main execution path."""
  52. # Inventory grouped by display group
  53. self.inventory = {}
  54. # Index of deployment name -> host
  55. self.index = {}
  56. # Read settings and parse CLI arguments
  57. self.read_settings()
  58. self.read_environment()
  59. self.parse_cli_args()
  60. # Initialize Azure ServiceManagementService
  61. self.sms = ServiceManagementService(self.subscription_id, self.cert_path)
  62. # Cache
  63. if self.args.refresh_cache:
  64. self.do_api_calls_update_cache()
  65. elif not self.is_cache_valid():
  66. self.do_api_calls_update_cache()
  67. if self.args.list_images:
  68. data_to_print = self.json_format_dict(self.get_images(), True)
  69. elif self.args.list:
  70. # Display list of nodes for inventory
  71. if len(self.inventory) == 0:
  72. data_to_print = self.get_inventory_from_cache()
  73. else:
  74. data_to_print = self.json_format_dict(self.inventory, True)
  75. print data_to_print
  76. def get_images(self):
  77. images = []
  78. for image in self.sms.list_os_images():
  79. if str(image.label).lower().find(self.args.list_images.lower()) >= 0:
  80. images.append(vars(image))
  81. return json.loads(json.dumps(images, default=lambda o: o.__dict__))
  82. def is_cache_valid(self):
  83. """Determines if the cache file has expired, or if it is still valid."""
  84. if os.path.isfile(self.cache_path_cache):
  85. mod_time = os.path.getmtime(self.cache_path_cache)
  86. current_time = time()
  87. if (mod_time + self.cache_max_age) > current_time:
  88. if os.path.isfile(self.cache_path_index):
  89. return True
  90. return False
  91. def read_settings(self):
  92. """Reads the settings from the .ini file."""
  93. config = ConfigParser.SafeConfigParser()
  94. config.read(os.path.dirname(os.path.realpath(__file__)) + '/windows_azure.ini')
  95. # Credentials related
  96. if config.has_option('azure', 'subscription_id'):
  97. self.subscription_id = config.get('azure', 'subscription_id')
  98. if config.has_option('azure', 'cert_path'):
  99. self.cert_path = config.get('azure', 'cert_path')
  100. # Cache related
  101. if config.has_option('azure', 'cache_path'):
  102. cache_path = config.get('azure', 'cache_path')
  103. self.cache_path_cache = cache_path + "/ansible-azure.cache"
  104. self.cache_path_index = cache_path + "/ansible-azure.index"
  105. if config.has_option('azure', 'cache_max_age'):
  106. self.cache_max_age = config.getint('azure', 'cache_max_age')
  107. def read_environment(self):
  108. ''' Reads the settings from environment variables '''
  109. # Credentials
  110. if os.getenv("AZURE_SUBSCRIPTION_ID"): self.subscription_id = os.getenv("AZURE_SUBSCRIPTION_ID")
  111. if os.getenv("AZURE_CERT_PATH"): self.cert_path = os.getenv("AZURE_CERT_PATH")
  112. def parse_cli_args(self):
  113. """Command line argument processing"""
  114. parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on Azure')
  115. parser.add_argument('--list', action='store_true', default=True,
  116. help='List nodes (default: True)')
  117. parser.add_argument('--list-images', action='store',
  118. help='Get all available images.')
  119. parser.add_argument('--refresh-cache', action='store_true', default=False,
  120. help='Force refresh of cache by making API requests to Azure (default: False - use cache files)')
  121. self.args = parser.parse_args()
  122. def do_api_calls_update_cache(self):
  123. """Do API calls, and save data in cache files."""
  124. self.add_cloud_services()
  125. self.write_to_cache(self.inventory, self.cache_path_cache)
  126. self.write_to_cache(self.index, self.cache_path_index)
  127. def add_cloud_services(self):
  128. """Makes an Azure API call to get the list of cloud services."""
  129. try:
  130. for cloud_service in self.sms.list_hosted_services():
  131. self.add_deployments(cloud_service)
  132. except WindowsAzureError as e:
  133. print "Looks like Azure's API is down:"
  134. print
  135. print e
  136. sys.exit(1)
  137. def add_deployments(self, cloud_service):
  138. """Makes an Azure API call to get the list of virtual machines associated with a cloud service"""
  139. try:
  140. for deployment in self.sms.get_hosted_service_properties(cloud_service.service_name,embed_detail=True).deployments.deployments:
  141. if deployment.deployment_slot == "Production":
  142. self.add_deployment(cloud_service, deployment)
  143. except WindowsAzureError as e:
  144. print "Looks like Azure's API is down:"
  145. print
  146. print e
  147. sys.exit(1)
  148. def add_deployment(self, cloud_service, deployment):
  149. """Adds a deployment to the inventory and index"""
  150. dest = urlparse(deployment.url).hostname
  151. # Add to index
  152. self.index[dest] = deployment.name
  153. # List of all azure deployments
  154. self.push(self.inventory, "azure", dest)
  155. # Inventory: Group by service name
  156. self.push(self.inventory, self.to_safe(cloud_service.service_name), dest)
  157. # Inventory: Group by region
  158. self.push(self.inventory, self.to_safe(cloud_service.hosted_service_properties.location), dest)
  159. def push(self, my_dict, key, element):
  160. """Pushed an element onto an array that may not have been defined in the dict."""
  161. if key in my_dict:
  162. my_dict[key].append(element);
  163. else:
  164. my_dict[key] = [element]
  165. def get_inventory_from_cache(self):
  166. """Reads the inventory from the cache file and returns it as a JSON object."""
  167. cache = open(self.cache_path_cache, 'r')
  168. json_inventory = cache.read()
  169. return json_inventory
  170. def load_index_from_cache(self):
  171. """Reads the index from the cache file and sets self.index."""
  172. cache = open(self.cache_path_index, 'r')
  173. json_index = cache.read()
  174. self.index = json.loads(json_index)
  175. def write_to_cache(self, data, filename):
  176. """Writes data in JSON format to a file."""
  177. json_data = self.json_format_dict(data, True)
  178. cache = open(filename, 'w')
  179. cache.write(json_data)
  180. cache.close()
  181. def to_safe(self, word):
  182. """Escapes any characters that would be invalid in an ansible group name."""
  183. return re.sub("[^A-Za-z0-9\-]", "_", word)
  184. def json_format_dict(self, data, pretty=False):
  185. """Converts a dict to a JSON object and dumps it as a formatted string."""
  186. if pretty:
  187. return json.dumps(data, sort_keys=True, indent=2)
  188. else:
  189. return json.dumps(data)
  190. AzureInventory()