PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/inventory/softlayer.py

https://gitlab.com/0072016/Facebook-SDK-json-
Python | 163 lines | 122 code | 9 blank | 32 comment | 3 complexity | 0f5e090244f5f2f2a4fa6d1a5b808e74 MD5 | raw file
  1. #!/usr/bin/env python
  2. """
  3. SoftLayer external inventory script.
  4. The SoftLayer Python API client is required. Use `pip install softlayer` to install it.
  5. You have a few different options for configuring your username and api_key. You can pass
  6. environment variables (SL_USERNAME and SL_API_KEY). You can also write INI file to
  7. ~/.softlayer or /etc/softlayer.conf. For more information see the SL API at:
  8. - https://softlayer-python.readthedocs.org/en/latest/config_file.html
  9. The SoftLayer Python client has a built in command for saving this configuration file
  10. via the command `sl config setup`.
  11. """
  12. # Copyright (C) 2014 AJ Bourg <aj@ajbourg.com>
  13. #
  14. # This program is free software: you can redistribute it and/or modify
  15. # it under the terms of the GNU General Public License as published by
  16. # the Free Software Foundation, either version 3 of the License, or
  17. # (at your option) any later version.
  18. #
  19. # This program is distributed in the hope that it will be useful,
  20. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. # GNU General Public License for more details.
  23. #
  24. # You should have received a copy of the GNU General Public License
  25. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. #
  27. # I found the structure of the ec2.py script very helpful as an example
  28. # as I put this together. Thanks to whoever wrote that script!
  29. #
  30. import SoftLayer
  31. import re
  32. import argparse
  33. try:
  34. import json
  35. except:
  36. import simplejson as json
  37. class SoftLayerInventory(object):
  38. def _empty_inventory(self):
  39. return {"_meta" : {"hostvars" : {}}}
  40. def __init__(self):
  41. '''Main path'''
  42. self.inventory = self._empty_inventory()
  43. self.parse_options()
  44. if self.args.list:
  45. self.get_all_servers()
  46. print(self.json_format_dict(self.inventory, True))
  47. elif self.args.host:
  48. self.get_virtual_servers()
  49. print(self.json_format_dict(self.inventory["_meta"]["hostvars"][self.args.host], True))
  50. def to_safe(self, word):
  51. '''Converts 'bad' characters in a string to underscores so they can be used as Ansible groups'''
  52. return re.sub("[^A-Za-z0-9\-\.]", "_", word)
  53. def push(self, my_dict, key, element):
  54. '''Push an element onto an array that may not have been defined in the dict'''
  55. if key in my_dict:
  56. my_dict[key].append(element);
  57. else:
  58. my_dict[key] = [element]
  59. def parse_options(self):
  60. '''Parse all the arguments from the CLI'''
  61. parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on SoftLayer')
  62. parser.add_argument('--list', action='store_true', default=False,
  63. help='List instances (default: False)')
  64. parser.add_argument('--host', action='store',
  65. help='Get all the variables about a specific instance')
  66. self.args = parser.parse_args()
  67. def json_format_dict(self, data, pretty=False):
  68. '''Converts a dict to a JSON object and dumps it as a formatted string'''
  69. if pretty:
  70. return json.dumps(data, sort_keys=True, indent=2)
  71. else:
  72. return json.dumps(data)
  73. def process_instance(self, instance, instance_type="virtual"):
  74. '''Populate the inventory dictionary with any instance information'''
  75. # only want active instances
  76. if 'status' in instance and instance['status']['name'] != 'Active':
  77. return
  78. # and powered on instances
  79. if 'powerState' in instance and instance['powerState']['name'] != 'Running':
  80. return
  81. # 5 is active for hardware... see https://forums.softlayer.com/forum/softlayer-developer-network/general-discussion/2955-hardwarestatusid
  82. if 'hardwareStatusId' in instance and instance['hardwareStatusId'] != 5:
  83. return
  84. # if there's no IP address, we can't reach it
  85. if 'primaryIpAddress' not in instance:
  86. return
  87. dest = instance['primaryIpAddress']
  88. self.inventory["_meta"]["hostvars"][dest] = instance
  89. # Inventory: group by memory
  90. if 'maxMemory' in instance:
  91. self.push(self.inventory, self.to_safe('memory_' + str(instance['maxMemory'])), dest)
  92. elif 'memoryCapacity' in instance:
  93. self.push(self.inventory, self.to_safe('memory_' + str(instance['memoryCapacity'])), dest)
  94. # Inventory: group by cpu count
  95. if 'maxCpu' in instance:
  96. self.push(self.inventory, self.to_safe('cpu_' + str(instance['maxCpu'])), dest)
  97. elif 'processorPhysicalCoreAmount' in instance:
  98. self.push(self.inventory, self.to_safe('cpu_' + str(instance['processorPhysicalCoreAmount'])), dest)
  99. # Inventory: group by datacenter
  100. self.push(self.inventory, self.to_safe('datacenter_' + instance['datacenter']['name']), dest)
  101. # Inventory: group by hostname
  102. self.push(self.inventory, self.to_safe(instance['hostname']), dest)
  103. # Inventory: group by FQDN
  104. self.push(self.inventory, self.to_safe(instance['fullyQualifiedDomainName']), dest)
  105. # Inventory: group by domain
  106. self.push(self.inventory, self.to_safe(instance['domain']), dest)
  107. # Inventory: group by type (hardware/virtual)
  108. self.push(self.inventory, instance_type, dest)
  109. def get_virtual_servers(self):
  110. '''Get all the CCI instances'''
  111. vs = SoftLayer.VSManager(self.client)
  112. instances = vs.list_instances()
  113. for instance in instances:
  114. self.process_instance(instance)
  115. def get_physical_servers(self):
  116. '''Get all the hardware instances'''
  117. hw = SoftLayer.HardwareManager(self.client)
  118. instances = hw.list_hardware()
  119. for instance in instances:
  120. self.process_instance(instance, 'hardware')
  121. def get_all_servers(self):
  122. self.client = SoftLayer.Client()
  123. self.get_virtual_servers()
  124. self.get_physical_servers()
  125. SoftLayerInventory()