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.

737 lines
24 KiB

  1. #!/usr/bin/env python
  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 parses(prefix):
  60. def inner(func):
  61. PARSERS[prefix] = func
  62. return func
  63. return inner
  64. def calculate_mantl_vars(func):
  65. """calculate Mantl vars"""
  66. @wraps(func)
  67. def inner(*args, **kwargs):
  68. name, attrs, groups = func(*args, **kwargs)
  69. # attrs
  70. if attrs.get('role', '') == 'control':
  71. attrs['consul_is_server'] = True
  72. else:
  73. attrs['consul_is_server'] = False
  74. # groups
  75. if attrs.get('publicly_routable', False):
  76. groups.append('publicly_routable')
  77. return name, attrs, groups
  78. return inner
  79. def _parse_prefix(source, prefix, sep='.'):
  80. for compkey, value in source.items():
  81. try:
  82. curprefix, rest = compkey.split(sep, 1)
  83. except ValueError:
  84. continue
  85. if curprefix != prefix or rest == '#':
  86. continue
  87. yield rest, value
  88. def parse_attr_list(source, prefix, sep='.'):
  89. attrs = defaultdict(dict)
  90. for compkey, value in _parse_prefix(source, prefix, sep):
  91. idx, key = compkey.split(sep, 1)
  92. attrs[idx][key] = value
  93. return attrs.values()
  94. def parse_dict(source, prefix, sep='.'):
  95. return dict(_parse_prefix(source, prefix, sep))
  96. def parse_list(source, prefix, sep='.'):
  97. return [value for _, value in _parse_prefix(source, prefix, sep)]
  98. def parse_bool(string_form):
  99. token = string_form.lower()[0]
  100. if token == 't':
  101. return True
  102. elif token == 'f':
  103. return False
  104. else:
  105. raise ValueError('could not convert %r to a bool' % string_form)
  106. @parses('triton_machine')
  107. @calculate_mantl_vars
  108. def triton_machine(resource, module_name):
  109. raw_attrs = resource['primary']['attributes']
  110. name = raw_attrs.get('name')
  111. groups = []
  112. attrs = {
  113. 'id': raw_attrs['id'],
  114. 'dataset': raw_attrs['dataset'],
  115. 'disk': raw_attrs['disk'],
  116. 'firewall_enabled': parse_bool(raw_attrs['firewall_enabled']),
  117. 'image': raw_attrs['image'],
  118. 'ips': parse_list(raw_attrs, 'ips'),
  119. 'memory': raw_attrs['memory'],
  120. 'name': raw_attrs['name'],
  121. 'networks': parse_list(raw_attrs, 'networks'),
  122. 'package': raw_attrs['package'],
  123. 'primary_ip': raw_attrs['primaryip'],
  124. 'root_authorized_keys': raw_attrs['root_authorized_keys'],
  125. 'state': raw_attrs['state'],
  126. 'tags': parse_dict(raw_attrs, 'tags'),
  127. 'type': raw_attrs['type'],
  128. 'user_data': raw_attrs['user_data'],
  129. 'user_script': raw_attrs['user_script'],
  130. # ansible
  131. 'ansible_ssh_host': raw_attrs['primaryip'],
  132. 'ansible_ssh_port': 22,
  133. 'ansible_ssh_user': 'root', # it's "root" on Triton by default
  134. # generic
  135. 'public_ipv4': raw_attrs['primaryip'],
  136. 'provider': 'triton',
  137. }
  138. # private IPv4
  139. for ip in attrs['ips']:
  140. if ip.startswith('10') or ip.startswith('192.168'): # private IPs
  141. attrs['private_ipv4'] = ip
  142. break
  143. if 'private_ipv4' not in attrs:
  144. attrs['private_ipv4'] = attrs['public_ipv4']
  145. # attrs specific to Mantl
  146. attrs.update({
  147. 'consul_dc': _clean_dc(attrs['tags'].get('dc', 'none')),
  148. 'role': attrs['tags'].get('role', 'none'),
  149. 'ansible_python_interpreter': attrs['tags'].get('python_bin', 'python')
  150. })
  151. # add groups based on attrs
  152. groups.append('triton_image=' + attrs['image'])
  153. groups.append('triton_package=' + attrs['package'])
  154. groups.append('triton_state=' + attrs['state'])
  155. groups.append('triton_firewall_enabled=%s' % attrs['firewall_enabled'])
  156. groups.extend('triton_tags_%s=%s' % item
  157. for item in attrs['tags'].items())
  158. groups.extend('triton_network=' + network
  159. for network in attrs['networks'])
  160. # groups specific to Mantl
  161. groups.append('role=' + attrs['role'])
  162. groups.append('dc=' + attrs['consul_dc'])
  163. return name, attrs, groups
  164. @parses('digitalocean_droplet')
  165. @calculate_mantl_vars
  166. def digitalocean_host(resource, tfvars=None):
  167. raw_attrs = resource['primary']['attributes']
  168. name = raw_attrs['name']
  169. groups = []
  170. attrs = {
  171. 'id': raw_attrs['id'],
  172. 'image': raw_attrs['image'],
  173. 'ipv4_address': raw_attrs['ipv4_address'],
  174. 'locked': parse_bool(raw_attrs['locked']),
  175. 'metadata': json.loads(raw_attrs.get('user_data', '{}')),
  176. 'region': raw_attrs['region'],
  177. 'size': raw_attrs['size'],
  178. 'ssh_keys': parse_list(raw_attrs, 'ssh_keys'),
  179. 'status': raw_attrs['status'],
  180. # ansible
  181. 'ansible_ssh_host': raw_attrs['ipv4_address'],
  182. 'ansible_ssh_port': 22,
  183. 'ansible_ssh_user': 'root', # it's always "root" on DO
  184. # generic
  185. 'public_ipv4': raw_attrs['ipv4_address'],
  186. 'private_ipv4': raw_attrs.get('ipv4_address_private',
  187. raw_attrs['ipv4_address']),
  188. 'provider': 'digitalocean',
  189. }
  190. # attrs specific to Mantl
  191. attrs.update({
  192. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', attrs['region'])),
  193. 'role': attrs['metadata'].get('role', 'none'),
  194. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  195. })
  196. # add groups based on attrs
  197. groups.append('do_image=' + attrs['image'])
  198. groups.append('do_locked=%s' % attrs['locked'])
  199. groups.append('do_region=' + attrs['region'])
  200. groups.append('do_size=' + attrs['size'])
  201. groups.append('do_status=' + attrs['status'])
  202. groups.extend('do_metadata_%s=%s' % item
  203. for item in attrs['metadata'].items())
  204. # groups specific to Mantl
  205. groups.append('role=' + attrs['role'])
  206. groups.append('dc=' + attrs['consul_dc'])
  207. return name, attrs, groups
  208. @parses('softlayer_virtualserver')
  209. @calculate_mantl_vars
  210. def softlayer_host(resource, module_name):
  211. raw_attrs = resource['primary']['attributes']
  212. name = raw_attrs['name']
  213. groups = []
  214. attrs = {
  215. 'id': raw_attrs['id'],
  216. 'image': raw_attrs['image'],
  217. 'ipv4_address': raw_attrs['ipv4_address'],
  218. 'metadata': json.loads(raw_attrs.get('user_data', '{}')),
  219. 'region': raw_attrs['region'],
  220. 'ram': raw_attrs['ram'],
  221. 'cpu': raw_attrs['cpu'],
  222. 'ssh_keys': parse_list(raw_attrs, 'ssh_keys'),
  223. 'public_ipv4': raw_attrs['ipv4_address'],
  224. 'private_ipv4': raw_attrs['ipv4_address_private'],
  225. 'ansible_ssh_host': raw_attrs['ipv4_address'],
  226. 'ansible_ssh_port': 22,
  227. 'ansible_ssh_user': 'root',
  228. 'provider': 'softlayer',
  229. }
  230. # attrs specific to Mantl
  231. attrs.update({
  232. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', attrs['region'])),
  233. 'role': attrs['metadata'].get('role', 'none'),
  234. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  235. })
  236. # groups specific to Mantl
  237. groups.append('role=' + attrs['role'])
  238. groups.append('dc=' + attrs['consul_dc'])
  239. return name, attrs, groups
  240. @parses('openstack_compute_instance_v2')
  241. @calculate_mantl_vars
  242. def openstack_host(resource, module_name):
  243. raw_attrs = resource['primary']['attributes']
  244. name = raw_attrs['name']
  245. groups = []
  246. attrs = {
  247. 'access_ip_v4': raw_attrs['access_ip_v4'],
  248. 'access_ip_v6': raw_attrs['access_ip_v6'],
  249. 'ip': raw_attrs['network.0.fixed_ip_v4'],
  250. 'flavor': parse_dict(raw_attrs, 'flavor',
  251. sep='_'),
  252. 'id': raw_attrs['id'],
  253. 'image': parse_dict(raw_attrs, 'image',
  254. sep='_'),
  255. 'key_pair': raw_attrs['key_pair'],
  256. 'metadata': parse_dict(raw_attrs, 'metadata'),
  257. 'network': parse_attr_list(raw_attrs, 'network'),
  258. 'region': raw_attrs.get('region', ''),
  259. 'security_groups': parse_list(raw_attrs, 'security_groups'),
  260. # ansible
  261. 'ansible_ssh_port': 22,
  262. # workaround for an OpenStack bug where hosts have a different domain
  263. # after they're restarted
  264. 'host_domain': 'novalocal',
  265. 'use_host_domain': True,
  266. # generic
  267. 'public_ipv4': raw_attrs['access_ip_v4'],
  268. 'private_ipv4': raw_attrs['access_ip_v4'],
  269. 'provider': 'openstack',
  270. }
  271. if 'floating_ip' in raw_attrs:
  272. attrs['private_ipv4'] = raw_attrs['network.0.fixed_ip_v4']
  273. try:
  274. attrs.update({
  275. 'ansible_ssh_host': raw_attrs['access_ip_v4'],
  276. 'publicly_routable': True,
  277. })
  278. except (KeyError, ValueError):
  279. attrs.update({'ansible_ssh_host': '', 'publicly_routable': False})
  280. # attrs specific to Ansible
  281. if 'metadata.ssh_user' in raw_attrs:
  282. attrs['ansible_ssh_user'] = raw_attrs['metadata.ssh_user']
  283. # attrs specific to Mantl
  284. attrs.update({
  285. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  286. 'role': attrs['metadata'].get('role', 'none'),
  287. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  288. })
  289. # add groups based on attrs
  290. groups.append('os_image=' + attrs['image']['name'])
  291. groups.append('os_flavor=' + attrs['flavor']['name'])
  292. groups.extend('os_metadata_%s=%s' % item
  293. for item in attrs['metadata'].items())
  294. groups.append('os_region=' + attrs['region'])
  295. # groups specific to Mantl
  296. groups.append('role=' + attrs['metadata'].get('role', 'none'))
  297. groups.append('dc=' + attrs['consul_dc'])
  298. # groups specific to kubespray
  299. for group in attrs['metadata'].get('kubespray_groups', "").split(","):
  300. groups.append(group)
  301. return name, attrs, groups
  302. @parses('aws_instance')
  303. @calculate_mantl_vars
  304. def aws_host(resource, module_name):
  305. name = resource['primary']['attributes']['tags.Name']
  306. raw_attrs = resource['primary']['attributes']
  307. groups = []
  308. attrs = {
  309. 'ami': raw_attrs['ami'],
  310. 'availability_zone': raw_attrs['availability_zone'],
  311. 'ebs_block_device': parse_attr_list(raw_attrs, 'ebs_block_device'),
  312. 'ebs_optimized': parse_bool(raw_attrs['ebs_optimized']),
  313. 'ephemeral_block_device': parse_attr_list(raw_attrs,
  314. 'ephemeral_block_device'),
  315. 'id': raw_attrs['id'],
  316. 'key_name': raw_attrs['key_name'],
  317. 'private': parse_dict(raw_attrs, 'private',
  318. sep='_'),
  319. 'public': parse_dict(raw_attrs, 'public',
  320. sep='_'),
  321. 'root_block_device': parse_attr_list(raw_attrs, 'root_block_device'),
  322. 'security_groups': parse_list(raw_attrs, 'security_groups'),
  323. 'subnet': parse_dict(raw_attrs, 'subnet',
  324. sep='_'),
  325. 'tags': parse_dict(raw_attrs, 'tags'),
  326. 'tenancy': raw_attrs['tenancy'],
  327. 'vpc_security_group_ids': parse_list(raw_attrs,
  328. 'vpc_security_group_ids'),
  329. # ansible-specific
  330. 'ansible_ssh_port': 22,
  331. 'ansible_ssh_host': raw_attrs['public_ip'],
  332. # generic
  333. 'public_ipv4': raw_attrs['public_ip'],
  334. 'private_ipv4': raw_attrs['private_ip'],
  335. 'provider': 'aws',
  336. }
  337. # attrs specific to Ansible
  338. if 'tags.sshUser' in raw_attrs:
  339. attrs['ansible_ssh_user'] = raw_attrs['tags.sshUser']
  340. if 'tags.sshPrivateIp' in raw_attrs:
  341. attrs['ansible_ssh_host'] = raw_attrs['private_ip']
  342. # attrs specific to Mantl
  343. attrs.update({
  344. 'consul_dc': _clean_dc(attrs['tags'].get('dc', module_name)),
  345. 'role': attrs['tags'].get('role', 'none'),
  346. 'ansible_python_interpreter': attrs['tags'].get('python_bin','python')
  347. })
  348. # groups specific to Mantl
  349. groups.extend(['aws_ami=' + attrs['ami'],
  350. 'aws_az=' + attrs['availability_zone'],
  351. 'aws_key_name=' + attrs['key_name'],
  352. 'aws_tenancy=' + attrs['tenancy']])
  353. groups.extend('aws_tag_%s=%s' % item for item in attrs['tags'].items())
  354. groups.extend('aws_vpc_security_group=' + group
  355. for group in attrs['vpc_security_group_ids'])
  356. groups.extend('aws_subnet_%s=%s' % subnet
  357. for subnet in attrs['subnet'].items())
  358. # groups specific to Mantl
  359. groups.append('role=' + attrs['role'])
  360. groups.append('dc=' + attrs['consul_dc'])
  361. return name, attrs, groups
  362. @parses('google_compute_instance')
  363. @calculate_mantl_vars
  364. def gce_host(resource, module_name):
  365. name = resource['primary']['id']
  366. raw_attrs = resource['primary']['attributes']
  367. groups = []
  368. # network interfaces
  369. interfaces = parse_attr_list(raw_attrs, 'network_interface')
  370. for interface in interfaces:
  371. interface['access_config'] = parse_attr_list(interface,
  372. 'access_config')
  373. for key in interface.keys():
  374. if '.' in key:
  375. del interface[key]
  376. # general attrs
  377. attrs = {
  378. 'can_ip_forward': raw_attrs['can_ip_forward'] == 'true',
  379. 'disks': parse_attr_list(raw_attrs, 'disk'),
  380. 'machine_type': raw_attrs['machine_type'],
  381. 'metadata': parse_dict(raw_attrs, 'metadata'),
  382. 'network': parse_attr_list(raw_attrs, 'network'),
  383. 'network_interface': interfaces,
  384. 'self_link': raw_attrs['self_link'],
  385. 'service_account': parse_attr_list(raw_attrs, 'service_account'),
  386. 'tags': parse_list(raw_attrs, 'tags'),
  387. 'zone': raw_attrs['zone'],
  388. # ansible
  389. 'ansible_ssh_port': 22,
  390. 'provider': 'gce',
  391. }
  392. # attrs specific to Ansible
  393. if 'metadata.ssh_user' in raw_attrs:
  394. attrs['ansible_ssh_user'] = raw_attrs['metadata.ssh_user']
  395. # attrs specific to Mantl
  396. attrs.update({
  397. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  398. 'role': attrs['metadata'].get('role', 'none'),
  399. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  400. })
  401. try:
  402. attrs.update({
  403. 'ansible_ssh_host': interfaces[0]['access_config'][0]['nat_ip'] or interfaces[0]['access_config'][0]['assigned_nat_ip'],
  404. 'public_ipv4': interfaces[0]['access_config'][0]['nat_ip'] or interfaces[0]['access_config'][0]['assigned_nat_ip'],
  405. 'private_ipv4': interfaces[0]['address'],
  406. 'publicly_routable': True,
  407. })
  408. except (KeyError, ValueError):
  409. attrs.update({'ansible_ssh_host': '', 'publicly_routable': False})
  410. # add groups based on attrs
  411. groups.extend('gce_image=' + disk['image'] for disk in attrs['disks'])
  412. groups.append('gce_machine_type=' + attrs['machine_type'])
  413. groups.extend('gce_metadata_%s=%s' % (key, value)
  414. for (key, value) in attrs['metadata'].items()
  415. if key not in set(['sshKeys']))
  416. groups.extend('gce_tag=' + tag for tag in attrs['tags'])
  417. groups.append('gce_zone=' + attrs['zone'])
  418. if attrs['can_ip_forward']:
  419. groups.append('gce_ip_forward')
  420. if attrs['publicly_routable']:
  421. groups.append('gce_publicly_routable')
  422. # groups specific to Mantl
  423. groups.append('role=' + attrs['metadata'].get('role', 'none'))
  424. groups.append('dc=' + attrs['consul_dc'])
  425. return name, attrs, groups
  426. @parses('vsphere_virtual_machine')
  427. @calculate_mantl_vars
  428. def vsphere_host(resource, module_name):
  429. raw_attrs = resource['primary']['attributes']
  430. network_attrs = parse_dict(raw_attrs, 'network_interface')
  431. network = parse_dict(network_attrs, '0')
  432. ip_address = network.get('ipv4_address', network['ip_address'])
  433. name = raw_attrs['name']
  434. groups = []
  435. attrs = {
  436. 'id': raw_attrs['id'],
  437. 'ip_address': ip_address,
  438. 'private_ipv4': ip_address,
  439. 'public_ipv4': ip_address,
  440. 'metadata': parse_dict(raw_attrs, 'custom_configuration_parameters'),
  441. 'ansible_ssh_port': 22,
  442. 'provider': 'vsphere',
  443. }
  444. try:
  445. attrs.update({
  446. 'ansible_ssh_host': ip_address,
  447. })
  448. except (KeyError, ValueError):
  449. attrs.update({'ansible_ssh_host': '', })
  450. attrs.update({
  451. 'consul_dc': _clean_dc(attrs['metadata'].get('consul_dc', module_name)),
  452. 'role': attrs['metadata'].get('role', 'none'),
  453. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  454. })
  455. # attrs specific to Ansible
  456. if 'ssh_user' in attrs['metadata']:
  457. attrs['ansible_ssh_user'] = attrs['metadata']['ssh_user']
  458. groups.append('role=' + attrs['role'])
  459. groups.append('dc=' + attrs['consul_dc'])
  460. return name, attrs, groups
  461. @parses('azure_instance')
  462. @calculate_mantl_vars
  463. def azure_host(resource, module_name):
  464. name = resource['primary']['attributes']['name']
  465. raw_attrs = resource['primary']['attributes']
  466. groups = []
  467. attrs = {
  468. 'automatic_updates': raw_attrs['automatic_updates'],
  469. 'description': raw_attrs['description'],
  470. 'hosted_service_name': raw_attrs['hosted_service_name'],
  471. 'id': raw_attrs['id'],
  472. 'image': raw_attrs['image'],
  473. 'ip_address': raw_attrs['ip_address'],
  474. 'location': raw_attrs['location'],
  475. 'name': raw_attrs['name'],
  476. 'reverse_dns': raw_attrs['reverse_dns'],
  477. 'security_group': raw_attrs['security_group'],
  478. 'size': raw_attrs['size'],
  479. 'ssh_key_thumbprint': raw_attrs['ssh_key_thumbprint'],
  480. 'subnet': raw_attrs['subnet'],
  481. 'username': raw_attrs['username'],
  482. 'vip_address': raw_attrs['vip_address'],
  483. 'virtual_network': raw_attrs['virtual_network'],
  484. 'endpoint': parse_attr_list(raw_attrs, 'endpoint'),
  485. # ansible
  486. 'ansible_ssh_port': 22,
  487. 'ansible_ssh_user': raw_attrs['username'],
  488. 'ansible_ssh_host': raw_attrs['vip_address'],
  489. }
  490. # attrs specific to mantl
  491. attrs.update({
  492. 'consul_dc': attrs['location'].lower().replace(" ", "-"),
  493. 'role': attrs['description']
  494. })
  495. # groups specific to mantl
  496. groups.extend(['azure_image=' + attrs['image'],
  497. 'azure_location=' + attrs['location'].lower().replace(" ", "-"),
  498. 'azure_username=' + attrs['username'],
  499. 'azure_security_group=' + attrs['security_group']])
  500. # groups specific to mantl
  501. groups.append('role=' + attrs['role'])
  502. groups.append('dc=' + attrs['consul_dc'])
  503. return name, attrs, groups
  504. @parses('clc_server')
  505. @calculate_mantl_vars
  506. def clc_server(resource, module_name):
  507. raw_attrs = resource['primary']['attributes']
  508. name = raw_attrs.get('id')
  509. groups = []
  510. md = parse_dict(raw_attrs, 'metadata')
  511. attrs = {
  512. 'metadata': md,
  513. 'ansible_ssh_port': md.get('ssh_port', 22),
  514. 'ansible_ssh_user': md.get('ssh_user', 'root'),
  515. 'provider': 'clc',
  516. 'publicly_routable': False,
  517. }
  518. try:
  519. attrs.update({
  520. 'public_ipv4': raw_attrs['public_ip_address'],
  521. 'private_ipv4': raw_attrs['private_ip_address'],
  522. 'ansible_ssh_host': raw_attrs['public_ip_address'],
  523. 'publicly_routable': True,
  524. })
  525. except (KeyError, ValueError):
  526. attrs.update({
  527. 'ansible_ssh_host': raw_attrs['private_ip_address'],
  528. 'private_ipv4': raw_attrs['private_ip_address'],
  529. })
  530. attrs.update({
  531. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  532. 'role': attrs['metadata'].get('role', 'none'),
  533. })
  534. groups.append('role=' + attrs['role'])
  535. groups.append('dc=' + attrs['consul_dc'])
  536. return name, attrs, groups
  537. ## QUERY TYPES
  538. def query_host(hosts, target):
  539. for name, attrs, _ in hosts:
  540. if name == target:
  541. return attrs
  542. return {}
  543. def query_list(hosts):
  544. groups = defaultdict(dict)
  545. meta = {}
  546. for name, attrs, hostgroups in hosts:
  547. for group in set(hostgroups):
  548. groups[group].setdefault('hosts', [])
  549. groups[group]['hosts'].append(name)
  550. meta[name] = attrs
  551. groups['_meta'] = {'hostvars': meta}
  552. return groups
  553. def query_hostfile(hosts):
  554. out = ['## begin hosts generated by terraform.py ##']
  555. out.extend(
  556. '{}\t{}'.format(attrs['ansible_ssh_host'].ljust(16), name)
  557. for name, attrs, _ in hosts
  558. )
  559. out.append('## end hosts generated by terraform.py ##')
  560. return '\n'.join(out)
  561. def main():
  562. parser = argparse.ArgumentParser(
  563. __file__, __doc__,
  564. formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
  565. modes = parser.add_mutually_exclusive_group(required=True)
  566. modes.add_argument('--list',
  567. action='store_true',
  568. help='list all variables')
  569. modes.add_argument('--host', help='list variables for a single host')
  570. modes.add_argument('--version',
  571. action='store_true',
  572. help='print version and exit')
  573. modes.add_argument('--hostfile',
  574. action='store_true',
  575. help='print hosts as a /etc/hosts snippet')
  576. parser.add_argument('--pretty',
  577. action='store_true',
  578. help='pretty-print output JSON')
  579. parser.add_argument('--nometa',
  580. action='store_true',
  581. help='with --list, exclude hostvars')
  582. default_root = os.environ.get('TERRAFORM_STATE_ROOT',
  583. os.path.abspath(os.path.join(os.path.dirname(__file__),
  584. '..', '..', )))
  585. parser.add_argument('--root',
  586. default=default_root,
  587. help='custom root to search for `.tfstate`s in')
  588. args = parser.parse_args()
  589. if args.version:
  590. print('%s %s' % (__file__, VERSION))
  591. parser.exit()
  592. hosts = iterhosts(iterresources(tfstates(args.root)))
  593. if args.list:
  594. output = query_list(hosts)
  595. if args.nometa:
  596. del output['_meta']
  597. print(json.dumps(output, indent=4 if args.pretty else None))
  598. elif args.host:
  599. output = query_host(hosts, args.host)
  600. print(json.dumps(output, indent=4 if args.pretty else None))
  601. elif args.hostfile:
  602. output = query_hostfile(hosts)
  603. print(output)
  604. parser.exit()
  605. if __name__ == '__main__':
  606. main()