/lib/ansible/inventory/ini.py

https://github.com/ajanthanm/ansible · Python · 204 lines · 137 code · 25 blank · 42 comment · 57 complexity · f7ace00cf22d22748cec94a3112f4396 MD5 · raw file

  1. # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
  2. #
  3. # This file is part of Ansible
  4. #
  5. # Ansible is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # Ansible is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
  17. #############################################
  18. import ansible.constants as C
  19. from ansible.inventory.host import Host
  20. from ansible.inventory.group import Group
  21. from ansible.inventory.expand_hosts import detect_range
  22. from ansible.inventory.expand_hosts import expand_hostname_range
  23. from ansible import errors
  24. from ansible import utils
  25. import shlex
  26. import re
  27. import ast
  28. class InventoryParser(object):
  29. """
  30. Host inventory for ansible.
  31. """
  32. def __init__(self, filename=C.DEFAULT_HOST_LIST):
  33. with open(filename) as fh:
  34. self.lines = fh.readlines()
  35. self.groups = {}
  36. self.hosts = {}
  37. self._parse()
  38. def _parse(self):
  39. self._parse_base_groups()
  40. self._parse_group_children()
  41. self._add_allgroup_children()
  42. self._parse_group_variables()
  43. return self.groups
  44. @staticmethod
  45. def _parse_value(v):
  46. if "#" not in v:
  47. try:
  48. return ast.literal_eval(v)
  49. # Using explicit exceptions.
  50. # Likely a string that literal_eval does not like. We wil then just set it.
  51. except ValueError:
  52. # For some reason this was thought to be malformed.
  53. pass
  54. except SyntaxError:
  55. # Is this a hash with an equals at the end?
  56. pass
  57. return v
  58. # [webservers]
  59. # alpha
  60. # beta:2345
  61. # gamma sudo=True user=root
  62. # delta asdf=jkl favcolor=red
  63. def _add_allgroup_children(self):
  64. for group in self.groups.values():
  65. if group.depth == 0 and group.name != 'all':
  66. self.groups['all'].add_child_group(group)
  67. def _parse_base_groups(self):
  68. # FIXME: refactor
  69. ungrouped = Group(name='ungrouped')
  70. all = Group(name='all')
  71. all.add_child_group(ungrouped)
  72. self.groups = dict(all=all, ungrouped=ungrouped)
  73. active_group_name = 'ungrouped'
  74. for line in self.lines:
  75. line = utils.before_comment(line).strip()
  76. if line.startswith("[") and line.endswith("]"):
  77. active_group_name = line.replace("[","").replace("]","")
  78. if ":vars" in line or ":children" in line:
  79. active_group_name = active_group_name.rsplit(":", 1)[0]
  80. if active_group_name not in self.groups:
  81. new_group = self.groups[active_group_name] = Group(name=active_group_name)
  82. active_group_name = None
  83. elif active_group_name not in self.groups:
  84. new_group = self.groups[active_group_name] = Group(name=active_group_name)
  85. elif line.startswith(";") or line == '':
  86. pass
  87. elif active_group_name:
  88. tokens = shlex.split(line)
  89. if len(tokens) == 0:
  90. continue
  91. hostname = tokens[0]
  92. port = C.DEFAULT_REMOTE_PORT
  93. # Three cases to check:
  94. # 0. A hostname that contains a range pesudo-code and a port
  95. # 1. A hostname that contains just a port
  96. if hostname.count(":") > 1:
  97. # Possible an IPv6 address, or maybe a host line with multiple ranges
  98. # IPv6 with Port XXX:XXX::XXX.port
  99. # FQDN foo.example.com
  100. if hostname.count(".") == 1:
  101. (hostname, port) = hostname.rsplit(".", 1)
  102. elif ("[" in hostname and
  103. "]" in hostname and
  104. ":" in hostname and
  105. (hostname.rindex("]") < hostname.rindex(":")) or
  106. ("]" not in hostname and ":" in hostname)):
  107. (hostname, port) = hostname.rsplit(":", 1)
  108. hostnames = []
  109. if detect_range(hostname):
  110. hostnames = expand_hostname_range(hostname)
  111. else:
  112. hostnames = [hostname]
  113. for hn in hostnames:
  114. host = None
  115. if hn in self.hosts:
  116. host = self.hosts[hn]
  117. else:
  118. host = Host(name=hn, port=port)
  119. self.hosts[hn] = host
  120. if len(tokens) > 1:
  121. for t in tokens[1:]:
  122. if t.startswith('#'):
  123. break
  124. try:
  125. (k,v) = t.split("=", 1)
  126. except ValueError, e:
  127. raise errors.AnsibleError("Invalid ini entry: %s - %s" % (t, str(e)))
  128. host.set_variable(k, self._parse_value(v))
  129. self.groups[active_group_name].add_host(host)
  130. # [southeast:children]
  131. # atlanta
  132. # raleigh
  133. def _parse_group_children(self):
  134. group = None
  135. for line in self.lines:
  136. line = line.strip()
  137. if line is None or line == '':
  138. continue
  139. if line.startswith("[") and ":children]" in line:
  140. line = line.replace("[","").replace(":children]","")
  141. group = self.groups.get(line, None)
  142. if group is None:
  143. group = self.groups[line] = Group(name=line)
  144. elif line.startswith("#") or line.startswith(";"):
  145. pass
  146. elif line.startswith("["):
  147. group = None
  148. elif group:
  149. kid_group = self.groups.get(line, None)
  150. if kid_group is None:
  151. raise errors.AnsibleError("child group is not defined: (%s)" % line)
  152. else:
  153. group.add_child_group(kid_group)
  154. # [webservers:vars]
  155. # http_port=1234
  156. # maxRequestsPerChild=200
  157. def _parse_group_variables(self):
  158. group = None
  159. for line in self.lines:
  160. line = line.strip()
  161. if line.startswith("[") and ":vars]" in line:
  162. line = line.replace("[","").replace(":vars]","")
  163. group = self.groups.get(line, None)
  164. if group is None:
  165. raise errors.AnsibleError("can't add vars to undefined group: %s" % line)
  166. elif line.startswith("#") or line.startswith(";"):
  167. pass
  168. elif line.startswith("["):
  169. group = None
  170. elif line == '':
  171. pass
  172. elif group:
  173. if "=" not in line:
  174. raise errors.AnsibleError("variables assigned to group must be in key=value form")
  175. else:
  176. (k, v) = [e.strip() for e in line.split("=", 1)]
  177. group.set_variable(k, self._parse_value(v))
  178. def get_host_variables(self, host):
  179. return {}