Coverage for lib/ansible/inventory/manager.py : 60%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#############################################
except ImportError: from ansible.utils.display import Display display = Display()
''' takes a list of patterns and reorders them by modifier to apply them consistently '''
# FIXME: this goes away if we apply patterns incrementally or by groups pattern_exclude.append(p) pattern_intersection.append(p)
# if no regular pattern was given, hence only exclude and/or intersection # make that magically work pattern_regular = ['all']
# when applying the host selectors, run those without the "&" or "!" # first, then the &s, then the !s.
""" Takes a string containing host patterns separated by commas (or a list thereof) and returns a list of single patterns (which may not contain commas). Whitespace is ignored.
Also accepts ':' as a separator for backwards compatibility, but it is not recommended due to the conflict with IPv6 addresses and host ranges.
Example: 'a,b[1], c[2:3] , d' -> ['a', 'b[1]', 'c[2:3]', 'd'] """
pattern = to_native(pattern)
# If it's got commas in it, we'll treat it as a straightforward # comma-separated list of patterns. patterns = pattern.split(',')
# If it doesn't, it could still be a single pattern. This accounts for # non-separator uses of colons: IPv6 addresses and [x:y] host ranges. else: except Exception: # The only other case we accept is a ':'-separated list of patterns. # This mishandles IPv6 addresses, and is retained only for backwards # compatibility. patterns = re.findall( r'''(?: # We want to match something comprising: [^\s:\[\]] # (anything other than whitespace or ':[]' | # ...or... \[[^\]]*\] # a single complete bracketed expression) )+ # occurring once or more ''', pattern, re.X )
''' Creates and manages inventory '''
# base objects
# a list of host(names) to contain current inquiries to
# caches
# the inventory dirs, files, script paths or lists of hosts self._sources = [] self._sources = [sources] else:
# get to work!
def localhost(self): return self._inventory.localhost
def groups(self):
def hosts(self):
return self._inventory.get_vars(args, kwargs)
return self._inventory.add_host(host, group, port)
return self._inventory.add_group(group)
self.clear_caches() return self._inventory.reconcile_inventory()
return self._inventory.get_host(hostname)
''' sets up loaded inventory plugins for usage '''
else: display.warning('Failed to load inventory plugin, skipping %s' % name)
raise AnsibleError("No inventory plugins available to generate inventory, make sure you have at least one whitelisted.")
''' iterate over inventory sources and parse each one to populate it'''
# allow for multiple inventory parsing
# do post processing else: if C.INVENTORY_UNPARSED_IS_FAILED: raise AnsibleError("No inventory was parsed, please check your configuration and options.") else: display.warning("No inventory was parsed, only implicit localhost is available")
''' Generate or update inventory for the source provided '''
# process directories as a collection of inventories display.debug(u'Searching for inventory files in directory: %s' % source) for i in sorted(os.listdir(b_source)):
display.debug(u'Considering %s' % i) # Skip hidden files and stuff we explicitly ignore if IGNORED.search(i): continue
# recursively deal with directory entries fullpath = os.path.join(b_source, i) parsed_this_one = self.parse_source(to_native(fullpath), cache=cache) display.debug(u'parsed %s as %s' % (fullpath, parsed_this_one)) if not parsed: parsed = parsed_this_one else: # left with strings or files, let plugins figure it out
# set so new hosts can use for inventory_file/dir vasr
# get inventory plugins if needed, there should always be at least one generator self._setup_inventory_plugins()
# try source with each plugin
# initialize # in case plugin fails 1/2 way we dont want partial inventory except Exception as e: display.debug('%s failed to parse %s' % (plugin_name, to_text(source))) failures.append({'src': source, 'plugin': plugin_name, 'exc': e}) else: else: if not parsed and failures: # only if no plugin processed files should we show errors. for fail in failures: display.warning(u'\n* Failed to parse %s with %s plugin: %s' % (to_text(fail['src']), fail['plugin'], to_text(fail['exc']))) if hasattr(fail['exc'], 'tb'): display.vvv(to_text(fail['exc'].tb)) display.warning("Unable to parse %s as an inventory source" % to_text(source))
# clear up, jic
''' clear all caches ''' self._hosts_patterns_cache = {} self._pattern_cache = {} # FIXME: flush inventory cache
''' recalculate inventory '''
self.clear_caches() self._inventory = InventoryData() self.parse_sources(cache=False)
# compile patterns else: pattern = re.compile(pattern_str[1:]) except Exception: raise AnsibleError('Invalid host list pattern: %s' % pattern_str)
# apply patterns
""" Takes a pattern or list of patterns and returns a list of matching inventory host names, taking into account any active restrictions or applied subsets """
# Check if pattern already computed else:
pattern_hash += ":%s" % to_native(self._subset)
# mainly useful for hostvars[host] access # exclude hosts not in a subset, if defined subset = self._evaluate_patterns(self._subset) hosts = [h for h in hosts if h in subset]
# exclude hosts mentioned in any restriction (ex: failed hosts)
# sort hosts list if needed (should only happen when called from strategy) from operator import attrgetter hosts = sorted(self._hosts_patterns_cache[pattern_hash][:], key=attrgetter('name'), reverse=(order == 'reverse_sorted')) hosts = sorted(self._hosts_patterns_cache[pattern_hash][:], reverse=True) else: from random import shuffle shuffle(hosts) AnsibleOptionsError("Invalid 'order' specified for inventory hosts: %s" % order)
""" Takes a list of patterns and returns a list of matching host names, taking into account any negative and intersection patterns. """
# avoid resolving a pattern that is a plain host hosts.append(self._inventory.get_host(p)) else: hosts = [h for h in hosts if h not in frozenset(that)] hosts = [h for h in hosts if h in frozenset(that)] else:
""" Takes a single pattern and returns a list of matching host names. Ignores intersection (&) and exclusion (!) specifiers.
The pattern may be:
1. A regex starting with ~, e.g. '~[abc]*' 2. A shell glob pattern with ?/*/[chars]/[!chars], e.g. 'foo*' 3. An ordinary word that matches itself only, e.g. 'foo'
The pattern is matched using the following rules:
1. If it's 'all', it matches all hosts in all groups. 2. Otherwise, for each known group name: (a) if it matches the group name, the results include all hosts in the group or any of its children. (b) otherwise, if it matches any hosts in the group, the results include the matching hosts.
This means that 'foo*' may match one or more groups (thus including all hosts therein) but also hosts in other groups.
The built-in groups 'all' and 'ungrouped' are special. No pattern can match these group names (though 'all' behaves as though it matches, as described above). The word 'ungrouped' can match a host of that name, and patterns like 'ungr*' and 'al*' can match either hosts or groups other than all and ungrouped.
If the pattern matches one or more group names according to these rules, it may have an optional range suffix to select a subset of the results. This is allowed only if the pattern is not a regex, i.e. '~foo[1]' does not work (the [1] is interpreted as part of the regex), but 'foo*[1]' would work if 'foo*' matched the name of one or more groups.
Duplicate matches are always eliminated from the results. """
pattern = pattern[1:]
except IndexError: raise AnsibleError("No hosts matched the subscripted pattern '%s'" % pattern)
""" Takes a pattern, checks if it has a subscript, and returns the pattern without the subscript and a (start,end) tuple representing the given subscript (or None if there is no subscript).
Validates that the subscript is in the right syntax, but doesn't make sure the actual indices make sense in context. """
# Do not parse regexes for enumeration info return (pattern, None)
# We want a pattern followed by an integer or range subscript. # (We can't be more restrictive about the expression because the # fnmatch semantics permit [\[:\]] to occur.)
r'''^ (.+) # A pattern expression ending with... \[(?: # A [subscript] expression comprising: (-?[0-9]+)| # A single positive or negative number ([0-9]+)([:-]) # Or an x:y or x: range. ([0-9]*) )\] $ ''', re.X )
(pattern, idx, start, sep, end) = m.groups() if idx: subscript = (int(idx), None) else: if not end: end = -1 subscript = (int(start), int(end)) if sep == '-': display.warning("Use [x:y] inclusive subscripts instead of [x-y] which has been removed")
""" Takes a list of hosts and a (start,end) tuple and returns the subset of hosts based on the subscript (which may be None to return all hosts). """
(start, end) = subscript
if end: if end == -1: end = len(hosts) - 1 return hosts[start:end + 1] else: return [hosts[start]]
""" Returns a list of host names matching the given pattern according to the rules explained above in _match_one_pattern. """
# check if pattern matches group
# check hosts if no groups matched or it is a regex/glob pattern # pattern might match host matching_hosts = self._match_list(self._inventory.hosts, pattern) if matching_hosts: for hostname in matching_hosts: results.append(self._inventory.hosts[hostname])
# get_host autocreates implicit when needed implicit = self._inventory.get_host(pattern) if implicit: results.append(implicit)
display.warning("Could not match supplied host pattern, ignoring: %s" % pattern)
""" return a list of hostnames for a pattern """ # FIXME: cache?
# allow implicit localhost if pattern matches and no other results result = [pattern]
# FIXME: cache? return sorted(self._inventory.groups.keys(), key=lambda x: x)
""" Restrict list operations to the hosts given in restriction. This is used to batch serial operations in main playbook code, don't use this for other reasons. """ return restriction = [restriction]
""" Limits inventory results to a subset of inventory that matches a given pattern, such as to select a given geographic of numeric slice amongst a previous 'hosts' selection that only select roles, or vice versa. Corresponds to --limit parameter to ansible-playbook """ else: subset_patterns = split_host_pattern(subset_pattern) results = [] # allow Unix style @filename data for x in subset_patterns: if x.startswith("@"): fd = open(x[1:]) results.extend(fd.read().split("\n")) fd.close() else: results.append(x) self._subset = results
""" Do not restrict list operations """
self._pattern_cache = {} |