PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ansible/inventory/__init__.py

https://gitlab.com/18runt88/ansible
Python | 654 lines | 612 code | 13 blank | 29 comment | 19 complexity | 489f11ddbd8705d05d76252033ab7dc5 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 fnmatch
  19. import os
  20. import sys
  21. import re
  22. import subprocess
  23. import ansible.constants as C
  24. from ansible.inventory.ini import InventoryParser
  25. from ansible.inventory.script import InventoryScript
  26. from ansible.inventory.dir import InventoryDirectory
  27. from ansible.inventory.group import Group
  28. from ansible.inventory.host import Host
  29. from ansible import errors
  30. from ansible import utils
  31. class Inventory(object):
  32. """
  33. Host inventory for ansible.
  34. """
  35. __slots__ = [ 'host_list', 'groups', '_restriction', '_also_restriction', '_subset',
  36. 'parser', '_vars_per_host', '_vars_per_group', '_hosts_cache', '_groups_list',
  37. '_pattern_cache', '_vault_password', '_vars_plugins', '_playbook_basedir']
  38. def __init__(self, host_list=C.DEFAULT_HOST_LIST, vault_password=None):
  39. # the host file file, or script path, or list of hosts
  40. # if a list, inventory data will NOT be loaded
  41. self.host_list = host_list
  42. self._vault_password=vault_password
  43. # caching to avoid repeated calculations, particularly with
  44. # external inventory scripts.
  45. self._vars_per_host = {}
  46. self._vars_per_group = {}
  47. self._hosts_cache = {}
  48. self._groups_list = {}
  49. self._pattern_cache = {}
  50. # to be set by calling set_playbook_basedir by playbook code
  51. self._playbook_basedir = None
  52. # the inventory object holds a list of groups
  53. self.groups = []
  54. # a list of host(names) to contain current inquiries to
  55. self._restriction = None
  56. self._also_restriction = None
  57. self._subset = None
  58. if isinstance(host_list, basestring):
  59. if "," in host_list:
  60. host_list = host_list.split(",")
  61. host_list = [ h for h in host_list if h and h.strip() ]
  62. if host_list is None:
  63. self.parser = None
  64. elif isinstance(host_list, list):
  65. self.parser = None
  66. all = Group('all')
  67. self.groups = [ all ]
  68. ipv6_re = re.compile('\[([a-f:A-F0-9]*[%[0-z]+]?)\](?::(\d+))?')
  69. for x in host_list:
  70. m = ipv6_re.match(x)
  71. if m:
  72. all.add_host(Host(m.groups()[0], m.groups()[1]))
  73. else:
  74. if ":" in x:
  75. tokens = x.rsplit(":", 1)
  76. # if there is ':' in the address, then this is an ipv6
  77. if ':' in tokens[0]:
  78. all.add_host(Host(x))
  79. else:
  80. all.add_host(Host(tokens[0], tokens[1]))
  81. else:
  82. all.add_host(Host(x))
  83. elif os.path.exists(host_list):
  84. if os.path.isdir(host_list):
  85. # Ensure basedir is inside the directory
  86. self.host_list = os.path.join(self.host_list, "")
  87. self.parser = InventoryDirectory(filename=host_list)
  88. self.groups = self.parser.groups.values()
  89. else:
  90. # check to see if the specified file starts with a
  91. # shebang (#!/), so if an error is raised by the parser
  92. # class we can show a more apropos error
  93. shebang_present = False
  94. try:
  95. inv_file = open(host_list)
  96. first_line = inv_file.readlines()[0]
  97. inv_file.close()
  98. if first_line.startswith('#!'):
  99. shebang_present = True
  100. except:
  101. pass
  102. if utils.is_executable(host_list):
  103. try:
  104. self.parser = InventoryScript(filename=host_list)
  105. self.groups = self.parser.groups.values()
  106. except:
  107. if not shebang_present:
  108. raise errors.AnsibleError("The file %s is marked as executable, but failed to execute correctly. " % host_list + \
  109. "If this is not supposed to be an executable script, correct this with `chmod -x %s`." % host_list)
  110. else:
  111. raise
  112. else:
  113. try:
  114. self.parser = InventoryParser(filename=host_list)
  115. self.groups = self.parser.groups.values()
  116. except:
  117. if shebang_present:
  118. raise errors.AnsibleError("The file %s looks like it should be an executable inventory script, but is not marked executable. " % host_list + \
  119. "Perhaps you want to correct this with `chmod +x %s`?" % host_list)
  120. else:
  121. raise
  122. utils.plugins.vars_loader.add_directory(self.basedir(), with_subdir=True)
  123. else:
  124. raise errors.AnsibleError("Unable to find an inventory file, specify one with -i ?")
  125. self._vars_plugins = [ x for x in utils.plugins.vars_loader.all(self) ]
  126. # get group vars from group_vars/ files and vars plugins
  127. for group in self.groups:
  128. group.vars = utils.combine_vars(group.vars, self.get_group_variables(group.name, vault_password=self._vault_password))
  129. # get host vars from host_vars/ files and vars plugins
  130. for host in self.get_hosts():
  131. host.vars = utils.combine_vars(host.vars, self.get_host_variables(host.name, vault_password=self._vault_password))
  132. def _match(self, str, pattern_str):
  133. try:
  134. if pattern_str.startswith('~'):
  135. return re.search(pattern_str[1:], str)
  136. else:
  137. return fnmatch.fnmatch(str, pattern_str)
  138. except Exception, e:
  139. raise errors.AnsibleError('invalid host pattern: %s' % pattern_str)
  140. def _match_list(self, items, item_attr, pattern_str):
  141. results = []
  142. try:
  143. if not pattern_str.startswith('~'):
  144. pattern = re.compile(fnmatch.translate(pattern_str))
  145. else:
  146. pattern = re.compile(pattern_str[1:])
  147. except Exception, e:
  148. raise errors.AnsibleError('invalid host pattern: %s' % pattern_str)
  149. for item in items:
  150. if pattern.match(getattr(item, item_attr)):
  151. results.append(item)
  152. return results
  153. def get_hosts(self, pattern="all"):
  154. """
  155. find all host names matching a pattern string, taking into account any inventory restrictions or
  156. applied subsets.
  157. """
  158. # process patterns
  159. if isinstance(pattern, list):
  160. pattern = ';'.join(pattern)
  161. patterns = pattern.replace(";",":").split(":")
  162. hosts = self._get_hosts(patterns)
  163. # exclude hosts not in a subset, if defined
  164. if self._subset:
  165. subset = self._get_hosts(self._subset)
  166. hosts = [ h for h in hosts if h in subset ]
  167. # exclude hosts mentioned in any restriction (ex: failed hosts)
  168. if self._restriction is not None:
  169. hosts = [ h for h in hosts if h.name in self._restriction ]
  170. if self._also_restriction is not None:
  171. hosts = [ h for h in hosts if h.name in self._also_restriction ]
  172. return hosts
  173. def _get_hosts(self, patterns):
  174. """
  175. finds hosts that match a list of patterns. Handles negative
  176. matches as well as intersection matches.
  177. """
  178. # Host specifiers should be sorted to ensure consistent behavior
  179. pattern_regular = []
  180. pattern_intersection = []
  181. pattern_exclude = []
  182. for p in patterns:
  183. if p.startswith("!"):
  184. pattern_exclude.append(p)
  185. elif p.startswith("&"):
  186. pattern_intersection.append(p)
  187. elif p:
  188. pattern_regular.append(p)
  189. # if no regular pattern was given, hence only exclude and/or intersection
  190. # make that magically work
  191. if pattern_regular == []:
  192. pattern_regular = ['all']
  193. # when applying the host selectors, run those without the "&" or "!"
  194. # first, then the &s, then the !s.
  195. patterns = pattern_regular + pattern_intersection + pattern_exclude
  196. hosts = []
  197. for p in patterns:
  198. # avoid resolving a pattern that is a plain host
  199. if p in self._hosts_cache:
  200. hosts.append(self.get_host(p))
  201. else:
  202. that = self.__get_hosts(p)
  203. if p.startswith("!"):
  204. hosts = [ h for h in hosts if h not in that ]
  205. elif p.startswith("&"):
  206. hosts = [ h for h in hosts if h in that ]
  207. else:
  208. to_append = [ h for h in that if h.name not in [ y.name for y in hosts ] ]
  209. hosts.extend(to_append)
  210. return hosts
  211. def __get_hosts(self, pattern):
  212. """
  213. finds hosts that positively match a particular pattern. Does not
  214. take into account negative matches.
  215. """
  216. if pattern in self._pattern_cache:
  217. return self._pattern_cache[pattern]
  218. (name, enumeration_details) = self._enumeration_info(pattern)
  219. hpat = self._hosts_in_unenumerated_pattern(name)
  220. result = self._apply_ranges(pattern, hpat)
  221. self._pattern_cache[pattern] = result
  222. return result
  223. def _enumeration_info(self, pattern):
  224. """
  225. returns (pattern, limits) taking a regular pattern and finding out
  226. which parts of it correspond to start/stop offsets. limits is
  227. a tuple of (start, stop) or None
  228. """
  229. # Do not parse regexes for enumeration info
  230. if pattern.startswith('~'):
  231. return (pattern, None)
  232. # The regex used to match on the range, which can be [x] or [x-y].
  233. pattern_re = re.compile("^(.*)\[([-]?[0-9]+)(?:(?:-)([0-9]+))?\](.*)$")
  234. m = pattern_re.match(pattern)
  235. if m:
  236. (target, first, last, rest) = m.groups()
  237. first = int(first)
  238. if last:
  239. if first < 0:
  240. raise errors.AnsibleError("invalid range: negative indices cannot be used as the first item in a range")
  241. last = int(last)
  242. else:
  243. last = first
  244. return (target, (first, last))
  245. else:
  246. return (pattern, None)
  247. def _apply_ranges(self, pat, hosts):
  248. """
  249. given a pattern like foo, that matches hosts, return all of hosts
  250. given a pattern like foo[0:5], where foo matches hosts, return the first 6 hosts
  251. """
  252. # If there are no hosts to select from, just return the
  253. # empty set. This prevents trying to do selections on an empty set.
  254. # issue#6258
  255. if not hosts:
  256. return hosts
  257. (loose_pattern, limits) = self._enumeration_info(pat)
  258. if not limits:
  259. return hosts
  260. (left, right) = limits
  261. if left == '':
  262. left = 0
  263. if right == '':
  264. right = 0
  265. left=int(left)
  266. right=int(right)
  267. try:
  268. if left != right:
  269. return hosts[left:right]
  270. else:
  271. return [ hosts[left] ]
  272. except IndexError:
  273. raise errors.AnsibleError("no hosts matching the pattern '%s' were found" % pat)
  274. def _create_implicit_localhost(self, pattern):
  275. new_host = Host(pattern)
  276. new_host.set_variable("ansible_python_interpreter", sys.executable)
  277. new_host.set_variable("ansible_connection", "local")
  278. ungrouped = self.get_group("ungrouped")
  279. if ungrouped is None:
  280. self.add_group(Group('ungrouped'))
  281. ungrouped = self.get_group('ungrouped')
  282. self.get_group('all').add_child_group(ungrouped)
  283. ungrouped.add_host(new_host)
  284. return new_host
  285. def _hosts_in_unenumerated_pattern(self, pattern):
  286. """ Get all host names matching the pattern """
  287. results = []
  288. hosts = []
  289. hostnames = set()
  290. # ignore any negative checks here, this is handled elsewhere
  291. pattern = pattern.replace("!","").replace("&", "")
  292. def __append_host_to_results(host):
  293. if host not in results and host.name not in hostnames:
  294. hostnames.add(host.name)
  295. results.append(host)
  296. groups = self.get_groups()
  297. for group in groups:
  298. if pattern == 'all':
  299. for host in group.get_hosts():
  300. __append_host_to_results(host)
  301. else:
  302. if self._match(group.name, pattern):
  303. for host in group.get_hosts():
  304. __append_host_to_results(host)
  305. else:
  306. matching_hosts = self._match_list(group.get_hosts(), 'name', pattern)
  307. for host in matching_hosts:
  308. __append_host_to_results(host)
  309. if pattern in ["localhost", "127.0.0.1"] and len(results) == 0:
  310. new_host = self._create_implicit_localhost(pattern)
  311. results.append(new_host)
  312. return results
  313. def clear_pattern_cache(self):
  314. ''' called exclusively by the add_host plugin to allow patterns to be recalculated '''
  315. self._pattern_cache = {}
  316. def groups_for_host(self, host):
  317. if host in self._hosts_cache:
  318. return self._hosts_cache[host].get_groups()
  319. else:
  320. return []
  321. def groups_list(self):
  322. if not self._groups_list:
  323. groups = {}
  324. for g in self.groups:
  325. groups[g.name] = [h.name for h in g.get_hosts()]
  326. ancestors = g.get_ancestors()
  327. for a in ancestors:
  328. if a.name not in groups:
  329. groups[a.name] = [h.name for h in a.get_hosts()]
  330. self._groups_list = groups
  331. return self._groups_list
  332. def get_groups(self):
  333. return self.groups
  334. def get_host(self, hostname):
  335. if hostname not in self._hosts_cache:
  336. self._hosts_cache[hostname] = self._get_host(hostname)
  337. return self._hosts_cache[hostname]
  338. def _get_host(self, hostname):
  339. if hostname in ['localhost','127.0.0.1']:
  340. for host in self.get_group('all').get_hosts():
  341. if host.name in ['localhost', '127.0.0.1']:
  342. return host
  343. return self._create_implicit_localhost(hostname)
  344. else:
  345. for group in self.groups:
  346. for host in group.get_hosts():
  347. if hostname == host.name:
  348. return host
  349. return None
  350. def get_group(self, groupname):
  351. for group in self.groups:
  352. if group.name == groupname:
  353. return group
  354. return None
  355. def get_group_variables(self, groupname, update_cached=False, vault_password=None):
  356. if groupname not in self._vars_per_group or update_cached:
  357. self._vars_per_group[groupname] = self._get_group_variables(groupname, vault_password=vault_password)
  358. return self._vars_per_group[groupname]
  359. def _get_group_variables(self, groupname, vault_password=None):
  360. group = self.get_group(groupname)
  361. if group is None:
  362. raise errors.AnsibleError("group not found: %s" % groupname)
  363. vars = {}
  364. # plugin.get_group_vars retrieves just vars for specific group
  365. vars_results = [ plugin.get_group_vars(group, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'get_group_vars')]
  366. for updated in vars_results:
  367. if updated is not None:
  368. vars = utils.combine_vars(vars, updated)
  369. # Read group_vars/ files
  370. vars = utils.combine_vars(vars, self.get_group_vars(group))
  371. return vars
  372. def get_variables(self, hostname, update_cached=False, vault_password=None):
  373. host = self.get_host(hostname)
  374. if not host:
  375. raise errors.AnsibleError("host not found: %s" % hostname)
  376. return host.get_variables()
  377. def get_host_variables(self, hostname, update_cached=False, vault_password=None):
  378. if hostname not in self._vars_per_host or update_cached:
  379. self._vars_per_host[hostname] = self._get_host_variables(hostname, vault_password=vault_password)
  380. return self._vars_per_host[hostname]
  381. def _get_host_variables(self, hostname, vault_password=None):
  382. host = self.get_host(hostname)
  383. if host is None:
  384. raise errors.AnsibleError("host not found: %s" % hostname)
  385. vars = {}
  386. # plugin.run retrieves all vars (also from groups) for host
  387. vars_results = [ plugin.run(host, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'run')]
  388. for updated in vars_results:
  389. if updated is not None:
  390. vars = utils.combine_vars(vars, updated)
  391. # plugin.get_host_vars retrieves just vars for specific host
  392. vars_results = [ plugin.get_host_vars(host, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'get_host_vars')]
  393. for updated in vars_results:
  394. if updated is not None:
  395. vars = utils.combine_vars(vars, updated)
  396. # still need to check InventoryParser per host vars
  397. # which actually means InventoryScript per host,
  398. # which is not performant
  399. if self.parser is not None:
  400. vars = utils.combine_vars(vars, self.parser.get_host_variables(host))
  401. # Read host_vars/ files
  402. vars = utils.combine_vars(vars, self.get_host_vars(host))
  403. return vars
  404. def add_group(self, group):
  405. if group.name not in self.groups_list():
  406. self.groups.append(group)
  407. self._groups_list = None # invalidate internal cache
  408. else:
  409. raise errors.AnsibleError("group already in inventory: %s" % group.name)
  410. def list_hosts(self, pattern="all"):
  411. """ return a list of hostnames for a pattern """
  412. result = [ h.name for h in self.get_hosts(pattern) ]
  413. if len(result) == 0 and pattern in ["localhost", "127.0.0.1"]:
  414. result = [pattern]
  415. return result
  416. def list_groups(self):
  417. return sorted([ g.name for g in self.groups ], key=lambda x: x)
  418. # TODO: remove this function
  419. def get_restriction(self):
  420. return self._restriction
  421. def restrict_to(self, restriction):
  422. """
  423. Restrict list operations to the hosts given in restriction. This is used
  424. to exclude failed hosts in main playbook code, don't use this for other
  425. reasons.
  426. """
  427. if not isinstance(restriction, list):
  428. restriction = [ restriction ]
  429. self._restriction = restriction
  430. def also_restrict_to(self, restriction):
  431. """
  432. Works like restict_to but offers an additional restriction. Playbooks use this
  433. to implement serial behavior.
  434. """
  435. if not isinstance(restriction, list):
  436. restriction = [ restriction ]
  437. self._also_restriction = restriction
  438. def subset(self, subset_pattern):
  439. """
  440. Limits inventory results to a subset of inventory that matches a given
  441. pattern, such as to select a given geographic of numeric slice amongst
  442. a previous 'hosts' selection that only select roles, or vice versa.
  443. Corresponds to --limit parameter to ansible-playbook
  444. """
  445. if subset_pattern is None:
  446. self._subset = None
  447. else:
  448. subset_pattern = subset_pattern.replace(',',':')
  449. subset_pattern = subset_pattern.replace(";",":").split(":")
  450. results = []
  451. # allow Unix style @filename data
  452. for x in subset_pattern:
  453. if x.startswith("@"):
  454. fd = open(x[1:])
  455. results.extend(fd.read().split("\n"))
  456. fd.close()
  457. else:
  458. results.append(x)
  459. self._subset = results
  460. def lift_restriction(self):
  461. """ Do not restrict list operations """
  462. self._restriction = None
  463. def lift_also_restriction(self):
  464. """ Clears the also restriction """
  465. self._also_restriction = None
  466. def is_file(self):
  467. """ did inventory come from a file? """
  468. if not isinstance(self.host_list, basestring):
  469. return False
  470. return os.path.exists(self.host_list)
  471. def basedir(self):
  472. """ if inventory came from a file, what's the directory? """
  473. if not self.is_file():
  474. return None
  475. dname = os.path.dirname(self.host_list)
  476. if dname is None or dname == '' or dname == '.':
  477. cwd = os.getcwd()
  478. return os.path.abspath(cwd)
  479. return os.path.abspath(dname)
  480. def src(self):
  481. """ if inventory came from a file, what's the directory and file name? """
  482. if not self.is_file():
  483. return None
  484. return self.host_list
  485. def playbook_basedir(self):
  486. """ returns the directory of the current playbook """
  487. return self._playbook_basedir
  488. def set_playbook_basedir(self, dir):
  489. """
  490. sets the base directory of the playbook so inventory can use it as a
  491. basedir for host_ and group_vars, and other things.
  492. """
  493. # Only update things if dir is a different playbook basedir
  494. if dir != self._playbook_basedir:
  495. self._playbook_basedir = dir
  496. # get group vars from group_vars/ files
  497. for group in self.groups:
  498. group.vars = utils.combine_vars(group.vars, self.get_group_vars(group, new_pb_basedir=True))
  499. # get host vars from host_vars/ files
  500. for host in self.get_hosts():
  501. host.vars = utils.combine_vars(host.vars, self.get_host_vars(host, new_pb_basedir=True))
  502. # invalidate cache
  503. self._vars_per_host = {}
  504. self._vars_per_group = {}
  505. def get_host_vars(self, host, new_pb_basedir=False):
  506. """ Read host_vars/ files """
  507. return self._get_hostgroup_vars(host=host, group=None, new_pb_basedir=new_pb_basedir)
  508. def get_group_vars(self, group, new_pb_basedir=False):
  509. """ Read group_vars/ files """
  510. return self._get_hostgroup_vars(host=None, group=group, new_pb_basedir=new_pb_basedir)
  511. def _get_hostgroup_vars(self, host=None, group=None, new_pb_basedir=False):
  512. """
  513. Loads variables from group_vars/<groupname> and host_vars/<hostname> in directories parallel
  514. to the inventory base directory or in the same directory as the playbook. Variables in the playbook
  515. dir will win over the inventory dir if files are in both.
  516. """
  517. results = {}
  518. scan_pass = 0
  519. _basedir = self.basedir()
  520. # look in both the inventory base directory and the playbook base directory
  521. # unless we do an update for a new playbook base dir
  522. if not new_pb_basedir:
  523. basedirs = [_basedir, self._playbook_basedir]
  524. else:
  525. basedirs = [self._playbook_basedir]
  526. for basedir in basedirs:
  527. # this can happen from particular API usages, particularly if not run
  528. # from /usr/bin/ansible-playbook
  529. if basedir is None:
  530. continue
  531. scan_pass = scan_pass + 1
  532. # it's not an eror if the directory does not exist, keep moving
  533. if not os.path.exists(basedir):
  534. continue
  535. # save work of second scan if the directories are the same
  536. if _basedir == self._playbook_basedir and scan_pass != 1:
  537. continue
  538. if group and host is None:
  539. # load vars in dir/group_vars/name_of_group
  540. base_path = os.path.join(basedir, "group_vars/%s" % group.name)
  541. results = utils.load_vars(base_path, results, vault_password=self._vault_password)
  542. elif host and group is None:
  543. # same for hostvars in dir/host_vars/name_of_host
  544. base_path = os.path.join(basedir, "host_vars/%s" % host.name)
  545. results = utils.load_vars(base_path, results, vault_password=self._vault_password)
  546. # all done, results is a dictionary of variables for this particular host.
  547. return results