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.

455 lines
15 KiB

  1. #!/usr/bin/env python3
  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. import argparse
  23. from collections import defaultdict
  24. import random
  25. from functools import wraps
  26. import json
  27. import os
  28. import re
  29. VERSION = '0.4.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 convert_to_v3_structure(attributes, prefix=''):
  37. """ Convert the attributes from v4 to v3
  38. Receives a dict and return a dictionary """
  39. result = {}
  40. if isinstance(attributes, str):
  41. # In the case when we receive a string (e.g. values for security_groups)
  42. return {'{}{}'.format(prefix, random.randint(1,10**10)): attributes}
  43. for key, value in attributes.items():
  44. if isinstance(value, list):
  45. if len(value):
  46. result['{}{}.#'.format(prefix, key, hash)] = len(value)
  47. for i, v in enumerate(value):
  48. result.update(convert_to_v3_structure(v, '{}{}.{}.'.format(prefix, key, i)))
  49. elif isinstance(value, dict):
  50. result['{}{}.%'.format(prefix, key)] = len(value)
  51. for k, v in value.items():
  52. result['{}{}.{}'.format(prefix, key, k)] = v
  53. else:
  54. result['{}{}'.format(prefix, key)] = value
  55. return result
  56. def iterresources(filenames):
  57. for filename in filenames:
  58. with open(filename, 'r') as json_file:
  59. state = json.load(json_file)
  60. tf_version = state['version']
  61. if tf_version == 3:
  62. for module in state['modules']:
  63. name = module['path'][-1]
  64. for key, resource in module['resources'].items():
  65. yield name, key, resource
  66. elif tf_version == 4:
  67. # In version 4 the structure changes so we need to iterate
  68. # each instance inside the resource branch.
  69. for resource in state['resources']:
  70. name = resource['module'].split('.')[-1]
  71. for instance in resource['instances']:
  72. key = "{}.{}".format(resource['type'], resource['name'])
  73. if 'index_key' in instance:
  74. key = "{}.{}".format(key, instance['index_key'])
  75. data = {}
  76. data['type'] = resource['type']
  77. data['provider'] = resource['provider']
  78. data['depends_on'] = instance.get('depends_on', [])
  79. data['primary'] = {'attributes': convert_to_v3_structure(instance['attributes'])}
  80. if 'id' in instance['attributes']:
  81. data['primary']['id'] = instance['attributes']['id']
  82. data['primary']['meta'] = instance['attributes'].get('meta',{})
  83. yield name, key, data
  84. else:
  85. raise KeyError('tfstate version %d not supported' % tf_version)
  86. ## READ RESOURCES
  87. PARSERS = {}
  88. def _clean_dc(dcname):
  89. # Consul DCs are strictly alphanumeric with underscores and hyphens -
  90. # ensure that the consul_dc attribute meets these requirements.
  91. return re.sub('[^\w_\-]', '-', dcname)
  92. def iterhosts(resources):
  93. '''yield host tuples of (name, attributes, groups)'''
  94. for module_name, key, resource in resources:
  95. resource_type, name = key.split('.', 1)
  96. try:
  97. parser = PARSERS[resource_type]
  98. except KeyError:
  99. continue
  100. yield parser(resource, module_name)
  101. def iterips(resources):
  102. '''yield ip tuples of (instance_id, ip)'''
  103. for module_name, key, resource in resources:
  104. resource_type, name = key.split('.', 1)
  105. if resource_type == 'openstack_compute_floatingip_associate_v2':
  106. yield openstack_floating_ips(resource)
  107. def parses(prefix):
  108. def inner(func):
  109. PARSERS[prefix] = func
  110. return func
  111. return inner
  112. def calculate_mantl_vars(func):
  113. """calculate Mantl vars"""
  114. @wraps(func)
  115. def inner(*args, **kwargs):
  116. name, attrs, groups = func(*args, **kwargs)
  117. # attrs
  118. if attrs.get('role', '') == 'control':
  119. attrs['consul_is_server'] = True
  120. else:
  121. attrs['consul_is_server'] = False
  122. # groups
  123. if attrs.get('publicly_routable', False):
  124. groups.append('publicly_routable')
  125. return name, attrs, groups
  126. return inner
  127. def _parse_prefix(source, prefix, sep='.'):
  128. for compkey, value in list(source.items()):
  129. try:
  130. curprefix, rest = compkey.split(sep, 1)
  131. except ValueError:
  132. continue
  133. if curprefix != prefix or rest == '#':
  134. continue
  135. yield rest, value
  136. def parse_attr_list(source, prefix, sep='.'):
  137. attrs = defaultdict(dict)
  138. for compkey, value in _parse_prefix(source, prefix, sep):
  139. idx, key = compkey.split(sep, 1)
  140. attrs[idx][key] = value
  141. return list(attrs.values())
  142. def parse_dict(source, prefix, sep='.'):
  143. return dict(_parse_prefix(source, prefix, sep))
  144. def parse_list(source, prefix, sep='.'):
  145. return [value for _, value in _parse_prefix(source, prefix, sep)]
  146. def parse_bool(string_form):
  147. token = string_form.lower()[0]
  148. if token == 't':
  149. return True
  150. elif token == 'f':
  151. return False
  152. else:
  153. raise ValueError('could not convert %r to a bool' % string_form)
  154. @parses('packet_device')
  155. def packet_device(resource, tfvars=None):
  156. raw_attrs = resource['primary']['attributes']
  157. name = raw_attrs['hostname']
  158. groups = []
  159. attrs = {
  160. 'id': raw_attrs['id'],
  161. 'facilities': parse_list(raw_attrs, 'facilities'),
  162. 'hostname': raw_attrs['hostname'],
  163. 'operating_system': raw_attrs['operating_system'],
  164. 'locked': parse_bool(raw_attrs['locked']),
  165. 'tags': parse_list(raw_attrs, 'tags'),
  166. 'plan': raw_attrs['plan'],
  167. 'project_id': raw_attrs['project_id'],
  168. 'state': raw_attrs['state'],
  169. # ansible
  170. 'ansible_ssh_host': raw_attrs['network.0.address'],
  171. 'ansible_ssh_user': 'root', # it's always "root" on Packet
  172. # generic
  173. 'ipv4_address': raw_attrs['network.0.address'],
  174. 'public_ipv4': raw_attrs['network.0.address'],
  175. 'ipv6_address': raw_attrs['network.1.address'],
  176. 'public_ipv6': raw_attrs['network.1.address'],
  177. 'private_ipv4': raw_attrs['network.2.address'],
  178. 'provider': 'packet',
  179. }
  180. # add groups based on attrs
  181. groups.append('packet_operating_system=' + attrs['operating_system'])
  182. groups.append('packet_locked=%s' % attrs['locked'])
  183. groups.append('packet_state=' + attrs['state'])
  184. groups.append('packet_plan=' + attrs['plan'])
  185. # groups specific to kubespray
  186. groups = groups + attrs['tags']
  187. return name, attrs, groups
  188. def openstack_floating_ips(resource):
  189. raw_attrs = resource['primary']['attributes']
  190. attrs = {
  191. 'ip': raw_attrs['floating_ip'],
  192. 'instance_id': raw_attrs['instance_id'],
  193. }
  194. return attrs
  195. def openstack_floating_ips(resource):
  196. raw_attrs = resource['primary']['attributes']
  197. return raw_attrs['instance_id'], raw_attrs['floating_ip']
  198. @parses('openstack_compute_instance_v2')
  199. @calculate_mantl_vars
  200. def openstack_host(resource, module_name):
  201. raw_attrs = resource['primary']['attributes']
  202. name = raw_attrs['name']
  203. groups = []
  204. attrs = {
  205. 'access_ip_v4': raw_attrs['access_ip_v4'],
  206. 'access_ip_v6': raw_attrs['access_ip_v6'],
  207. 'access_ip': raw_attrs['access_ip_v4'],
  208. 'ip': raw_attrs['network.0.fixed_ip_v4'],
  209. 'flavor': parse_dict(raw_attrs, 'flavor',
  210. sep='_'),
  211. 'id': raw_attrs['id'],
  212. 'image': parse_dict(raw_attrs, 'image',
  213. sep='_'),
  214. 'key_pair': raw_attrs['key_pair'],
  215. 'metadata': parse_dict(raw_attrs, 'metadata'),
  216. 'network': parse_attr_list(raw_attrs, 'network'),
  217. 'region': raw_attrs.get('region', ''),
  218. 'security_groups': parse_list(raw_attrs, 'security_groups'),
  219. # ansible
  220. 'ansible_ssh_port': 22,
  221. # workaround for an OpenStack bug where hosts have a different domain
  222. # after they're restarted
  223. 'host_domain': 'novalocal',
  224. 'use_host_domain': True,
  225. # generic
  226. 'public_ipv4': raw_attrs['access_ip_v4'],
  227. 'private_ipv4': raw_attrs['access_ip_v4'],
  228. 'provider': 'openstack',
  229. }
  230. if 'floating_ip' in raw_attrs:
  231. attrs['private_ipv4'] = raw_attrs['network.0.fixed_ip_v4']
  232. try:
  233. if 'metadata.prefer_ipv6' in raw_attrs and raw_attrs['metadata.prefer_ipv6'] == "1":
  234. attrs.update({
  235. 'ansible_ssh_host': re.sub("[\[\]]", "", raw_attrs['access_ip_v6']),
  236. 'publicly_routable': True,
  237. })
  238. else:
  239. attrs.update({
  240. 'ansible_ssh_host': raw_attrs['access_ip_v4'],
  241. 'publicly_routable': True,
  242. })
  243. except (KeyError, ValueError):
  244. attrs.update({'ansible_ssh_host': '', 'publicly_routable': False})
  245. # Handling of floating IPs has changed: https://github.com/terraform-providers/terraform-provider-openstack/blob/master/CHANGELOG.md#010-june-21-2017
  246. # attrs specific to Ansible
  247. if 'metadata.ssh_user' in raw_attrs:
  248. attrs['ansible_ssh_user'] = raw_attrs['metadata.ssh_user']
  249. if 'volume.#' in list(raw_attrs.keys()) and int(raw_attrs['volume.#']) > 0:
  250. device_index = 1
  251. for key, value in list(raw_attrs.items()):
  252. match = re.search("^volume.*.device$", key)
  253. if match:
  254. attrs['disk_volume_device_'+str(device_index)] = value
  255. device_index += 1
  256. # attrs specific to Mantl
  257. attrs.update({
  258. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  259. 'role': attrs['metadata'].get('role', 'none'),
  260. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  261. })
  262. # add groups based on attrs
  263. groups.append('os_image=' + attrs['image']['name'])
  264. groups.append('os_flavor=' + attrs['flavor']['name'])
  265. groups.extend('os_metadata_%s=%s' % item
  266. for item in list(attrs['metadata'].items()))
  267. groups.append('os_region=' + attrs['region'])
  268. # groups specific to Mantl
  269. groups.append('role=' + attrs['metadata'].get('role', 'none'))
  270. groups.append('dc=' + attrs['consul_dc'])
  271. # groups specific to kubespray
  272. for group in attrs['metadata'].get('kubespray_groups', "").split(","):
  273. groups.append(group)
  274. return name, attrs, groups
  275. def iter_host_ips(hosts, ips):
  276. '''Update hosts that have an entry in the floating IP list'''
  277. for host in hosts:
  278. host_id = host[1]['id']
  279. use_access_ip = host[1]['metadata']['use_access_ip']
  280. if host_id in ips:
  281. ip = ips[host_id]
  282. host[1].update({
  283. 'access_ip_v4': ip,
  284. 'access_ip': ip,
  285. 'public_ipv4': ip,
  286. 'ansible_ssh_host': ip,
  287. })
  288. if use_access_ip == "0":
  289. host[1].pop('access_ip')
  290. yield host
  291. ## QUERY TYPES
  292. def query_host(hosts, target):
  293. for name, attrs, _ in hosts:
  294. if name == target:
  295. return attrs
  296. return {}
  297. def query_list(hosts):
  298. groups = defaultdict(dict)
  299. meta = {}
  300. for name, attrs, hostgroups in hosts:
  301. for group in set(hostgroups):
  302. # Ansible 2.6.2 stopped supporting empty group names: https://github.com/ansible/ansible/pull/42584/commits/d4cd474b42ed23d8f8aabb2a7f84699673852eaf
  303. # Empty group name defaults to "all" in Ansible < 2.6.2 so we alter empty group names to "all"
  304. if not group: group = "all"
  305. groups[group].setdefault('hosts', [])
  306. groups[group]['hosts'].append(name)
  307. meta[name] = attrs
  308. groups['_meta'] = {'hostvars': meta}
  309. return groups
  310. def query_hostfile(hosts):
  311. out = ['## begin hosts generated by terraform.py ##']
  312. out.extend(
  313. '{}\t{}'.format(attrs['ansible_ssh_host'].ljust(16), name)
  314. for name, attrs, _ in hosts
  315. )
  316. out.append('## end hosts generated by terraform.py ##')
  317. return '\n'.join(out)
  318. def main():
  319. parser = argparse.ArgumentParser(
  320. __file__, __doc__,
  321. formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
  322. modes = parser.add_mutually_exclusive_group(required=True)
  323. modes.add_argument('--list',
  324. action='store_true',
  325. help='list all variables')
  326. modes.add_argument('--host', help='list variables for a single host')
  327. modes.add_argument('--version',
  328. action='store_true',
  329. help='print version and exit')
  330. modes.add_argument('--hostfile',
  331. action='store_true',
  332. help='print hosts as a /etc/hosts snippet')
  333. parser.add_argument('--pretty',
  334. action='store_true',
  335. help='pretty-print output JSON')
  336. parser.add_argument('--nometa',
  337. action='store_true',
  338. help='with --list, exclude hostvars')
  339. default_root = os.environ.get('TERRAFORM_STATE_ROOT',
  340. os.path.abspath(os.path.join(os.path.dirname(__file__),
  341. '..', '..', )))
  342. parser.add_argument('--root',
  343. default=default_root,
  344. help='custom root to search for `.tfstate`s in')
  345. args = parser.parse_args()
  346. if args.version:
  347. print('%s %s' % (__file__, VERSION))
  348. parser.exit()
  349. hosts = iterhosts(iterresources(tfstates(args.root)))
  350. # Perform a second pass on the file to pick up floating_ip entries to update the ip address of referenced hosts
  351. ips = dict(iterips(iterresources(tfstates(args.root))))
  352. if ips:
  353. hosts = iter_host_ips(hosts, ips)
  354. if args.list:
  355. output = query_list(hosts)
  356. if args.nometa:
  357. del output['_meta']
  358. print(json.dumps(output, indent=4 if args.pretty else None))
  359. elif args.host:
  360. output = query_host(hosts, args.host)
  361. print(json.dumps(output, indent=4 if args.pretty else None))
  362. elif args.hostfile:
  363. output = query_hostfile(hosts)
  364. print(output)
  365. parser.exit()
  366. if __name__ == '__main__':
  367. main()