Repos with recipes to deploy some infrastructure services
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 

178 linhas
5.1 KiB

  1. #!/usr/bin/env python3
  2. import sys
  3. import os
  4. import yaml
  5. import json
  6. class YamlReaderError(Exception):
  7. pass
  8. #**********************************
  9. def static_to_dynamic_inventory(inputdict, hosts={}, groups={}, position='top'):
  10. '''{
  11. "_meta": {
  12. "hostvars": {}
  13. },
  14. "all": {
  15. "children": [
  16. "ungrouped"
  17. ]
  18. },
  19. "ungrouped": {
  20. "children": [
  21. ]
  22. }
  23. }
  24. '''
  25. outputdict = {'_meta': {'hostvars': {} }}
  26. newhosts = {}
  27. newgroups = {}
  28. for k,v in inputdict.items():
  29. if k == 'groups' or k == 'children':
  30. for group in v:
  31. if group not in groups:
  32. groups.update({group: {}})
  33. if isinstance(v, dict):
  34. if 'children' in v:
  35. if not k in newgroups:
  36. newgroups = { k: { 'children': [] }}
  37. for group in v['children']:
  38. newgroups[k]['children'].append(group)
  39. groups.update(newgroups)
  40. if 'groups' in v:
  41. if not k in newgroups:
  42. newgroups = { k: { 'children': [] }}
  43. for group in v['groups']:
  44. newgroups[k]['children'].append(group)
  45. groups.update(newgroups)
  46. if 'hosts' in v:
  47. if isinstance(v['hosts'], list):
  48. msg = """
  49. Hosts should not be define as a list:
  50. Error appear on v['hosts']
  51. Do this:
  52. hosts:
  53. host1:
  54. host2:
  55. Instead of this:
  56. hosts:
  57. - host1
  58. - host2
  59. Exit on Error (1)
  60. """
  61. sys.stderr.write(msg)
  62. exit(1)
  63. for host in list(v['hosts']):
  64. if k in groups:
  65. if 'hosts' in groups[k]:
  66. groups[k]['hosts'].append(host)
  67. else:
  68. groups[k]['hosts'] = [host]
  69. else:
  70. groups.update({k: {'hosts': [host]}})
  71. if v['hosts'][host] is None:
  72. if not host in newhosts:
  73. newhosts[host] = {}
  74. elif 'vars' in v['hosts'][host]:
  75. newhosts.update({host: v['hosts'][host]})
  76. else:
  77. for key,val in v['hosts'][host].items():
  78. if host in newhosts:
  79. newhosts[host].update({key: val})
  80. else:
  81. newhosts[host] = {key: val}
  82. hosts.update(newhosts)
  83. if 'vars' in v:
  84. if position == 'group':
  85. if k in newgroups:
  86. newgroups[k].update({'vars': v['vars']})
  87. else:
  88. newgroups[k] = {'vars': v['vars']}
  89. groups.update(newgroups)
  90. if k == 'groups' or k == 'children':
  91. newposition = 'group'
  92. elif k == 'hosts':
  93. newposition = 'host'
  94. else:
  95. newposition = 'data'
  96. valid_group_syntax = ['children', 'groups', 'hosts', 'vars', '', None]
  97. if position == 'group':
  98. for word in v:
  99. if not word in valid_group_syntax:
  100. print("Syntax error in definition of group: {}".format(k))
  101. print("\"{}\" is not a valid syntax key in group".format(word))
  102. exit(1)
  103. outputdict.update(static_to_dynamic_inventory(v, hosts, groups, newposition))
  104. outputdict['_meta']['hostvars'].update(hosts)
  105. outputdict.update(groups)
  106. return outputdict
  107. #**********************************
  108. def data_merge(inst1, inst2):
  109. try:
  110. if (inst1 is None or isinstance(inst1, str)
  111. or isinstance(inst1, int)
  112. or isinstance(inst1, float)
  113. ):
  114. inst1 = inst2
  115. elif isinstance(inst1, list):
  116. if isinstance(inst2, list):
  117. inst1 = inst1 + inst2
  118. else:
  119. inst1.append(inst2)
  120. elif isinstance(inst1, dict):
  121. if isinstance(inst2, dict):
  122. inst1.update(inst2)
  123. else:
  124. raise YamlReaderError('Cannot merge non-dict "%s" into dict "%s"' % (inst2, inst1))
  125. except TypeError as e:
  126. raise YamlReaderError('TypeError "%s" when merging "%s" into "%s"' %
  127. (e, inst1, inst2))
  128. return inst1
  129. #**********************************
  130. def load_static_inventory(path, static):
  131. ##- load static
  132. #add filename to dir
  133. files = {}
  134. files['static'] = {}
  135. files['static']['dir'] = path + '/static'
  136. files['static']['files'] = []
  137. static_hosts = []
  138. #get all *.yml files
  139. for root, directory, filename in sorted(os.walk(path)):
  140. for file in filename:
  141. if file.endswith(('.yml', '.yaml')):
  142. files['static']['files'].append(os.path.join(root, file))
  143. filecontent = None
  144. filecontent = yaml.load(
  145. open(os.path.join(root, file), "rb").read(),
  146. Loader=yaml.FullLoader
  147. )
  148. if type(filecontent) == dict:
  149. filecontent = static_to_dynamic_inventory(filecontent)
  150. if 'hostvars' in filecontent['_meta']:
  151. for hostname in filecontent['_meta']['hostvars']:
  152. static_hosts.append(hostname)
  153. static.update(filecontent)
  154. static_hosts = sorted(set(static_hosts))
  155. return static, static_hosts
  156. #**********************************
  157. def main():
  158. static = {'_meta': {'hostvars': {}}}
  159. static, static_hosts = load_static_inventory(os.path.dirname(__file__), static)
  160. print(format(json.dumps(static, indent=2)))
  161. #print(format(json.dumps(static_hosts, indent=2)))
  162. if __name__ == '__main__':
  163. main()