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.

736 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. 'flavor': parse_dict(raw_attrs, 'flavor',
  250. sep='_'),
  251. 'id': raw_attrs['id'],
  252. 'image': parse_dict(raw_attrs, 'image',
  253. sep='_'),
  254. 'key_pair': raw_attrs['key_pair'],
  255. 'metadata': parse_dict(raw_attrs, 'metadata'),
  256. 'network': parse_attr_list(raw_attrs, 'network'),
  257. 'region': raw_attrs.get('region', ''),
  258. 'security_groups': parse_list(raw_attrs, 'security_groups'),
  259. # ansible
  260. 'ansible_ssh_port': 22,
  261. # workaround for an OpenStack bug where hosts have a different domain
  262. # after they're restarted
  263. 'host_domain': 'novalocal',
  264. 'use_host_domain': True,
  265. # generic
  266. 'public_ipv4': raw_attrs['access_ip_v4'],
  267. 'private_ipv4': raw_attrs['access_ip_v4'],
  268. 'provider': 'openstack',
  269. }
  270. if 'floating_ip' in raw_attrs:
  271. attrs['private_ipv4'] = raw_attrs['network.0.fixed_ip_v4']
  272. try:
  273. attrs.update({
  274. 'ansible_ssh_host': raw_attrs['access_ip_v4'],
  275. 'publicly_routable': True,
  276. })
  277. except (KeyError, ValueError):
  278. attrs.update({'ansible_ssh_host': '', 'publicly_routable': False})
  279. # attrs specific to Ansible
  280. if 'metadata.ssh_user' in raw_attrs:
  281. attrs['ansible_ssh_user'] = raw_attrs['metadata.ssh_user']
  282. # attrs specific to Mantl
  283. attrs.update({
  284. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  285. 'role': attrs['metadata'].get('role', 'none'),
  286. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  287. })
  288. # add groups based on attrs
  289. groups.append('os_image=' + attrs['image']['name'])
  290. groups.append('os_flavor=' + attrs['flavor']['name'])
  291. groups.extend('os_metadata_%s=%s' % item
  292. for item in attrs['metadata'].items())
  293. groups.append('os_region=' + attrs['region'])
  294. # groups specific to Mantl
  295. groups.append('role=' + attrs['metadata'].get('role', 'none'))
  296. groups.append('dc=' + attrs['consul_dc'])
  297. # groups specific to kubespray
  298. for group in attrs['metadata'].get('kubespray_groups', "").split(","):
  299. groups.append(group)
  300. return name, attrs, groups
  301. @parses('aws_instance')
  302. @calculate_mantl_vars
  303. def aws_host(resource, module_name):
  304. name = resource['primary']['attributes']['tags.Name']
  305. raw_attrs = resource['primary']['attributes']
  306. groups = []
  307. attrs = {
  308. 'ami': raw_attrs['ami'],
  309. 'availability_zone': raw_attrs['availability_zone'],
  310. 'ebs_block_device': parse_attr_list(raw_attrs, 'ebs_block_device'),
  311. 'ebs_optimized': parse_bool(raw_attrs['ebs_optimized']),
  312. 'ephemeral_block_device': parse_attr_list(raw_attrs,
  313. 'ephemeral_block_device'),
  314. 'id': raw_attrs['id'],
  315. 'key_name': raw_attrs['key_name'],
  316. 'private': parse_dict(raw_attrs, 'private',
  317. sep='_'),
  318. 'public': parse_dict(raw_attrs, 'public',
  319. sep='_'),
  320. 'root_block_device': parse_attr_list(raw_attrs, 'root_block_device'),
  321. 'security_groups': parse_list(raw_attrs, 'security_groups'),
  322. 'subnet': parse_dict(raw_attrs, 'subnet',
  323. sep='_'),
  324. 'tags': parse_dict(raw_attrs, 'tags'),
  325. 'tenancy': raw_attrs['tenancy'],
  326. 'vpc_security_group_ids': parse_list(raw_attrs,
  327. 'vpc_security_group_ids'),
  328. # ansible-specific
  329. 'ansible_ssh_port': 22,
  330. 'ansible_ssh_host': raw_attrs['public_ip'],
  331. # generic
  332. 'public_ipv4': raw_attrs['public_ip'],
  333. 'private_ipv4': raw_attrs['private_ip'],
  334. 'provider': 'aws',
  335. }
  336. # attrs specific to Ansible
  337. if 'tags.sshUser' in raw_attrs:
  338. attrs['ansible_ssh_user'] = raw_attrs['tags.sshUser']
  339. if 'tags.sshPrivateIp' in raw_attrs:
  340. attrs['ansible_ssh_host'] = raw_attrs['private_ip']
  341. # attrs specific to Mantl
  342. attrs.update({
  343. 'consul_dc': _clean_dc(attrs['tags'].get('dc', module_name)),
  344. 'role': attrs['tags'].get('role', 'none'),
  345. 'ansible_python_interpreter': attrs['tags'].get('python_bin','python')
  346. })
  347. # groups specific to Mantl
  348. groups.extend(['aws_ami=' + attrs['ami'],
  349. 'aws_az=' + attrs['availability_zone'],
  350. 'aws_key_name=' + attrs['key_name'],
  351. 'aws_tenancy=' + attrs['tenancy']])
  352. groups.extend('aws_tag_%s=%s' % item for item in attrs['tags'].items())
  353. groups.extend('aws_vpc_security_group=' + group
  354. for group in attrs['vpc_security_group_ids'])
  355. groups.extend('aws_subnet_%s=%s' % subnet
  356. for subnet in attrs['subnet'].items())
  357. # groups specific to Mantl
  358. groups.append('role=' + attrs['role'])
  359. groups.append('dc=' + attrs['consul_dc'])
  360. return name, attrs, groups
  361. @parses('google_compute_instance')
  362. @calculate_mantl_vars
  363. def gce_host(resource, module_name):
  364. name = resource['primary']['id']
  365. raw_attrs = resource['primary']['attributes']
  366. groups = []
  367. # network interfaces
  368. interfaces = parse_attr_list(raw_attrs, 'network_interface')
  369. for interface in interfaces:
  370. interface['access_config'] = parse_attr_list(interface,
  371. 'access_config')
  372. for key in interface.keys():
  373. if '.' in key:
  374. del interface[key]
  375. # general attrs
  376. attrs = {
  377. 'can_ip_forward': raw_attrs['can_ip_forward'] == 'true',
  378. 'disks': parse_attr_list(raw_attrs, 'disk'),
  379. 'machine_type': raw_attrs['machine_type'],
  380. 'metadata': parse_dict(raw_attrs, 'metadata'),
  381. 'network': parse_attr_list(raw_attrs, 'network'),
  382. 'network_interface': interfaces,
  383. 'self_link': raw_attrs['self_link'],
  384. 'service_account': parse_attr_list(raw_attrs, 'service_account'),
  385. 'tags': parse_list(raw_attrs, 'tags'),
  386. 'zone': raw_attrs['zone'],
  387. # ansible
  388. 'ansible_ssh_port': 22,
  389. 'provider': 'gce',
  390. }
  391. # attrs specific to Ansible
  392. if 'metadata.ssh_user' in raw_attrs:
  393. attrs['ansible_ssh_user'] = raw_attrs['metadata.ssh_user']
  394. # attrs specific to Mantl
  395. attrs.update({
  396. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  397. 'role': attrs['metadata'].get('role', 'none'),
  398. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  399. })
  400. try:
  401. attrs.update({
  402. 'ansible_ssh_host': interfaces[0]['access_config'][0]['nat_ip'] or interfaces[0]['access_config'][0]['assigned_nat_ip'],
  403. 'public_ipv4': interfaces[0]['access_config'][0]['nat_ip'] or interfaces[0]['access_config'][0]['assigned_nat_ip'],
  404. 'private_ipv4': interfaces[0]['address'],
  405. 'publicly_routable': True,
  406. })
  407. except (KeyError, ValueError):
  408. attrs.update({'ansible_ssh_host': '', 'publicly_routable': False})
  409. # add groups based on attrs
  410. groups.extend('gce_image=' + disk['image'] for disk in attrs['disks'])
  411. groups.append('gce_machine_type=' + attrs['machine_type'])
  412. groups.extend('gce_metadata_%s=%s' % (key, value)
  413. for (key, value) in attrs['metadata'].items()
  414. if key not in set(['sshKeys']))
  415. groups.extend('gce_tag=' + tag for tag in attrs['tags'])
  416. groups.append('gce_zone=' + attrs['zone'])
  417. if attrs['can_ip_forward']:
  418. groups.append('gce_ip_forward')
  419. if attrs['publicly_routable']:
  420. groups.append('gce_publicly_routable')
  421. # groups specific to Mantl
  422. groups.append('role=' + attrs['metadata'].get('role', 'none'))
  423. groups.append('dc=' + attrs['consul_dc'])
  424. return name, attrs, groups
  425. @parses('vsphere_virtual_machine')
  426. @calculate_mantl_vars
  427. def vsphere_host(resource, module_name):
  428. raw_attrs = resource['primary']['attributes']
  429. network_attrs = parse_dict(raw_attrs, 'network_interface')
  430. network = parse_dict(network_attrs, '0')
  431. ip_address = network.get('ipv4_address', network['ip_address'])
  432. name = raw_attrs['name']
  433. groups = []
  434. attrs = {
  435. 'id': raw_attrs['id'],
  436. 'ip_address': ip_address,
  437. 'private_ipv4': ip_address,
  438. 'public_ipv4': ip_address,
  439. 'metadata': parse_dict(raw_attrs, 'custom_configuration_parameters'),
  440. 'ansible_ssh_port': 22,
  441. 'provider': 'vsphere',
  442. }
  443. try:
  444. attrs.update({
  445. 'ansible_ssh_host': ip_address,
  446. })
  447. except (KeyError, ValueError):
  448. attrs.update({'ansible_ssh_host': '', })
  449. attrs.update({
  450. 'consul_dc': _clean_dc(attrs['metadata'].get('consul_dc', module_name)),
  451. 'role': attrs['metadata'].get('role', 'none'),
  452. 'ansible_python_interpreter': attrs['metadata'].get('python_bin','python')
  453. })
  454. # attrs specific to Ansible
  455. if 'ssh_user' in attrs['metadata']:
  456. attrs['ansible_ssh_user'] = attrs['metadata']['ssh_user']
  457. groups.append('role=' + attrs['role'])
  458. groups.append('dc=' + attrs['consul_dc'])
  459. return name, attrs, groups
  460. @parses('azure_instance')
  461. @calculate_mantl_vars
  462. def azure_host(resource, module_name):
  463. name = resource['primary']['attributes']['name']
  464. raw_attrs = resource['primary']['attributes']
  465. groups = []
  466. attrs = {
  467. 'automatic_updates': raw_attrs['automatic_updates'],
  468. 'description': raw_attrs['description'],
  469. 'hosted_service_name': raw_attrs['hosted_service_name'],
  470. 'id': raw_attrs['id'],
  471. 'image': raw_attrs['image'],
  472. 'ip_address': raw_attrs['ip_address'],
  473. 'location': raw_attrs['location'],
  474. 'name': raw_attrs['name'],
  475. 'reverse_dns': raw_attrs['reverse_dns'],
  476. 'security_group': raw_attrs['security_group'],
  477. 'size': raw_attrs['size'],
  478. 'ssh_key_thumbprint': raw_attrs['ssh_key_thumbprint'],
  479. 'subnet': raw_attrs['subnet'],
  480. 'username': raw_attrs['username'],
  481. 'vip_address': raw_attrs['vip_address'],
  482. 'virtual_network': raw_attrs['virtual_network'],
  483. 'endpoint': parse_attr_list(raw_attrs, 'endpoint'),
  484. # ansible
  485. 'ansible_ssh_port': 22,
  486. 'ansible_ssh_user': raw_attrs['username'],
  487. 'ansible_ssh_host': raw_attrs['vip_address'],
  488. }
  489. # attrs specific to mantl
  490. attrs.update({
  491. 'consul_dc': attrs['location'].lower().replace(" ", "-"),
  492. 'role': attrs['description']
  493. })
  494. # groups specific to mantl
  495. groups.extend(['azure_image=' + attrs['image'],
  496. 'azure_location=' + attrs['location'].lower().replace(" ", "-"),
  497. 'azure_username=' + attrs['username'],
  498. 'azure_security_group=' + attrs['security_group']])
  499. # groups specific to mantl
  500. groups.append('role=' + attrs['role'])
  501. groups.append('dc=' + attrs['consul_dc'])
  502. return name, attrs, groups
  503. @parses('clc_server')
  504. @calculate_mantl_vars
  505. def clc_server(resource, module_name):
  506. raw_attrs = resource['primary']['attributes']
  507. name = raw_attrs.get('id')
  508. groups = []
  509. md = parse_dict(raw_attrs, 'metadata')
  510. attrs = {
  511. 'metadata': md,
  512. 'ansible_ssh_port': md.get('ssh_port', 22),
  513. 'ansible_ssh_user': md.get('ssh_user', 'root'),
  514. 'provider': 'clc',
  515. 'publicly_routable': False,
  516. }
  517. try:
  518. attrs.update({
  519. 'public_ipv4': raw_attrs['public_ip_address'],
  520. 'private_ipv4': raw_attrs['private_ip_address'],
  521. 'ansible_ssh_host': raw_attrs['public_ip_address'],
  522. 'publicly_routable': True,
  523. })
  524. except (KeyError, ValueError):
  525. attrs.update({
  526. 'ansible_ssh_host': raw_attrs['private_ip_address'],
  527. 'private_ipv4': raw_attrs['private_ip_address'],
  528. })
  529. attrs.update({
  530. 'consul_dc': _clean_dc(attrs['metadata'].get('dc', module_name)),
  531. 'role': attrs['metadata'].get('role', 'none'),
  532. })
  533. groups.append('role=' + attrs['role'])
  534. groups.append('dc=' + attrs['consul_dc'])
  535. return name, attrs, groups
  536. ## QUERY TYPES
  537. def query_host(hosts, target):
  538. for name, attrs, _ in hosts:
  539. if name == target:
  540. return attrs
  541. return {}
  542. def query_list(hosts):
  543. groups = defaultdict(dict)
  544. meta = {}
  545. for name, attrs, hostgroups in hosts:
  546. for group in set(hostgroups):
  547. groups[group].setdefault('hosts', [])
  548. groups[group]['hosts'].append(name)
  549. meta[name] = attrs
  550. groups['_meta'] = {'hostvars': meta}
  551. return groups
  552. def query_hostfile(hosts):
  553. out = ['## begin hosts generated by terraform.py ##']
  554. out.extend(
  555. '{}\t{}'.format(attrs['ansible_ssh_host'].ljust(16), name)
  556. for name, attrs, _ in hosts
  557. )
  558. out.append('## end hosts generated by terraform.py ##')
  559. return '\n'.join(out)
  560. def main():
  561. parser = argparse.ArgumentParser(
  562. __file__, __doc__,
  563. formatter_class=argparse.ArgumentDefaultsHelpFormatter, )
  564. modes = parser.add_mutually_exclusive_group(required=True)
  565. modes.add_argument('--list',
  566. action='store_true',
  567. help='list all variables')
  568. modes.add_argument('--host', help='list variables for a single host')
  569. modes.add_argument('--version',
  570. action='store_true',
  571. help='print version and exit')
  572. modes.add_argument('--hostfile',
  573. action='store_true',
  574. help='print hosts as a /etc/hosts snippet')
  575. parser.add_argument('--pretty',
  576. action='store_true',
  577. help='pretty-print output JSON')
  578. parser.add_argument('--nometa',
  579. action='store_true',
  580. help='with --list, exclude hostvars')
  581. default_root = os.environ.get('TERRAFORM_STATE_ROOT',
  582. os.path.abspath(os.path.join(os.path.dirname(__file__),
  583. '..', '..', )))
  584. parser.add_argument('--root',
  585. default=default_root,
  586. help='custom root to search for `.tfstate`s in')
  587. args = parser.parse_args()
  588. if args.version:
  589. print('%s %s' % (__file__, VERSION))
  590. parser.exit()
  591. hosts = iterhosts(iterresources(tfstates(args.root)))
  592. if args.list:
  593. output = query_list(hosts)
  594. if args.nometa:
  595. del output['_meta']
  596. print(json.dumps(output, indent=4 if args.pretty else None))
  597. elif args.host:
  598. output = query_host(hosts, args.host)
  599. print(json.dumps(output, indent=4 if args.pretty else None))
  600. elif args.hostfile:
  601. output = query_hostfile(hosts)
  602. print(output)
  603. parser.exit()
  604. if __name__ == '__main__':
  605. main()