Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.02 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3. #####
  4. #
  5. # Description
  6. # -----------
  7. #
  8. # This is an Ansible dynamic inventory script that reads any Ansible hosts file
  9. # and transforms it into the JSON data structure.
  10. #
  11. # Author
  12. # ------
  13. #
  14. # Jiri Tyr <jiri.tyr@gmail.com>
  15. #
  16. #####
  17.  
  18. from ansible.utils.shlex import shlex_split
  19. from ansible.inventory.ini import InventoryParser
  20.  
  21. import argparse
  22. import json
  23. import os
  24. import sys
  25.  
  26.  
  27. class MyInventoryParser(InventoryParser):
  28. def __init__(self):
  29. pass
  30.  
  31.  
  32. def msg(_type, text, exit=0):
  33. sys.stderr.write("%s: %s\n" % (_type, text))
  34. sys.exit(exit)
  35.  
  36.  
  37. def main():
  38. # Read command line options
  39. parser = argparse.ArgumentParser(
  40. description=(
  41. 'Dynamic inventory script that reads inventory file in the INI '
  42. 'format.'))
  43. parser.add_argument(
  44. '--filename',
  45. metavar='filename',
  46. required=True,
  47. help='Path to the inventory file')
  48. parser.add_argument(
  49. '--list',
  50. action='store_true',
  51. help='List all groups and hosts')
  52. args = parser.parse_args()
  53.  
  54. # Get the filename from the command line arguments
  55. filename = args.filename
  56.  
  57. try:
  58. f = open(filename)
  59. except Exception as e:
  60. msg('E', 'Cannot open inventory file %s. %s' % (filename, str(e)))
  61.  
  62. # Some default values
  63. data = {}
  64. group = None
  65. state = None
  66. mip = MyInventoryParser()
  67.  
  68. # Walk through the file and build the data structure
  69. for line in f:
  70. line = line.strip()
  71.  
  72. # Skip comments and empty lines
  73. if line.startswith('#') or line.startswith(';') or len(line) == 0:
  74. continue
  75.  
  76. if line.startswith('['):
  77. # Parse group
  78. section = line[1:-1]
  79.  
  80. if ':' in line:
  81. group, state = line[1:-1].split(':')
  82. else:
  83. group = section
  84. state = 'hosts'
  85.  
  86. if group not in data:
  87. data[group] = {}
  88.  
  89. if state not in data[group]:
  90. if state == 'vars':
  91. data[group][state] = {}
  92. else:
  93. data[group][state] = []
  94. else:
  95. # Parse hosts or group members/vars
  96. try:
  97. tokens = shlex_split(line, comments=True)
  98. except ValueError as e:
  99. msg('E', "Error parsing host definition '%s': %s" % (line, e))
  100.  
  101. # Create 'all' group if no group was defined yet
  102. if group is None:
  103. group = 'all'
  104. state = 'hosts'
  105. data['all'] = {
  106. 'hosts': []
  107. }
  108.  
  109. tok = []
  110.  
  111. if state == 'hosts':
  112. tok = tokens[1:]
  113. elif state == 'vars':
  114. tok = tokens
  115.  
  116. variables = {}
  117.  
  118. for t in tok:
  119. if '=' not in t:
  120. msg(
  121. 'E',
  122. "Expected key=value host variable assignment, "
  123. "got: %s" % (t))
  124.  
  125. (k, v) = t.split('=', 1)
  126. variables[k] = mip._parse_value(v)
  127.  
  128. if state == 'vars':
  129. for key, val in variables.iteritems():
  130. data[group][state][key] = val
  131. else:
  132. (hostnames, port) = mip._expand_hostpattern(tokens[0])
  133.  
  134. for host in hostnames:
  135. data[group][state].append(host)
  136.  
  137. if state == 'hosts' and len(variables):
  138. if '_meta' not in data:
  139. data['_meta'] = {
  140. 'hostvars': {}
  141. }
  142.  
  143. data['_meta']['hostvars'][host] = {}
  144.  
  145. for key, val in variables.iteritems():
  146. data['_meta']['hostvars'][host][key] = val
  147.  
  148. print(json.dumps(data, sort_keys=True, indent=2))
  149.  
  150. try:
  151. f.close()
  152. except IOError as e:
  153. msg('E', 'Cannot close inventory file %s. %s' % (filename, str(e)))
  154.  
  155.  
  156. if __name__ == '__main__':
  157. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement