PageRenderTime 44ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/ansible/inventory/__init__.py

https://gitlab.com/smoke.torez/ansible
Python | 763 lines | 704 code | 26 blank | 33 comment | 15 complexity | 64e5fd5ea4d3ad0ae4c51de9436902e0 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. from __future__ import (absolute_import, division, print_function)
  19. __metaclass__ = type
  20. import fnmatch
  21. import os
  22. import sys
  23. import re
  24. import itertools
  25. from ansible.compat.six import string_types
  26. from ansible import constants as C
  27. from ansible.errors import AnsibleError
  28. from ansible.inventory.dir import InventoryDirectory, get_file_parser
  29. from ansible.inventory.group import Group
  30. from ansible.inventory.host import Host
  31. from ansible.plugins import vars_loader
  32. from ansible.utils.unicode import to_unicode
  33. from ansible.utils.vars import combine_vars
  34. from ansible.parsing.utils.addresses import parse_address
  35. HOSTS_PATTERNS_CACHE = {}
  36. try:
  37. from __main__ import display
  38. except ImportError:
  39. from ansible.utils.display import Display
  40. display = Display()
  41. class Inventory(object):
  42. """
  43. Host inventory for ansible.
  44. """
  45. def __init__(self, loader, variable_manager, host_list=C.DEFAULT_HOST_LIST):
  46. # the host file file, or script path, or list of hosts
  47. # if a list, inventory data will NOT be loaded
  48. self.host_list = host_list
  49. self._loader = loader
  50. self._variable_manager = variable_manager
  51. # caching to avoid repeated calculations, particularly with
  52. # external inventory scripts.
  53. self._vars_per_host = {}
  54. self._vars_per_group = {}
  55. self._hosts_cache = {}
  56. self._pattern_cache = {}
  57. self._vars_plugins = []
  58. # to be set by calling set_playbook_basedir by playbook code
  59. self._playbook_basedir = None
  60. # the inventory object holds a list of groups
  61. self.groups = {}
  62. # a list of host(names) to contain current inquiries to
  63. self._restriction = None
  64. self._subset = None
  65. # clear the cache here, which is only useful if more than
  66. # one Inventory objects are created when using the API directly
  67. self.clear_pattern_cache()
  68. self.parse_inventory(host_list)
  69. def serialize(self):
  70. data = dict()
  71. return data
  72. def deserialize(self, data):
  73. pass
  74. def parse_inventory(self, host_list):
  75. if isinstance(host_list, string_types):
  76. if "," in host_list:
  77. host_list = host_list.split(",")
  78. host_list = [ h for h in host_list if h and h.strip() ]
  79. self.parser = None
  80. # Always create the 'all' and 'ungrouped' groups, even if host_list is
  81. # empty: in this case we will subsequently an the implicit 'localhost' to it.
  82. ungrouped = Group(name='ungrouped')
  83. all = Group('all')
  84. all.add_child_group(ungrouped)
  85. self.groups = dict(all=all, ungrouped=ungrouped)
  86. if host_list is None:
  87. pass
  88. elif isinstance(host_list, list):
  89. for h in host_list:
  90. try:
  91. (host, port) = parse_address(h, allow_ranges=False)
  92. except AnsibleError as e:
  93. display.vvv("Unable to parse address from hostname, leaving unchanged: %s" % to_unicode(e))
  94. host = h
  95. port = None
  96. all.add_host(Host(host, port))
  97. elif self._loader.path_exists(host_list):
  98. #TODO: switch this to a plugin loader and a 'condition' per plugin on which it should be tried, restoring 'inventory pllugins'
  99. if self.is_directory(host_list):
  100. # Ensure basedir is inside the directory
  101. host_list = os.path.join(self.host_list, "")
  102. self.parser = InventoryDirectory(loader=self._loader, groups=self.groups, filename=host_list)
  103. else:
  104. self.parser = get_file_parser(host_list, self.groups, self._loader)
  105. vars_loader.add_directory(self.basedir(), with_subdir=True)
  106. if not self.parser:
  107. # should never happen, but JIC
  108. raise AnsibleError("Unable to parse %s as an inventory source" % host_list)
  109. else:
  110. display.warning("Host file not found: %s" % to_unicode(host_list))
  111. self._vars_plugins = [ x for x in vars_loader.all(self) ]
  112. # get group vars from group_vars/ files and vars plugins
  113. for group in self.groups.values():
  114. group.vars = combine_vars(group.vars, self.get_group_variables(group.name))
  115. # get host vars from host_vars/ files and vars plugins
  116. for host in self.get_hosts():
  117. host.vars = combine_vars(host.vars, self.get_host_variables(host.name))
  118. def _match(self, str, pattern_str):
  119. try:
  120. if pattern_str.startswith('~'):
  121. return re.search(pattern_str[1:], str)
  122. else:
  123. return fnmatch.fnmatch(str, pattern_str)
  124. except Exception:
  125. raise AnsibleError('invalid host pattern: %s' % pattern_str)
  126. def _match_list(self, items, item_attr, pattern_str):
  127. results = []
  128. try:
  129. if not pattern_str.startswith('~'):
  130. pattern = re.compile(fnmatch.translate(pattern_str))
  131. else:
  132. pattern = re.compile(pattern_str[1:])
  133. except Exception:
  134. raise AnsibleError('invalid host pattern: %s' % pattern_str)
  135. for item in items:
  136. if pattern.match(getattr(item, item_attr)):
  137. results.append(item)
  138. return results
  139. def get_hosts(self, pattern="all", ignore_limits_and_restrictions=False):
  140. """
  141. Takes a pattern or list of patterns and returns a list of matching
  142. inventory host names, taking into account any active restrictions
  143. or applied subsets
  144. """
  145. # Check if pattern already computed
  146. if isinstance(pattern, list):
  147. pattern_hash = u":".join(pattern)
  148. else:
  149. pattern_hash = pattern
  150. if not ignore_limits_and_restrictions:
  151. if self._subset:
  152. pattern_hash += u":%s" % to_unicode(self._subset)
  153. if self._restriction:
  154. pattern_hash += u":%s" % to_unicode(self._restriction)
  155. if pattern_hash not in HOSTS_PATTERNS_CACHE:
  156. patterns = Inventory.split_host_pattern(pattern)
  157. hosts = self._evaluate_patterns(patterns)
  158. # mainly useful for hostvars[host] access
  159. if not ignore_limits_and_restrictions:
  160. # exclude hosts not in a subset, if defined
  161. if self._subset:
  162. subset = self._evaluate_patterns(self._subset)
  163. hosts = [ h for h in hosts if h in subset ]
  164. # exclude hosts mentioned in any restriction (ex: failed hosts)
  165. if self._restriction is not None:
  166. hosts = [ h for h in hosts if h in self._restriction ]
  167. seen = set()
  168. HOSTS_PATTERNS_CACHE[pattern_hash] = [x for x in hosts if x not in seen and not seen.add(x)]
  169. return HOSTS_PATTERNS_CACHE[pattern_hash][:]
  170. @classmethod
  171. def split_host_pattern(cls, pattern):
  172. """
  173. Takes a string containing host patterns separated by commas (or a list
  174. thereof) and returns a list of single patterns (which may not contain
  175. commas). Whitespace is ignored.
  176. Also accepts ':' as a separator for backwards compatibility, but it is
  177. not recommended due to the conflict with IPv6 addresses and host ranges.
  178. Example: 'a,b[1], c[2:3] , d' -> ['a', 'b[1]', 'c[2:3]', 'd']
  179. """
  180. if isinstance(pattern, list):
  181. return list(itertools.chain(*map(cls.split_host_pattern, pattern)))
  182. if ';' in pattern:
  183. patterns = re.split('\s*;\s*', pattern)
  184. display.deprecated("Use ',' or ':' instead of ';' to separate host patterns")
  185. # If it's got commas in it, we'll treat it as a straightforward
  186. # comma-separated list of patterns.
  187. elif ',' in pattern:
  188. patterns = re.split('\s*,\s*', pattern)
  189. # If it doesn't, it could still be a single pattern. This accounts for
  190. # non-separator uses of colons: IPv6 addresses and [x:y] host ranges.
  191. else:
  192. try:
  193. (base, port) = parse_address(pattern, allow_ranges=True)
  194. patterns = [pattern]
  195. except:
  196. # The only other case we accept is a ':'-separated list of patterns.
  197. # This mishandles IPv6 addresses, and is retained only for backwards
  198. # compatibility.
  199. patterns = re.findall(
  200. r'''(?: # We want to match something comprising:
  201. [^\s:\[\]] # (anything other than whitespace or ':[]'
  202. | # ...or...
  203. \[[^\]]*\] # a single complete bracketed expression)
  204. )+ # occurring once or more
  205. ''', pattern, re.X
  206. )
  207. return [p.strip() for p in patterns]
  208. @classmethod
  209. def order_patterns(cls, patterns):
  210. # Host specifiers should be sorted to ensure consistent behavior
  211. pattern_regular = []
  212. pattern_intersection = []
  213. pattern_exclude = []
  214. for p in patterns:
  215. if p.startswith("!"):
  216. pattern_exclude.append(p)
  217. elif p.startswith("&"):
  218. pattern_intersection.append(p)
  219. elif p:
  220. pattern_regular.append(p)
  221. # if no regular pattern was given, hence only exclude and/or intersection
  222. # make that magically work
  223. if pattern_regular == []:
  224. pattern_regular = ['all']
  225. # when applying the host selectors, run those without the "&" or "!"
  226. # first, then the &s, then the !s.
  227. return pattern_regular + pattern_intersection + pattern_exclude
  228. def _evaluate_patterns(self, patterns):
  229. """
  230. Takes a list of patterns and returns a list of matching host names,
  231. taking into account any negative and intersection patterns.
  232. """
  233. patterns = Inventory.order_patterns(patterns)
  234. hosts = []
  235. for p in patterns:
  236. # avoid resolving a pattern that is a plain host
  237. if p in self._hosts_cache:
  238. hosts.append(self.get_host(p))
  239. else:
  240. that = self._match_one_pattern(p)
  241. if p.startswith("!"):
  242. hosts = [ h for h in hosts if h not in that ]
  243. elif p.startswith("&"):
  244. hosts = [ h for h in hosts if h in that ]
  245. else:
  246. to_append = [ h for h in that if h.name not in [ y.name for y in hosts ] ]
  247. hosts.extend(to_append)
  248. return hosts
  249. def _match_one_pattern(self, pattern):
  250. """
  251. Takes a single pattern and returns a list of matching host names.
  252. Ignores intersection (&) and exclusion (!) specifiers.
  253. The pattern may be:
  254. 1. A regex starting with ~, e.g. '~[abc]*'
  255. 2. A shell glob pattern with ?/*/[chars]/[!chars], e.g. 'foo*'
  256. 3. An ordinary word that matches itself only, e.g. 'foo'
  257. The pattern is matched using the following rules:
  258. 1. If it's 'all', it matches all hosts in all groups.
  259. 2. Otherwise, for each known group name:
  260. (a) if it matches the group name, the results include all hosts
  261. in the group or any of its children.
  262. (b) otherwise, if it matches any hosts in the group, the results
  263. include the matching hosts.
  264. This means that 'foo*' may match one or more groups (thus including all
  265. hosts therein) but also hosts in other groups.
  266. The built-in groups 'all' and 'ungrouped' are special. No pattern can
  267. match these group names (though 'all' behaves as though it matches, as
  268. described above). The word 'ungrouped' can match a host of that name,
  269. and patterns like 'ungr*' and 'al*' can match either hosts or groups
  270. other than all and ungrouped.
  271. If the pattern matches one or more group names according to these rules,
  272. it may have an optional range suffix to select a subset of the results.
  273. This is allowed only if the pattern is not a regex, i.e. '~foo[1]' does
  274. not work (the [1] is interpreted as part of the regex), but 'foo*[1]'
  275. would work if 'foo*' matched the name of one or more groups.
  276. Duplicate matches are always eliminated from the results.
  277. """
  278. if pattern.startswith("&") or pattern.startswith("!"):
  279. pattern = pattern[1:]
  280. if pattern not in self._pattern_cache:
  281. (expr, slice) = self._split_subscript(pattern)
  282. hosts = self._enumerate_matches(expr)
  283. try:
  284. hosts = self._apply_subscript(hosts, slice)
  285. except IndexError:
  286. raise AnsibleError("No hosts matched the subscripted pattern '%s'" % pattern)
  287. self._pattern_cache[pattern] = hosts
  288. return self._pattern_cache[pattern]
  289. def _split_subscript(self, pattern):
  290. """
  291. Takes a pattern, checks if it has a subscript, and returns the pattern
  292. without the subscript and a (start,end) tuple representing the given
  293. subscript (or None if there is no subscript).
  294. Validates that the subscript is in the right syntax, but doesn't make
  295. sure the actual indices make sense in context.
  296. """
  297. # Do not parse regexes for enumeration info
  298. if pattern.startswith('~'):
  299. return (pattern, None)
  300. # We want a pattern followed by an integer or range subscript.
  301. # (We can't be more restrictive about the expression because the
  302. # fnmatch semantics permit [\[:\]] to occur.)
  303. pattern_with_subscript = re.compile(
  304. r'''^
  305. (.+) # A pattern expression ending with...
  306. \[(?: # A [subscript] expression comprising:
  307. (-?[0-9]+)| # A single positive or negative number
  308. ([0-9]+)([:-]) # Or an x:y or x: range.
  309. ([0-9]*)
  310. )\]
  311. $
  312. ''', re.X
  313. )
  314. subscript = None
  315. m = pattern_with_subscript.match(pattern)
  316. if m:
  317. (pattern, idx, start, sep, end) = m.groups()
  318. if idx:
  319. subscript = (int(idx), None)
  320. else:
  321. if not end:
  322. end = -1
  323. subscript = (int(start), int(end))
  324. if sep == '-':
  325. display.warning("Use [x:y] inclusive subscripts instead of [x-y] which has been removed")
  326. return (pattern, subscript)
  327. def _apply_subscript(self, hosts, subscript):
  328. """
  329. Takes a list of hosts and a (start,end) tuple and returns the subset of
  330. hosts based on the subscript (which may be None to return all hosts).
  331. """
  332. if not hosts or not subscript:
  333. return hosts
  334. (start, end) = subscript
  335. if end:
  336. if end == -1:
  337. end = len(hosts)-1
  338. return hosts[start:end+1]
  339. else:
  340. return [ hosts[start] ]
  341. def _enumerate_matches(self, pattern):
  342. """
  343. Returns a list of host names matching the given pattern according to the
  344. rules explained above in _match_one_pattern.
  345. """
  346. results = []
  347. hostnames = set()
  348. def __append_host_to_results(host):
  349. if host.name not in hostnames:
  350. hostnames.add(host.name)
  351. results.append(host)
  352. groups = self.get_groups()
  353. for group in groups.values():
  354. if pattern == 'all':
  355. for host in group.get_hosts():
  356. __append_host_to_results(host)
  357. else:
  358. if self._match(group.name, pattern) and group.name not in ('all', 'ungrouped'):
  359. for host in group.get_hosts():
  360. __append_host_to_results(host)
  361. else:
  362. matching_hosts = self._match_list(group.get_hosts(), 'name', pattern)
  363. for host in matching_hosts:
  364. __append_host_to_results(host)
  365. if pattern in C.LOCALHOST and len(results) == 0:
  366. new_host = self._create_implicit_localhost(pattern)
  367. results.append(new_host)
  368. return results
  369. def _create_implicit_localhost(self, pattern):
  370. new_host = Host(pattern)
  371. new_host.address = "127.0.0.1"
  372. new_host.vars = self.get_host_vars(new_host)
  373. new_host.set_variable("ansible_connection", "local")
  374. if "ansible_python_interpreter" not in new_host.vars:
  375. new_host.set_variable("ansible_python_interpreter", sys.executable)
  376. self.get_group("ungrouped").add_host(new_host)
  377. return new_host
  378. def clear_pattern_cache(self):
  379. ''' called exclusively by the add_host plugin to allow patterns to be recalculated '''
  380. global HOSTS_PATTERNS_CACHE
  381. HOSTS_PATTERNS_CACHE = {}
  382. self._pattern_cache = {}
  383. def groups_for_host(self, host):
  384. if host in self._hosts_cache:
  385. return self._hosts_cache[host].get_groups()
  386. else:
  387. return []
  388. def get_groups(self):
  389. return self.groups
  390. def get_host(self, hostname):
  391. if hostname not in self._hosts_cache:
  392. self._hosts_cache[hostname] = self._get_host(hostname)
  393. if hostname in C.LOCALHOST:
  394. for host in C.LOCALHOST.difference((hostname,)):
  395. self._hosts_cache[host] = self._hosts_cache[hostname]
  396. return self._hosts_cache[hostname]
  397. def _get_host(self, hostname):
  398. if hostname in C.LOCALHOST:
  399. for host in self.get_group('all').get_hosts():
  400. if host.name in C.LOCALHOST:
  401. return host
  402. return self._create_implicit_localhost(hostname)
  403. matching_host = None
  404. for group in self.groups.values():
  405. for host in group.get_hosts():
  406. if hostname == host.name:
  407. matching_host = host
  408. self._hosts_cache[host.name] = host
  409. return matching_host
  410. def get_group(self, groupname):
  411. return self.groups.get(groupname)
  412. def get_group_variables(self, groupname, update_cached=False, vault_password=None):
  413. if groupname not in self._vars_per_group or update_cached:
  414. self._vars_per_group[groupname] = self._get_group_variables(groupname, vault_password=vault_password)
  415. return self._vars_per_group[groupname]
  416. def _get_group_variables(self, groupname, vault_password=None):
  417. group = self.get_group(groupname)
  418. if group is None:
  419. raise Exception("group not found: %s" % groupname)
  420. vars = {}
  421. # plugin.get_group_vars retrieves just vars for specific group
  422. vars_results = [ plugin.get_group_vars(group, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'get_group_vars')]
  423. for updated in vars_results:
  424. if updated is not None:
  425. vars = combine_vars(vars, updated)
  426. # Read group_vars/ files
  427. vars = combine_vars(vars, self.get_group_vars(group))
  428. return vars
  429. def get_vars(self, hostname, update_cached=False, vault_password=None):
  430. host = self.get_host(hostname)
  431. if not host:
  432. raise AnsibleError("no vars as host is not in inventory: %s" % hostname)
  433. return host.get_vars()
  434. def get_host_variables(self, hostname, update_cached=False, vault_password=None):
  435. if hostname not in self._vars_per_host or update_cached:
  436. self._vars_per_host[hostname] = self._get_host_variables(hostname, vault_password=vault_password)
  437. return self._vars_per_host[hostname]
  438. def _get_host_variables(self, hostname, vault_password=None):
  439. host = self.get_host(hostname)
  440. if host is None:
  441. raise AnsibleError("no host vars as host is not in inventory: %s" % hostname)
  442. vars = {}
  443. # plugin.run retrieves all vars (also from groups) for host
  444. vars_results = [ plugin.run(host, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'run')]
  445. for updated in vars_results:
  446. if updated is not None:
  447. vars = combine_vars(vars, updated)
  448. # plugin.get_host_vars retrieves just vars for specific host
  449. vars_results = [ plugin.get_host_vars(host, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'get_host_vars')]
  450. for updated in vars_results:
  451. if updated is not None:
  452. vars = combine_vars(vars, updated)
  453. # still need to check InventoryParser per host vars
  454. # which actually means InventoryScript per host,
  455. # which is not performant
  456. if self.parser is not None:
  457. vars = combine_vars(vars, self.parser.get_host_variables(host))
  458. # Read host_vars/ files
  459. vars = combine_vars(vars, self.get_host_vars(host))
  460. return vars
  461. def add_group(self, group):
  462. if group.name not in self.groups:
  463. self.groups[group.name] = group
  464. else:
  465. raise AnsibleError("group already in inventory: %s" % group.name)
  466. def list_hosts(self, pattern="all"):
  467. """ return a list of hostnames for a pattern """
  468. result = [ h for h in self.get_hosts(pattern) ]
  469. if len(result) == 0 and pattern in C.LOCALHOST:
  470. result = [pattern]
  471. return result
  472. def list_groups(self):
  473. return sorted(self.groups.keys(), key=lambda x: x)
  474. def restrict_to_hosts(self, restriction):
  475. """
  476. Restrict list operations to the hosts given in restriction. This is used
  477. to batch serial operations in main playbook code, don't use this for other
  478. reasons.
  479. """
  480. if restriction is None:
  481. return
  482. elif not isinstance(restriction, list):
  483. restriction = [ restriction ]
  484. self._restriction = restriction
  485. def subset(self, subset_pattern):
  486. """
  487. Limits inventory results to a subset of inventory that matches a given
  488. pattern, such as to select a given geographic of numeric slice amongst
  489. a previous 'hosts' selection that only select roles, or vice versa.
  490. Corresponds to --limit parameter to ansible-playbook
  491. """
  492. if subset_pattern is None:
  493. self._subset = None
  494. else:
  495. subset_patterns = Inventory.split_host_pattern(subset_pattern)
  496. results = []
  497. # allow Unix style @filename data
  498. for x in subset_patterns:
  499. if x.startswith("@"):
  500. fd = open(x[1:])
  501. results.extend(fd.read().split("\n"))
  502. fd.close()
  503. else:
  504. results.append(x)
  505. self._subset = results
  506. def remove_restriction(self):
  507. """ Do not restrict list operations """
  508. self._restriction = None
  509. def is_file(self):
  510. """
  511. Did inventory come from a file? We don't use the equivalent loader
  512. methods in inventory, due to the fact that the loader does an implict
  513. DWIM on the path, which may be incorrect for inventory paths relative
  514. to the playbook basedir.
  515. """
  516. if not isinstance(self.host_list, string_types):
  517. return False
  518. return os.path.isfile(self.host_list) or self.host_list == os.devnull
  519. def is_directory(self, path):
  520. """
  521. Is the inventory host list a directory? Same caveat for here as with
  522. the is_file() method above.
  523. """
  524. if not isinstance(self.host_list, string_types):
  525. return False
  526. return os.path.isdir(path)
  527. def basedir(self):
  528. """ if inventory came from a file, what's the directory? """
  529. dname = self.host_list
  530. if self.is_directory(self.host_list):
  531. dname = self.host_list
  532. elif not self.is_file():
  533. dname = None
  534. else:
  535. dname = os.path.dirname(self.host_list)
  536. if dname is None or dname == '' or dname == '.':
  537. dname = os.getcwd()
  538. if dname:
  539. dname = os.path.abspath(dname)
  540. return dname
  541. def src(self):
  542. """ if inventory came from a file, what's the directory and file name? """
  543. if not self.is_file():
  544. return None
  545. return self.host_list
  546. def playbook_basedir(self):
  547. """ returns the directory of the current playbook """
  548. return self._playbook_basedir
  549. def set_playbook_basedir(self, dir_name):
  550. """
  551. sets the base directory of the playbook so inventory can use it as a
  552. basedir for host_ and group_vars, and other things.
  553. """
  554. # Only update things if dir is a different playbook basedir
  555. if dir_name != self._playbook_basedir:
  556. self._playbook_basedir = dir_name
  557. # get group vars from group_vars/ files
  558. # TODO: excluding the new_pb_basedir directory may result in group_vars
  559. # files loading more than they should, however with the file caching
  560. # we do this shouldn't be too much of an issue. Still, this should
  561. # be fixed at some point to allow a "first load" to touch all of the
  562. # directories, then later runs only touch the new basedir specified
  563. for group in self.groups.values():
  564. #group.vars = combine_vars(group.vars, self.get_group_vars(group, new_pb_basedir=True))
  565. group.vars = combine_vars(group.vars, self.get_group_vars(group))
  566. # get host vars from host_vars/ files
  567. for host in self.get_hosts():
  568. #host.vars = combine_vars(host.vars, self.get_host_vars(host, new_pb_basedir=True))
  569. host.vars = combine_vars(host.vars, self.get_host_vars(host))
  570. # invalidate cache
  571. self._vars_per_host = {}
  572. self._vars_per_group = {}
  573. def get_host_vars(self, host, new_pb_basedir=False):
  574. """ Read host_vars/ files """
  575. return self._get_hostgroup_vars(host=host, group=None, new_pb_basedir=new_pb_basedir)
  576. def get_group_vars(self, group, new_pb_basedir=False):
  577. """ Read group_vars/ files """
  578. return self._get_hostgroup_vars(host=None, group=group, new_pb_basedir=new_pb_basedir)
  579. def _get_hostgroup_vars(self, host=None, group=None, new_pb_basedir=False):
  580. """
  581. Loads variables from group_vars/<groupname> and host_vars/<hostname> in directories parallel
  582. to the inventory base directory or in the same directory as the playbook. Variables in the playbook
  583. dir will win over the inventory dir if files are in both.
  584. """
  585. results = {}
  586. scan_pass = 0
  587. _basedir = self.basedir()
  588. # look in both the inventory base directory and the playbook base directory
  589. # unless we do an update for a new playbook base dir
  590. if not new_pb_basedir:
  591. basedirs = [_basedir, self._playbook_basedir]
  592. else:
  593. basedirs = [self._playbook_basedir]
  594. for basedir in basedirs:
  595. # this can happen from particular API usages, particularly if not run
  596. # from /usr/bin/ansible-playbook
  597. if basedir in ('', None):
  598. basedir = './'
  599. scan_pass = scan_pass + 1
  600. # it's not an eror if the directory does not exist, keep moving
  601. if not os.path.exists(basedir):
  602. continue
  603. # save work of second scan if the directories are the same
  604. if _basedir == self._playbook_basedir and scan_pass != 1:
  605. continue
  606. if group and host is None:
  607. # load vars in dir/group_vars/name_of_group
  608. base_path = os.path.abspath(os.path.join(to_unicode(basedir, errors='strict'), "group_vars/%s" % group.name))
  609. results = combine_vars(results, self._variable_manager.add_group_vars_file(base_path, self._loader))
  610. elif host and group is None:
  611. # same for hostvars in dir/host_vars/name_of_host
  612. base_path = os.path.abspath(os.path.join(to_unicode(basedir, errors='strict'), "host_vars/%s" % host.name))
  613. results = combine_vars(results, self._variable_manager.add_host_vars_file(base_path, self._loader))
  614. # all done, results is a dictionary of variables for this particular host.
  615. return results
  616. def refresh_inventory(self):
  617. self.clear_pattern_cache()
  618. self._hosts_cache = {}
  619. self._vars_per_host = {}
  620. self._vars_per_group = {}
  621. self.groups = {}
  622. self.parse_inventory(self.host_list)