gce.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #!/usr/bin/env python2
  2. # Copyright 2013 Google Inc.
  3. #
  4. # This file is part of Ansible
  5. #
  6. # Ansible is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # Ansible is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  18. '''
  19. GCE external inventory script
  20. =================================
  21. Generates inventory that Ansible can understand by making API requests
  22. Google Compute Engine via the libcloud library. Full install/configuration
  23. instructions for the gce* modules can be found in the comments of
  24. ansible/test/gce_tests.py.
  25. When run against a specific host, this script returns the following variables
  26. based on the data obtained from the libcloud Node object:
  27. - gce_uuid
  28. - gce_id
  29. - gce_image
  30. - gce_machine_type
  31. - gce_private_ip
  32. - gce_public_ip
  33. - gce_name
  34. - gce_description
  35. - gce_status
  36. - gce_zone
  37. - gce_tags
  38. - gce_metadata
  39. - gce_network
  40. When run in --list mode, instances are grouped by the following categories:
  41. - zone:
  42. zone group name examples are us-central1-b, europe-west1-a, etc.
  43. - instance tags:
  44. An entry is created for each tag. For example, if you have two instances
  45. with a common tag called 'foo', they will both be grouped together under
  46. the 'tag_foo' name.
  47. - network name:
  48. the name of the network is appended to 'network_' (e.g. the 'default'
  49. network will result in a group named 'network_default')
  50. - machine type
  51. types follow a pattern like n1-standard-4, g1-small, etc.
  52. - running status:
  53. group name prefixed with 'status_' (e.g. status_running, status_stopped,..)
  54. - image:
  55. when using an ephemeral/scratch disk, this will be set to the image name
  56. used when creating the instance (e.g. debian-7-wheezy-v20130816). when
  57. your instance was created with a root persistent disk it will be set to
  58. 'persistent_disk' since there is no current way to determine the image.
  59. Examples:
  60. Execute uname on all instances in the us-central1-a zone
  61. $ ansible -i gce.py us-central1-a -m shell -a "/bin/uname -a"
  62. Use the GCE inventory script to print out instance specific information
  63. $ plugins/inventory/gce.py --host my_instance
  64. Author: Eric Johnson <erjohnso@google.com>
  65. Version: 0.0.1
  66. '''
  67. USER_AGENT_PRODUCT="Ansible-gce_inventory_plugin"
  68. USER_AGENT_VERSION="v1"
  69. import sys
  70. import os
  71. import argparse
  72. import ConfigParser
  73. try:
  74. import json
  75. except ImportError:
  76. import simplejson as json
  77. try:
  78. from libcloud.compute.types import Provider
  79. from libcloud.compute.providers import get_driver
  80. _ = Provider.GCE
  81. except:
  82. print("GCE inventory script requires libcloud >= 0.13")
  83. sys.exit(1)
  84. class GceInventory(object):
  85. def __init__(self):
  86. # Read settings and parse CLI arguments
  87. self.parse_cli_args()
  88. self.driver = self.get_gce_driver()
  89. # Just display data for specific host
  90. if self.args.host:
  91. print self.json_format_dict(self.node_to_dict(
  92. self.get_instance(self.args.host)),
  93. pretty=self.args.pretty)
  94. sys.exit(0)
  95. # Otherwise, assume user wants all instances grouped
  96. print(self.json_format_dict(self.group_instances(),
  97. pretty=self.args.pretty))
  98. sys.exit(0)
  99. def get_gce_driver(self):
  100. """Determine the GCE authorization settings and return a
  101. libcloud driver.
  102. """
  103. gce_ini_default_path = os.path.join(
  104. os.path.dirname(os.path.realpath(__file__)), "gce.ini")
  105. gce_ini_path = os.environ.get('GCE_INI_PATH', gce_ini_default_path)
  106. print "GCE INI PATH :: "+gce_ini_path
  107. # Create a ConfigParser.
  108. # This provides empty defaults to each key, so that environment
  109. # variable configuration (as opposed to INI configuration) is able
  110. # to work.
  111. config = ConfigParser.SafeConfigParser(defaults={
  112. 'gce_service_account_email_address': '',
  113. 'gce_service_account_pem_file_path': '',
  114. 'gce_project_id': '',
  115. 'libcloud_secrets': '',
  116. })
  117. if 'gce' not in config.sections():
  118. config.add_section('gce')
  119. config.read(gce_ini_path)
  120. # Attempt to get GCE params from a configuration file, if one
  121. # exists.
  122. secrets_path = config.get('gce', 'libcloud_secrets')
  123. secrets_found = False
  124. try:
  125. import secrets
  126. args = list(getattr(secrets, 'GCE_PARAMS', []))
  127. kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {})
  128. secrets_found = True
  129. except:
  130. pass
  131. if not secrets_found and secrets_path:
  132. if not secrets_path.endswith('secrets.py'):
  133. err = "Must specify libcloud secrets file as "
  134. err += "/absolute/path/to/secrets.py"
  135. print(err)
  136. sys.exit(1)
  137. sys.path.append(os.path.dirname(secrets_path))
  138. try:
  139. import secrets
  140. args = list(getattr(secrets, 'GCE_PARAMS', []))
  141. kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {})
  142. secrets_found = True
  143. except:
  144. pass
  145. if not secrets_found:
  146. args = [
  147. config.get('gce','gce_service_account_email_address'),
  148. config.get('gce','gce_service_account_pem_file_path')
  149. ]
  150. kwargs = {'project': config.get('gce', 'gce_project_id')}
  151. # If the appropriate environment variables are set, they override
  152. # other configuration; process those into our args and kwargs.
  153. args[0] = os.environ.get('GCE_EMAIL', args[0])
  154. args[1] = os.environ.get('GCE_PEM_FILE_PATH', args[1])
  155. kwargs['project'] = os.environ.get('GCE_PROJECT', kwargs['project'])
  156. sys.stderr.write("GCE_EMAIL : "+args[0]+"\n")
  157. sys.stderr.write("GCE_PEM_FILE_PATH : "+args[1]+"\n")
  158. sys.stderr.write("GCE_PROJECT : "+kwargs['project']+"\n")
  159. # Retrieve and return the GCE driver.
  160. gce = get_driver(Provider.GCE)(*args, **kwargs)
  161. gce.connection.user_agent_append(
  162. '%s/%s' % (USER_AGENT_PRODUCT, USER_AGENT_VERSION),
  163. )
  164. return gce
  165. def parse_cli_args(self):
  166. ''' Command line argument processing '''
  167. parser = argparse.ArgumentParser(
  168. description='Produce an Ansible Inventory file based on GCE')
  169. parser.add_argument('--list', action='store_true', default=True,
  170. help='List instances (default: True)')
  171. parser.add_argument('--host', action='store',
  172. help='Get all information about an instance')
  173. parser.add_argument('--pretty', action='store_true', default=False,
  174. help='Pretty format (default: False)')
  175. self.args = parser.parse_args()
  176. def node_to_dict(self, inst):
  177. md = {}
  178. if inst is None:
  179. return {}
  180. if inst.extra['metadata'].has_key('items'):
  181. for entry in inst.extra['metadata']['items']:
  182. md[entry['key']] = entry['value']
  183. net = inst.extra['networkInterfaces'][0]['network'].split('/')[-1]
  184. return {
  185. 'gce_uuid': inst.uuid,
  186. 'gce_id': inst.id,
  187. 'gce_image': inst.image,
  188. 'gce_machine_type': inst.size,
  189. 'gce_private_ip': inst.private_ips[0],
  190. # Hosts don't always have a public IP name
  191. #'gce_public_ip': inst.public_ips[0],
  192. 'gce_name': inst.name,
  193. 'gce_description': inst.extra['description'],
  194. 'gce_status': inst.extra['status'],
  195. 'gce_zone': inst.extra['zone'].name,
  196. 'gce_tags': inst.extra['tags'],
  197. 'gce_metadata': md,
  198. 'gce_network': net,
  199. # Hosts don't always have a public IP name
  200. #'ansible_ssh_host': inst.public_ips[0]
  201. }
  202. def get_instance(self, instance_name):
  203. '''Gets details about a specific instance '''
  204. try:
  205. return self.driver.ex_get_node(instance_name)
  206. except Exception, e:
  207. return None
  208. def group_instances(self):
  209. '''Group all instances'''
  210. groups = {}
  211. meta = {}
  212. meta["hostvars"] = {}
  213. for node in self.driver.list_nodes():
  214. name = node.name
  215. meta["hostvars"][name] = self.node_to_dict(node)
  216. zone = node.extra['zone'].name
  217. if groups.has_key(zone): groups[zone].append(name)
  218. else: groups[zone] = [name]
  219. tags = node.extra['tags']
  220. for t in tags:
  221. tag = 'tag_%s' % t
  222. if groups.has_key(tag): groups[tag].append(name)
  223. else: groups[tag] = [name]
  224. net = node.extra['networkInterfaces'][0]['network'].split('/')[-1]
  225. net = 'network_%s' % net
  226. if groups.has_key(net): groups[net].append(name)
  227. else: groups[net] = [name]
  228. machine_type = node.size
  229. if groups.has_key(machine_type): groups[machine_type].append(name)
  230. else: groups[machine_type] = [name]
  231. image = node.image and node.image or 'persistent_disk'
  232. if groups.has_key(image): groups[image].append(name)
  233. else: groups[image] = [name]
  234. status = node.extra['status']
  235. stat = 'status_%s' % status.lower()
  236. if groups.has_key(stat): groups[stat].append(name)
  237. else: groups[stat] = [name]
  238. groups["_meta"] = meta
  239. return groups
  240. def json_format_dict(self, data, pretty=False):
  241. ''' Converts a dict to a JSON object and dumps it as a formatted
  242. string '''
  243. if pretty:
  244. return json.dumps(data, sort_keys=True, indent=2)
  245. else:
  246. return json.dumps(data)
  247. # Run the script
  248. print "Hello world"
  249. GceInventory()