You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

402 lines
12 KiB

  1. #!/usr/bin/env python2
  2. #
  3. # Copyright 2015 Cisco Systems, Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # original: https://github.com/CiscoCloud/terraform.py
  18. """\
  19. Dynamic inventory for Terraform - finds all `.tfstate` files below the working
  20. directory and generates an inventory based on them.
  21. """
  22. from __future__ import unicode_literals, print_function
  23. import argparse
  24. from collections import defaultdict
  25. from functools import wraps
  26. import json
  27. import os
  28. import re
  29. VERSION = '0.3.0pre'
  30. def tfstates(root=None):
  31. root = root or os.getcwd()
  32. for dirpath, _, filenames in os.walk(root):
  33. for name in filenames:
  34. if os.path.splitext(name)[-1] == '.tfstate':
  35. yield os.path.join(dirpath, name)
  36. def iterresources(filenames):
  37. for filename in filenames:
  38. with open(filename, 'r') as json_file:
  39. state = json.load(json_file)
  40. for module in state['modules']:
  41. name = module['path'][-1]
  42. for key, resource in module['resources'].items():
  43. yield name, key, resource
  44. ## READ RESOURCES
  45. PARSERS = {}
  46. def _clean_dc(dcname):
  47. # Consul DCs are strictly alphanumeric with underscores and hyphens -
  48. # ensure that the consul_dc attribute meets these requirements.
  49. return re.sub('[^\w_\-]', '-', dcname)
  50. def iterhosts(resources):
  51. '''yield host tuples of (name, attributes, groups)'''
  52. for module_name, key, resource in resources:
  53. resource_type, name = key.split('.', 1)
  54. try:
  55. parser = PARSERS[resource_type]
  56. except KeyError:
  57. continue
  58. yield parser(resource, module_name)
  59. def iterips(resources):
  60. '''yield ip tuples of (instance_id, ip)'''
  61. for module_name, key, resource in resources:
  62. resource_type, name = key.split('.', 1)
  63. if resource_type == 'openstack_compute_floatingip_associate_v2':
  64. yield openstack_floating_ips(resource)
  65. def parses(prefix):
  66. def inner(func):
  67. PARSERS[prefix] = func
  68. return func
  69. return inner
  70. def calculate_mantl_vars(func):
  71. """calculate Mantl vars"""
  72. @wraps(func)
  73. def inner(*args, **kwargs):
  74. name, attrs, groups = func(*args, **kwargs)
  75. # attrs
  76. if attrs.get('role', '') == 'control':
  77. attrs['consul_is_server'] = True
  78. else:
  79. attrs['consul_is_server'] = False
  80. # groups
  81. if attrs.get('publicly_routable', False):
  82. groups.append('publicly_routable')
  83. return name, attrs, groups
  84. return inner
  85. def _parse_prefix(source, prefix, sep='.'):
  86. for compkey, value in source.items():
  87. try:
  88. curprefix, rest = compkey.split(sep, 1)
  89. except ValueError:
  90. continue
  91. if curprefix != prefix or rest == '#':
  92. continue
  93. yield rest, value
  94. def parse_attr_list(source, prefix, sep='.'):
  95. attrs = defaultdict(dict)
  96. for compkey, value in _parse_prefix(source, prefix, sep):
  97. idx, key = compkey.split(sep, 1)
  98. attrs[idx][key] = value
  99. return attrs.values()
  100. def parse_dict(source, prefix, sep='.'):
  101. return dict(_parse_prefix(source, prefix, sep))
  102. def parse_list(source, prefix, sep='.'):
  103. return [value for _, value in _parse_prefix(source, prefix, sep)]
  104. def parse_bool(string_form):
  105. token = string_form.lower()[0]
  106. if token == 't':
  107. return True
  108. elif token == 'f':
  109. return False
  110. else:
  111. raise ValueError('could not convert %r to a bool' % string_form)
  112. @parses('packet_device')
  113. def packet_device(resource, tfvars=None):
  114. raw_attrs = resource['primary']['attributes']
  115. name = raw_attrs['hostname']
  116. groups = []
  117. attrs = {
  118. 'id': raw_attrs['id'],
  119. 'facilities': parse_list(raw_attrs, 'facilities']),
  120. 'hostname': raw_attrs['hostname'],
  121. 'operating_system': raw_attrs['operating_system'],
  122. 'locked': parse_bool(raw_attrs['locked']),
  123. 'tags': parse_list(raw_attrs, 'tags'),
  124. 'plan': raw_attrs['plan'],
  125. 'project_id': raw_attrs['project_id'],
  126. 'state': raw_attrs['state'],
  127. # ansible
  128. 'ansible_ssh_host': raw_attrs['network.0.address'],
  129. 'ansible_ssh_user': 'root', # it's always "root" on Packet
  130. # generic
  131. 'ipv4_address': raw_attrs['network.0.address'],
  132. 'public_ipv4': raw_attrs['network.0.address'],
  133. 'ipv6_address': raw_attrs['network.1.address'],
  134. 'public_ipv6': raw_attrs['network.1.address'],
  135. 'private_ipv4': raw_attrs['network.2.address'],
  136. 'provider': 'packet',
  137. }
  138. # add groups based on attrs
  139. groups.append('packet_facilities=' + attrs['facilities'])
  140. groups.append('packet_operating_system=' + attrs['operating_system'])
  141. groups.append('packet_locked=%s' % attrs['locked'])
  142. groups.append('packet_state=' + attrs['state'])
  143. groups.append('packet_plan=' + attrs['plan'])
  144. # groups specific to kubespray
  145. groups = groups + attrs['tags']
  146. return name, attrs, groups
  147. def openstack_floating_ips(resource):
  148. raw_attrs = resource['primary']['attributes']
  149. attrs = {
  150. 'ip': raw_attrs['floating_ip'],
  151. 'instance_id': raw_attrs['instance_id'],
  152. }
  153. return attrs
  154. def openstack_floating_ips(resource):
  155. raw_attrs = resource['primary']['attributes']
  156. return raw_attrs['instance_id'], raw_attrs['floating_ip']
  157. @parses('openstack_compute_instance_v2')
  158. @calculate_mantl_vars
  159. def openstack_host(resource, module_name):
  160. raw_attrs = resource['primary']['attributes']
  161. name = raw_attrs['name']
  162. groups = []
  163. attrs = {
  164. 'access_ip_v4': raw_attrs['access_ip_v4'],
  165. 'access_ip_v6': raw_attrs['access_ip_v6'],
  166. 'access_ip': raw_attrs['access_ip_v4'],
  167. 'ip': raw_attrs['network.0.fixed_ip_v4'],
  168. 'flavor': parse_dict(raw_attrs, 'flavor',
  169. sep='_'),
  170. 'id': raw_attrs['id'],
  171. 'image': parse_dict(raw_attrs, 'image',
  172. sep='_'),
  173. 'key_pair': raw_attrs['key_pair'],
  174. 'metadata': parse_dict(raw_attrs, 'metadata'),
  175. 'network': parse_attr_list(raw_attrs, 'network'),
  176. 'region': raw_attrs.get('region', ''),
  177. 'security_groups': parse_list(raw_attrs, 'security_groups'),
  178. # ansible
  179. 'ansible_ssh_port': 22,
  180. # workaround for an OpenStack bug where hosts have a different domain
  181. # after they're restarted
  182. 'host_domain': 'novalocal',
  183. 'use_host_domain': True,
  184. # generic
  185. 'public_ipv4': raw_attrs['access_ip_v4'],
  186. 'private_ipv4': raw_attrs['access_ip_v4'],
  187. 'provider': 'openstack',
  188. }
  189. if 'floating_ip' in raw_attrs:
  190. attrs['private_ipv4'] = raw_attrs['network.0.fixed_ip_v4']
  191. try:
  192. attrs.update({
  193. 'ansible_ssh_host': raw_attrs['access_ip_v4'],
  194. 'publicly_routable': True,
  195. })
  196. except (KeyError, ValueError):
  197. attrs.update({'ansible_ssh_host': '', 'publicly_routable': False})
  198. # Handling of floating IPs has changed: https://github.com/terraform-providers/terraform-provider-openstack/blob/master/CHANGELOG.md#010-june-21-2017
  199. # attrs specific to Ansible
  200. if 'metadata.ssh_user' in raw_attrs:
  201. attrs['ansible_ssh_user'] = raw_attrs['metadata.ssh_user']
  202. if 'volume.#' in raw_attrs.keys() and int(raw_attrs['volume.#']) > 0:
  203. device_index = 1
  204. for key, value in raw_attrs.items():
  205. match = re.search("^volume.*.device$", key)
  206. if match:
  207. attrs['disk_volume_device_'+str(device_index)] = value
  208. device_index += 1
  209. # attrs specific to Mantl
  210. attrs.update({
  211. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  212. 'role': attrs['metadata'].get('role', 'none'),
  213. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  214. })
  215. # add groups based on attrs
  216. groups.append('os_image=' + attrs['image']['name'])
  217. groups.append('os_flavor=' + attrs['flavor']['name'])
  218. groups.extend('os_metadata_%s=%s' % item
  219. for item in attrs['metadata'].items())
  220. groups.append('os_region=' + attrs['region'])
  221. # groups specific to Mantl
  222. groups.append('role=' + attrs['metadata'].get('role', 'none'))
  223. groups.append('dc=' + attrs['consul_dc'])
  224. # groups specific to kubespray
  225. for group in attrs['metadata'].get('kubespray_groups', "").split(","):
  226. groups.append(group)
  227. return name, attrs, groups
  228. def iter_host_ips(hosts, ips):
  229. '''Update hosts that have an entry in the floating IP list'''
  230. for host in hosts:
  231. host_id = host[1]['id']
  232. if host_id in ips:
  233. ip = ips[host_id]
  234. host[1].update({
  235. 'access_ip_v4': ip,
  236. 'access_ip': ip,
  237. 'public_ipv4': ip,
  238. 'ansible_ssh_host': ip,
  239. })
  240. yield host
  241. ## QUERY TYPES
  242. def query_host(hosts, target):
  243. for name, attrs, _ in hosts:
  244. if name == target:
  245. return attrs
  246. return {}
  247. def query_list(hosts):
  248. groups = defaultdict(dict)
  249. meta = {}
  250. for name, attrs, hostgroups in hosts:
  251. for group in set(hostgroups):
  252. # Ansible 2.6.2 stopped supporting empty group names: https://github.com/ansible/ansible/pull/42584/commits/d4cd474b42ed23d8f8aabb2a7f84699673852eaf
  253. # Empty group name defaults to "all" in Ansible < 2.6.2 so we alter empty group names to "all"
  254. if not group: group = "all"
  255. groups[group].setdefault('hosts', [])
  256. groups[group]['hosts'].append(name)
  257. meta[name] = attrs
  258. groups['_meta'] = {'hostvars': meta}
  259. return groups
  260. def query_hostfile(hosts):
  261. out = ['## begin hosts generated by terraform.py ##']
  262. out.extend(
  263. '{}\t{}'.format(attrs['ansible_ssh_host'].ljust(16), name)
  264. for name, attrs, _ in hosts
  265. )
  266. out.append('## end hosts generated by terraform.py ##')
  267. return '\n'.join(out)
  268. def main():
  269. parser = argparse.ArgumentParser(
  270. __file__, __doc__,
  271. formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
  272. modes = parser.add_mutually_exclusive_group(required=True)
  273. modes.add_argument('--list',
  274. action='store_true',
  275. help='list all variables')
  276. modes.add_argument('--host', help='list variables for a single host')
  277. modes.add_argument('--version',
  278. action='store_true',
  279. help='print version and exit')
  280. modes.add_argument('--hostfile',
  281. action='store_true',
  282. help='print hosts as a /etc/hosts snippet')
  283. parser.add_argument('--pretty',
  284. action='store_true',
  285. help='pretty-print output JSON')
  286. parser.add_argument('--nometa',
  287. action='store_true',
  288. help='with --list, exclude hostvars')
  289. default_root = os.environ.get('TERRAFORM_STATE_ROOT',
  290. os.path.abspath(os.path.join(os.path.dirname(__file__),
  291. '..', '..', )))
  292. parser.add_argument('--root',
  293. default=default_root,
  294. help='custom root to search for `.tfstate`s in')
  295. args = parser.parse_args()
  296. if args.version:
  297. print('%s %s' % (__file__, VERSION))
  298. parser.exit()
  299. hosts = iterhosts(iterresources(tfstates(args.root)))
  300. # Perform a second pass on the file to pick up floating_ip entries to update the ip address of referenced hosts
  301. ips = dict(iterips(iterresources(tfstates(args.root))))
  302. if ips:
  303. hosts = iter_host_ips(hosts, ips)
  304. if args.list:
  305. output = query_list(hosts)
  306. if args.nometa:
  307. del output['_meta']
  308. print(json.dumps(output, indent=4 if args.pretty else None))
  309. elif args.host:
  310. output = query_host(hosts, args.host)
  311. print(json.dumps(output, indent=4 if args.pretty else None))
  312. elif args.hostfile:
  313. output = query_hostfile(hosts)
  314. print(output)
  315. parser.exit()
  316. if __name__ == '__main__':
  317. main()