2014-01-04 18:31:44 +00:00
|
|
|
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
|
2012-04-13 12:39:54 +00:00
|
|
|
#
|
|
|
|
# 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/>.
|
|
|
|
|
|
|
|
#############################################
|
2015-05-04 02:47:26 +00:00
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
|
|
|
|
2012-04-13 12:39:54 +00:00
|
|
|
import fnmatch
|
2012-05-06 18:47:05 +00:00
|
|
|
import os
|
2014-01-20 23:26:14 +00:00
|
|
|
import sys
|
2012-11-27 15:36:58 +00:00
|
|
|
import re
|
2015-05-04 02:47:26 +00:00
|
|
|
import stat
|
2013-10-07 19:06:15 +00:00
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
from ansible import constants as C
|
2015-07-18 19:24:44 +00:00
|
|
|
from ansible.errors import AnsibleError
|
2015-05-04 02:47:26 +00:00
|
|
|
|
2015-07-18 19:24:44 +00:00
|
|
|
from ansible.inventory.dir import InventoryDirectory, get_file_parser
|
2012-05-25 23:34:13 +00:00
|
|
|
from ansible.inventory.group import Group
|
|
|
|
from ansible.inventory.host import Host
|
2015-05-04 02:47:26 +00:00
|
|
|
from ansible.plugins import vars_loader
|
|
|
|
from ansible.utils.vars import combine_vars
|
2012-04-13 12:39:54 +00:00
|
|
|
|
2015-08-13 18:50:28 +00:00
|
|
|
try:
|
|
|
|
from __main__ import display
|
|
|
|
except ImportError:
|
|
|
|
from ansible.utils.display import Display
|
|
|
|
display = Display()
|
|
|
|
|
2012-04-13 12:39:54 +00:00
|
|
|
class Inventory(object):
|
2012-08-07 00:07:02 +00:00
|
|
|
"""
|
2012-05-05 20:31:03 +00:00
|
|
|
Host inventory for ansible.
|
2012-04-13 12:39:54 +00:00
|
|
|
"""
|
|
|
|
|
2015-08-13 00:36:38 +00:00
|
|
|
#__slots__ = [ 'host_list', 'groups', '_restriction', '_subset',
|
2015-06-02 01:02:15 +00:00
|
|
|
# 'parser', '_vars_per_host', '_vars_per_group', '_hosts_cache', '_groups_list',
|
|
|
|
# '_pattern_cache', '_vault_password', '_vars_plugins', '_playbook_basedir']
|
2012-07-22 15:40:02 +00:00
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
def __init__(self, loader, variable_manager, host_list=C.DEFAULT_HOST_LIST):
|
2012-04-13 12:39:54 +00:00
|
|
|
|
2012-05-08 04:27:37 +00:00
|
|
|
# the host file file, or script path, or list of hosts
|
|
|
|
# if a list, inventory data will NOT be loaded
|
2012-05-06 18:47:05 +00:00
|
|
|
self.host_list = host_list
|
2015-05-04 02:47:26 +00:00
|
|
|
self._loader = loader
|
|
|
|
self._variable_manager = variable_manager
|
2012-05-08 03:16:20 +00:00
|
|
|
|
2012-07-22 15:53:19 +00:00
|
|
|
# caching to avoid repeated calculations, particularly with
|
|
|
|
# external inventory scripts.
|
2012-08-07 00:07:02 +00:00
|
|
|
|
2012-07-22 15:53:19 +00:00
|
|
|
self._vars_per_host = {}
|
|
|
|
self._vars_per_group = {}
|
|
|
|
self._hosts_cache = {}
|
2015-05-14 14:50:22 +00:00
|
|
|
self._groups_list = {}
|
2013-10-12 02:24:37 +00:00
|
|
|
self._pattern_cache = {}
|
2015-07-18 19:24:44 +00:00
|
|
|
self._vars_plugins = []
|
2014-10-24 15:40:34 +00:00
|
|
|
self._groups_cache = {}
|
2012-07-22 15:53:19 +00:00
|
|
|
|
2014-03-19 10:09:38 +00:00
|
|
|
# to be set by calling set_playbook_basedir by playbook code
|
2013-06-01 14:38:16 +00:00
|
|
|
self._playbook_basedir = None
|
|
|
|
|
2012-05-08 03:16:20 +00:00
|
|
|
# the inventory object holds a list of groups
|
2012-05-05 20:31:03 +00:00
|
|
|
self.groups = []
|
2012-08-07 00:07:02 +00:00
|
|
|
|
2012-05-08 03:16:20 +00:00
|
|
|
# a list of host(names) to contain current inquiries to
|
2012-05-05 20:31:03 +00:00
|
|
|
self._restriction = None
|
2012-08-10 06:45:29 +00:00
|
|
|
self._subset = None
|
2012-05-08 03:16:20 +00:00
|
|
|
|
2015-07-18 19:24:44 +00:00
|
|
|
self.parse_inventory(host_list)
|
|
|
|
|
|
|
|
def parse_inventory(self, host_list):
|
|
|
|
|
2013-05-23 16:33:29 +00:00
|
|
|
if isinstance(host_list, basestring):
|
2013-05-23 16:37:30 +00:00
|
|
|
if "," in host_list:
|
2012-07-15 13:32:47 +00:00
|
|
|
host_list = host_list.split(",")
|
2012-07-18 20:56:41 +00:00
|
|
|
host_list = [ h for h in host_list if h and h.strip() ]
|
2012-05-10 03:26:45 +00:00
|
|
|
|
2013-09-25 12:59:11 +00:00
|
|
|
if host_list is None:
|
|
|
|
self.parser = None
|
|
|
|
elif isinstance(host_list, list):
|
2013-03-04 11:37:15 +00:00
|
|
|
self.parser = None
|
2012-05-08 04:27:37 +00:00
|
|
|
all = Group('all')
|
|
|
|
self.groups = [ all ]
|
2013-08-19 20:22:44 +00:00
|
|
|
ipv6_re = re.compile('\[([a-f:A-F0-9]*[%[0-z]+]?)\](?::(\d+))?')
|
2012-05-08 04:27:37 +00:00
|
|
|
for x in host_list:
|
2013-08-18 21:02:28 +00:00
|
|
|
m = ipv6_re.match(x)
|
|
|
|
if m:
|
|
|
|
all.add_host(Host(m.groups()[0], m.groups()[1]))
|
2012-05-08 04:27:37 +00:00
|
|
|
else:
|
2013-08-18 21:02:28 +00:00
|
|
|
if ":" in x:
|
|
|
|
tokens = x.rsplit(":", 1)
|
2014-05-03 16:40:05 +00:00
|
|
|
# if there is ':' in the address, then this is an ipv6
|
2013-08-18 21:02:28 +00:00
|
|
|
if ':' in tokens[0]:
|
|
|
|
all.add_host(Host(x))
|
|
|
|
else:
|
|
|
|
all.add_host(Host(tokens[0], tokens[1]))
|
|
|
|
else:
|
|
|
|
all.add_host(Host(x))
|
2013-02-04 04:19:37 +00:00
|
|
|
elif os.path.exists(host_list):
|
2015-07-18 19:24:44 +00:00
|
|
|
#TODO: switch this to a plugin loader and a 'condition' per plugin on which it should be tried, restoring 'inventory pllugins'
|
2013-02-27 20:24:45 +00:00
|
|
|
if os.path.isdir(host_list):
|
2013-02-28 15:58:09 +00:00
|
|
|
# Ensure basedir is inside the directory
|
2015-07-18 19:24:44 +00:00
|
|
|
host_list = os.path.join(self.host_list, "")
|
2015-05-04 02:47:26 +00:00
|
|
|
self.parser = InventoryDirectory(loader=self._loader, filename=host_list)
|
2012-08-07 00:07:02 +00:00
|
|
|
else:
|
2015-08-13 15:05:20 +00:00
|
|
|
self.parser = get_file_parser(host_list, self._loader)
|
2015-07-18 19:24:44 +00:00
|
|
|
vars_loader.add_directory(self.basedir(), with_subdir=True)
|
2013-02-28 15:58:09 +00:00
|
|
|
|
2015-07-18 19:24:44 +00:00
|
|
|
if self.parser:
|
|
|
|
self.groups = self.parser.groups.values()
|
|
|
|
else:
|
|
|
|
# should never happen, but JIC
|
|
|
|
raise AnsibleError("Unable to parse %s as an inventory source" % host_list)
|
2012-08-07 00:07:02 +00:00
|
|
|
|
2015-07-18 19:24:44 +00:00
|
|
|
self._vars_plugins = [ x for x in vars_loader.all(self) ]
|
2013-04-20 13:59:40 +00:00
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
# FIXME: shouldn't be required, since the group/host vars file
|
|
|
|
# management will be done in VariableManager
|
2014-03-21 18:05:18 +00:00
|
|
|
# get group vars from group_vars/ files and vars plugins
|
2014-03-17 17:05:30 +00:00
|
|
|
for group in self.groups:
|
2015-05-04 02:47:26 +00:00
|
|
|
group.vars = combine_vars(group.vars, self.get_group_variables(group.name))
|
2014-03-17 17:05:30 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
# get host vars from host_vars/ files and vars plugins
|
2014-03-17 17:05:30 +00:00
|
|
|
for host in self.get_hosts():
|
2015-05-04 02:47:26 +00:00
|
|
|
host.vars = combine_vars(host.vars, self.get_host_variables(host.name))
|
2014-03-17 17:05:30 +00:00
|
|
|
|
2013-04-20 13:59:40 +00:00
|
|
|
|
2012-05-05 20:31:03 +00:00
|
|
|
def _match(self, str, pattern_str):
|
2014-08-14 17:13:40 +00:00
|
|
|
try:
|
|
|
|
if pattern_str.startswith('~'):
|
|
|
|
return re.search(pattern_str[1:], str)
|
|
|
|
else:
|
|
|
|
return fnmatch.fnmatch(str, pattern_str)
|
|
|
|
except Exception, e:
|
2015-07-18 19:24:44 +00:00
|
|
|
raise AnsibleError('invalid host pattern: %s' % pattern_str)
|
2012-05-05 20:31:03 +00:00
|
|
|
|
2014-06-27 03:40:31 +00:00
|
|
|
def _match_list(self, items, item_attr, pattern_str):
|
|
|
|
results = []
|
2014-08-14 17:13:40 +00:00
|
|
|
try:
|
|
|
|
if not pattern_str.startswith('~'):
|
2014-08-14 17:26:52 +00:00
|
|
|
pattern = re.compile(fnmatch.translate(pattern_str))
|
2014-08-14 17:13:40 +00:00
|
|
|
else:
|
|
|
|
pattern = re.compile(pattern_str[1:])
|
|
|
|
except Exception, e:
|
2015-07-18 19:24:44 +00:00
|
|
|
raise AnsibleError('invalid host pattern: %s' % pattern_str)
|
2014-08-14 17:13:40 +00:00
|
|
|
|
2014-06-27 03:40:31 +00:00
|
|
|
for item in items:
|
2014-08-14 17:26:52 +00:00
|
|
|
if pattern.match(getattr(item, item_attr)):
|
2014-06-27 03:40:31 +00:00
|
|
|
results.append(item)
|
|
|
|
return results
|
|
|
|
|
2015-08-13 11:02:11 +00:00
|
|
|
def _split_pattern(self, pattern):
|
|
|
|
"""
|
|
|
|
takes e.g. "webservers[0:5]:dbservers:others"
|
|
|
|
and returns ["webservers[0:5]", "dbservers", "others"]
|
|
|
|
"""
|
|
|
|
|
|
|
|
term = re.compile(
|
|
|
|
r'''(?: # We want to match something comprising:
|
|
|
|
[^:\[\]] # (anything other than ':', '[', or ']'
|
|
|
|
| # ...or...
|
|
|
|
\[[^\]]*\] # a single complete bracketed expression)
|
|
|
|
)* # repeated as many times as possible
|
|
|
|
''', re.X
|
|
|
|
)
|
|
|
|
|
|
|
|
return [x for x in term.findall(pattern) if x]
|
|
|
|
|
2012-05-05 20:31:03 +00:00
|
|
|
def get_hosts(self, pattern="all"):
|
2012-08-11 15:36:59 +00:00
|
|
|
"""
|
2015-08-13 12:11:47 +00:00
|
|
|
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
|
2012-08-11 15:36:59 +00:00
|
|
|
"""
|
|
|
|
|
2015-08-13 11:51:53 +00:00
|
|
|
# Enumerate all hosts matching the given pattern (which may be
|
|
|
|
# either a list of patterns or a string like 'pat1:pat2').
|
2012-09-11 17:00:40 +00:00
|
|
|
if isinstance(pattern, list):
|
2015-08-13 11:51:53 +00:00
|
|
|
pattern = ':'.join(pattern)
|
2015-08-13 18:50:28 +00:00
|
|
|
|
|
|
|
if ';' in pattern or ',' in pattern:
|
2015-08-14 05:25:13 +00:00
|
|
|
display.deprecated("Use ':' instead of ',' or ';' to separate host patterns", version=2.0, removed=True)
|
2015-08-13 18:50:28 +00:00
|
|
|
|
2015-08-13 11:51:53 +00:00
|
|
|
patterns = self._split_pattern(pattern)
|
2015-08-13 12:11:47 +00:00
|
|
|
hosts = self._evaluate_patterns(patterns)
|
2012-08-11 15:36:59 +00:00
|
|
|
|
|
|
|
# exclude hosts not in a subset, if defined
|
|
|
|
if self._subset:
|
2015-08-13 12:11:47 +00:00
|
|
|
subset = self._evaluate_patterns(self._subset)
|
2014-01-04 02:07:00 +00:00
|
|
|
hosts = [ h for h in hosts if h in subset ]
|
2012-08-11 15:36:59 +00:00
|
|
|
|
|
|
|
# exclude hosts mentioned in any restriction (ex: failed hosts)
|
|
|
|
if self._restriction is not None:
|
2015-05-04 02:47:26 +00:00
|
|
|
hosts = [ h for h in hosts if h in self._restriction ]
|
2012-08-11 15:36:59 +00:00
|
|
|
|
2013-10-07 19:06:15 +00:00
|
|
|
return hosts
|
2012-08-11 15:36:59 +00:00
|
|
|
|
2015-08-13 12:11:47 +00:00
|
|
|
def _evaluate_patterns(self, patterns):
|
2012-12-10 14:54:07 +00:00
|
|
|
"""
|
2015-08-13 12:11:47 +00:00
|
|
|
Takes a list of patterns and returns a list of matching host names,
|
|
|
|
taking into account any negative and intersection patterns.
|
2012-08-11 15:36:59 +00:00
|
|
|
"""
|
2013-08-08 16:07:57 +00:00
|
|
|
|
|
|
|
# Host specifiers should be sorted to ensure consistent behavior
|
|
|
|
pattern_regular = []
|
|
|
|
pattern_intersection = []
|
|
|
|
pattern_exclude = []
|
|
|
|
for p in patterns:
|
|
|
|
if p.startswith("!"):
|
|
|
|
pattern_exclude.append(p)
|
|
|
|
elif p.startswith("&"):
|
|
|
|
pattern_intersection.append(p)
|
2014-07-08 02:08:39 +00:00
|
|
|
elif p:
|
2013-08-08 16:07:57 +00:00
|
|
|
pattern_regular.append(p)
|
|
|
|
|
|
|
|
# if no regular pattern was given, hence only exclude and/or intersection
|
|
|
|
# make that magically work
|
|
|
|
if pattern_regular == []:
|
|
|
|
pattern_regular = ['all']
|
|
|
|
|
|
|
|
# when applying the host selectors, run those without the "&" or "!"
|
|
|
|
# first, then the &s, then the !s.
|
|
|
|
patterns = pattern_regular + pattern_intersection + pattern_exclude
|
2012-08-11 15:36:59 +00:00
|
|
|
|
2013-10-07 19:06:15 +00:00
|
|
|
hosts = []
|
|
|
|
|
2012-08-11 15:36:59 +00:00
|
|
|
for p in patterns:
|
2014-03-26 15:24:54 +00:00
|
|
|
# avoid resolving a pattern that is a plain host
|
|
|
|
if p in self._hosts_cache:
|
|
|
|
hosts.append(self.get_host(p))
|
2012-12-10 14:54:07 +00:00
|
|
|
else:
|
2015-08-13 12:11:47 +00:00
|
|
|
that = self._match_one_pattern(p)
|
2014-03-26 15:24:54 +00:00
|
|
|
if p.startswith("!"):
|
|
|
|
hosts = [ h for h in hosts if h not in that ]
|
|
|
|
elif p.startswith("&"):
|
|
|
|
hosts = [ h for h in hosts if h in that ]
|
|
|
|
else:
|
|
|
|
to_append = [ h for h in that if h.name not in [ y.name for y in hosts ] ]
|
|
|
|
hosts.extend(to_append)
|
2012-12-10 14:54:07 +00:00
|
|
|
return hosts
|
2012-08-11 15:36:59 +00:00
|
|
|
|
2015-08-13 12:11:47 +00:00
|
|
|
def _match_one_pattern(self, pattern):
|
2012-12-10 14:54:07 +00:00
|
|
|
"""
|
2015-08-13 12:11:47 +00:00
|
|
|
Takes a single pattern (i.e., not "p1:p2") and returns a list of
|
|
|
|
matching hosts names. Does not take negatives or intersections
|
|
|
|
into account.
|
2012-12-10 14:54:07 +00:00
|
|
|
"""
|
2012-08-11 15:36:59 +00:00
|
|
|
|
2013-10-12 02:24:37 +00:00
|
|
|
if pattern in self._pattern_cache:
|
|
|
|
return self._pattern_cache[pattern]
|
|
|
|
|
2012-12-10 14:54:07 +00:00
|
|
|
(name, enumeration_details) = self._enumeration_info(pattern)
|
|
|
|
hpat = self._hosts_in_unenumerated_pattern(name)
|
2013-10-12 02:24:37 +00:00
|
|
|
result = self._apply_ranges(pattern, hpat)
|
|
|
|
self._pattern_cache[pattern] = result
|
|
|
|
return result
|
2012-08-11 15:36:59 +00:00
|
|
|
|
|
|
|
def _enumeration_info(self, pattern):
|
|
|
|
"""
|
|
|
|
returns (pattern, limits) taking a regular pattern and finding out
|
|
|
|
which parts of it correspond to start/stop offsets. limits is
|
|
|
|
a tuple of (start, stop) or None
|
|
|
|
"""
|
|
|
|
|
2014-07-10 00:08:12 +00:00
|
|
|
# Do not parse regexes for enumeration info
|
|
|
|
if pattern.startswith('~'):
|
|
|
|
return (pattern, None)
|
|
|
|
|
2014-02-05 19:43:52 +00:00
|
|
|
# The regex used to match on the range, which can be [x] or [x-y].
|
2014-03-07 22:34:04 +00:00
|
|
|
pattern_re = re.compile("^(.*)\[([-]?[0-9]+)(?:(?:-)([0-9]+))?\](.*)$")
|
2014-02-05 19:43:52 +00:00
|
|
|
m = pattern_re.match(pattern)
|
|
|
|
if m:
|
|
|
|
(target, first, last, rest) = m.groups()
|
|
|
|
first = int(first)
|
|
|
|
if last:
|
2014-03-07 22:34:04 +00:00
|
|
|
if first < 0:
|
2015-07-18 19:24:44 +00:00
|
|
|
raise AnsibleError("invalid range: negative indices cannot be used as the first item in a range")
|
2014-02-05 19:43:52 +00:00
|
|
|
last = int(last)
|
|
|
|
else:
|
|
|
|
last = first
|
|
|
|
return (target, (first, last))
|
2013-01-07 17:20:09 +00:00
|
|
|
else:
|
2014-02-05 19:43:52 +00:00
|
|
|
return (pattern, None)
|
2012-08-11 15:36:59 +00:00
|
|
|
|
|
|
|
def _apply_ranges(self, pat, hosts):
|
2012-08-11 17:49:18 +00:00
|
|
|
"""
|
|
|
|
given a pattern like foo, that matches hosts, return all of hosts
|
|
|
|
given a pattern like foo[0:5], where foo matches hosts, return the first 6 hosts
|
|
|
|
"""
|
|
|
|
|
2014-03-03 21:23:27 +00:00
|
|
|
# If there are no hosts to select from, just return the
|
|
|
|
# empty set. This prevents trying to do selections on an empty set.
|
|
|
|
# issue#6258
|
|
|
|
if not hosts:
|
|
|
|
return hosts
|
|
|
|
|
2012-08-11 15:36:59 +00:00
|
|
|
(loose_pattern, limits) = self._enumeration_info(pat)
|
|
|
|
if not limits:
|
|
|
|
return hosts
|
2012-08-11 17:49:18 +00:00
|
|
|
|
|
|
|
(left, right) = limits
|
2013-10-07 19:06:15 +00:00
|
|
|
|
2012-08-11 17:49:18 +00:00
|
|
|
if left == '':
|
|
|
|
left = 0
|
|
|
|
if right == '':
|
|
|
|
right = 0
|
|
|
|
left=int(left)
|
|
|
|
right=int(right)
|
2014-03-07 22:34:04 +00:00
|
|
|
try:
|
|
|
|
if left != right:
|
|
|
|
return hosts[left:right]
|
|
|
|
else:
|
|
|
|
return [ hosts[left] ]
|
|
|
|
except IndexError:
|
2015-07-18 19:24:44 +00:00
|
|
|
raise AnsibleError("no hosts matching the pattern '%s' were found" % pat)
|
2012-08-11 15:36:59 +00:00
|
|
|
|
2014-01-30 18:45:19 +00:00
|
|
|
def _create_implicit_localhost(self, pattern):
|
|
|
|
new_host = Host(pattern)
|
|
|
|
new_host.set_variable("ansible_python_interpreter", sys.executable)
|
|
|
|
new_host.set_variable("ansible_connection", "local")
|
2015-05-04 02:47:26 +00:00
|
|
|
new_host.ipv4_address = '127.0.0.1'
|
|
|
|
|
2014-01-30 18:45:19 +00:00
|
|
|
ungrouped = self.get_group("ungrouped")
|
|
|
|
if ungrouped is None:
|
|
|
|
self.add_group(Group('ungrouped'))
|
|
|
|
ungrouped = self.get_group('ungrouped')
|
2014-08-19 14:33:59 +00:00
|
|
|
self.get_group('all').add_child_group(ungrouped)
|
2014-01-30 18:45:19 +00:00
|
|
|
ungrouped.add_host(new_host)
|
|
|
|
return new_host
|
|
|
|
|
2012-08-11 15:36:59 +00:00
|
|
|
def _hosts_in_unenumerated_pattern(self, pattern):
|
|
|
|
""" Get all host names matching the pattern """
|
|
|
|
|
2014-06-27 03:40:31 +00:00
|
|
|
results = []
|
2013-10-07 19:06:15 +00:00
|
|
|
hosts = []
|
2014-01-07 01:07:31 +00:00
|
|
|
hostnames = set()
|
2014-01-06 19:19:20 +00:00
|
|
|
|
2012-08-11 15:36:59 +00:00
|
|
|
# ignore any negative checks here, this is handled elsewhere
|
2012-12-10 14:54:07 +00:00
|
|
|
pattern = pattern.replace("!","").replace("&", "")
|
2012-05-05 20:31:03 +00:00
|
|
|
|
2014-06-27 03:40:31 +00:00
|
|
|
def __append_host_to_results(host):
|
2015-01-17 17:49:13 +00:00
|
|
|
if host.name not in hostnames:
|
2014-06-27 03:40:31 +00:00
|
|
|
hostnames.add(host.name)
|
|
|
|
results.append(host)
|
|
|
|
|
2013-10-12 02:24:37 +00:00
|
|
|
groups = self.get_groups()
|
|
|
|
for group in groups:
|
2014-06-27 03:40:31 +00:00
|
|
|
if pattern == 'all':
|
|
|
|
for host in group.get_hosts():
|
|
|
|
__append_host_to_results(host)
|
|
|
|
else:
|
2015-06-17 20:25:58 +00:00
|
|
|
if self._match(group.name, pattern) and group.name not in ('all', 'ungrouped'):
|
2014-06-27 03:40:31 +00:00
|
|
|
for host in group.get_hosts():
|
|
|
|
__append_host_to_results(host)
|
|
|
|
else:
|
|
|
|
matching_hosts = self._match_list(group.get_hosts(), 'name', pattern)
|
|
|
|
for host in matching_hosts:
|
|
|
|
__append_host_to_results(host)
|
2014-01-20 23:26:14 +00:00
|
|
|
|
2015-08-19 00:02:03 +00:00
|
|
|
if pattern in C.LOCALHOST and len(results) == 0:
|
2014-01-30 18:45:19 +00:00
|
|
|
new_host = self._create_implicit_localhost(pattern)
|
2014-01-20 23:26:14 +00:00
|
|
|
results.append(new_host)
|
2013-10-12 02:24:37 +00:00
|
|
|
return results
|
2012-05-05 20:31:03 +00:00
|
|
|
|
2013-10-11 20:36:48 +00:00
|
|
|
def clear_pattern_cache(self):
|
|
|
|
''' called exclusively by the add_host plugin to allow patterns to be recalculated '''
|
2013-10-12 02:24:37 +00:00
|
|
|
self._pattern_cache = {}
|
2013-10-11 20:36:48 +00:00
|
|
|
|
2012-08-14 23:48:33 +00:00
|
|
|
def groups_for_host(self, host):
|
2014-07-08 02:08:39 +00:00
|
|
|
if host in self._hosts_cache:
|
|
|
|
return self._hosts_cache[host].get_groups()
|
|
|
|
else:
|
|
|
|
return []
|
2012-08-14 23:48:33 +00:00
|
|
|
|
2012-09-07 22:07:52 +00:00
|
|
|
def groups_list(self):
|
|
|
|
if not self._groups_list:
|
|
|
|
groups = {}
|
|
|
|
for g in self.groups:
|
|
|
|
groups[g.name] = [h.name for h in g.get_hosts()]
|
|
|
|
ancestors = g.get_ancestors()
|
|
|
|
for a in ancestors:
|
2013-05-28 10:53:51 +00:00
|
|
|
if a.name not in groups:
|
|
|
|
groups[a.name] = [h.name for h in a.get_hosts()]
|
2012-09-07 22:07:52 +00:00
|
|
|
self._groups_list = groups
|
2014-10-24 15:40:34 +00:00
|
|
|
self._groups_cache = {}
|
2012-09-07 22:07:52 +00:00
|
|
|
return self._groups_list
|
|
|
|
|
2012-05-05 20:31:03 +00:00
|
|
|
def get_groups(self):
|
|
|
|
return self.groups
|
|
|
|
|
|
|
|
def get_host(self, hostname):
|
2012-07-22 15:53:19 +00:00
|
|
|
if hostname not in self._hosts_cache:
|
|
|
|
self._hosts_cache[hostname] = self._get_host(hostname)
|
2015-08-19 00:02:03 +00:00
|
|
|
if hostname in C.LOCALHOST:
|
|
|
|
for host in C.LOCALHOST.difference((hostname,)):
|
2015-08-03 20:29:54 +00:00
|
|
|
self._hosts_cache[host] = self._hosts_cache[hostname]
|
2012-07-22 15:53:19 +00:00
|
|
|
return self._hosts_cache[hostname]
|
|
|
|
|
|
|
|
def _get_host(self, hostname):
|
2015-08-19 00:02:03 +00:00
|
|
|
if hostname in C.LOCALHOST:
|
2013-05-08 18:11:40 +00:00
|
|
|
for host in self.get_group('all').get_hosts():
|
2015-08-19 00:02:03 +00:00
|
|
|
if host.name in C.LOCALHOST:
|
2012-05-05 20:31:03 +00:00
|
|
|
return host
|
2014-01-30 18:45:19 +00:00
|
|
|
return self._create_implicit_localhost(hostname)
|
2015-01-17 17:49:13 +00:00
|
|
|
matching_host = None
|
|
|
|
for group in self.groups:
|
|
|
|
for host in group.get_hosts():
|
|
|
|
if hostname == host.name:
|
|
|
|
matching_host = host
|
|
|
|
self._hosts_cache[host.name] = host
|
|
|
|
return matching_host
|
2012-05-05 20:31:03 +00:00
|
|
|
|
|
|
|
def get_group(self, groupname):
|
2014-10-24 15:40:34 +00:00
|
|
|
if not self._groups_cache:
|
|
|
|
for group in self.groups:
|
|
|
|
self._groups_cache[group.name] = group
|
|
|
|
|
|
|
|
return self._groups_cache.get(groupname)
|
2012-08-07 00:07:02 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
def get_group_variables(self, groupname, update_cached=False, vault_password=None):
|
|
|
|
if groupname not in self._vars_per_group or update_cached:
|
2014-03-17 17:05:30 +00:00
|
|
|
self._vars_per_group[groupname] = self._get_group_variables(groupname, vault_password=vault_password)
|
2012-07-22 15:53:19 +00:00
|
|
|
return self._vars_per_group[groupname]
|
|
|
|
|
2014-03-17 17:05:30 +00:00
|
|
|
def _get_group_variables(self, groupname, vault_password=None):
|
|
|
|
|
2012-05-05 20:31:03 +00:00
|
|
|
group = self.get_group(groupname)
|
|
|
|
if group is None:
|
2015-05-04 02:47:26 +00:00
|
|
|
raise Exception("group not found: %s" % groupname)
|
2012-05-05 20:31:03 +00:00
|
|
|
|
2014-03-17 17:05:30 +00:00
|
|
|
vars = {}
|
2014-03-21 18:05:18 +00:00
|
|
|
|
|
|
|
# plugin.get_group_vars retrieves just vars for specific group
|
2014-03-17 17:05:30 +00:00
|
|
|
vars_results = [ plugin.get_group_vars(group, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'get_group_vars')]
|
|
|
|
for updated in vars_results:
|
|
|
|
if updated is not None:
|
2015-05-04 02:47:26 +00:00
|
|
|
vars = combine_vars(vars, updated)
|
2014-03-21 18:05:18 +00:00
|
|
|
|
|
|
|
# Read group_vars/ files
|
2015-05-04 02:47:26 +00:00
|
|
|
vars = combine_vars(vars, self.get_group_vars(group))
|
2014-03-17 17:05:30 +00:00
|
|
|
|
|
|
|
return vars
|
2012-05-05 20:31:03 +00:00
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
def get_vars(self, hostname, update_cached=False, vault_password=None):
|
2014-08-19 12:55:57 +00:00
|
|
|
|
2014-10-10 06:18:18 +00:00
|
|
|
host = self.get_host(hostname)
|
|
|
|
if not host:
|
2015-05-04 02:47:26 +00:00
|
|
|
raise Exception("host not found: %s" % hostname)
|
|
|
|
return host.get_vars()
|
2014-08-19 12:55:57 +00:00
|
|
|
|
|
|
|
def get_host_variables(self, hostname, update_cached=False, vault_password=None):
|
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
if hostname not in self._vars_per_host or update_cached:
|
2014-08-19 12:55:57 +00:00
|
|
|
self._vars_per_host[hostname] = self._get_host_variables(hostname, vault_password=vault_password)
|
2012-07-22 15:53:19 +00:00
|
|
|
return self._vars_per_host[hostname]
|
|
|
|
|
2014-08-19 12:55:57 +00:00
|
|
|
def _get_host_variables(self, hostname, vault_password=None):
|
2012-05-06 18:47:05 +00:00
|
|
|
|
2012-10-19 14:26:12 +00:00
|
|
|
host = self.get_host(hostname)
|
|
|
|
if host is None:
|
2015-07-18 19:24:44 +00:00
|
|
|
raise AnsibleError("host not found: %s" % hostname)
|
2012-10-19 14:26:12 +00:00
|
|
|
|
2012-10-26 23:55:59 +00:00
|
|
|
vars = {}
|
2014-03-17 17:05:30 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
# plugin.run retrieves all vars (also from groups) for host
|
|
|
|
vars_results = [ plugin.run(host, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'run')]
|
2014-03-17 17:05:30 +00:00
|
|
|
for updated in vars_results:
|
|
|
|
if updated is not None:
|
2015-05-04 02:47:26 +00:00
|
|
|
vars = combine_vars(vars, updated)
|
2014-03-17 17:05:30 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
# plugin.get_host_vars retrieves just vars for specific host
|
|
|
|
vars_results = [ plugin.get_host_vars(host, vault_password=vault_password) for plugin in self._vars_plugins if hasattr(plugin, 'get_host_vars')]
|
2013-04-20 13:59:40 +00:00
|
|
|
for updated in vars_results:
|
2012-10-29 16:11:57 +00:00
|
|
|
if updated is not None:
|
2015-05-04 02:47:26 +00:00
|
|
|
vars = combine_vars(vars, updated)
|
2012-10-26 23:55:59 +00:00
|
|
|
|
2014-03-17 17:05:30 +00:00
|
|
|
# still need to check InventoryParser per host vars
|
|
|
|
# which actually means InventoryScript per host,
|
|
|
|
# which is not performant
|
2013-03-04 11:37:15 +00:00
|
|
|
if self.parser is not None:
|
2015-05-04 02:47:26 +00:00
|
|
|
vars = combine_vars(vars, self.parser.get_host_variables(host))
|
2014-03-17 17:05:30 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
# Read host_vars/ files
|
2015-05-04 02:47:26 +00:00
|
|
|
vars = combine_vars(vars, self.get_host_vars(host))
|
2014-03-21 18:05:18 +00:00
|
|
|
|
2012-10-26 23:55:59 +00:00
|
|
|
return vars
|
2012-05-05 20:31:03 +00:00
|
|
|
|
|
|
|
def add_group(self, group):
|
2014-03-10 12:06:04 +00:00
|
|
|
if group.name not in self.groups_list():
|
|
|
|
self.groups.append(group)
|
|
|
|
self._groups_list = None # invalidate internal cache
|
2014-10-24 15:40:34 +00:00
|
|
|
self._groups_cache = {}
|
2014-03-10 12:06:04 +00:00
|
|
|
else:
|
2015-07-18 19:24:44 +00:00
|
|
|
raise AnsibleError("group already in inventory: %s" % group.name)
|
2012-04-13 12:39:54 +00:00
|
|
|
|
|
|
|
def list_hosts(self, pattern="all"):
|
2014-01-20 23:26:14 +00:00
|
|
|
|
|
|
|
""" return a list of hostnames for a pattern """
|
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
result = [ h for h in self.get_hosts(pattern) ]
|
2015-08-19 00:02:03 +00:00
|
|
|
if len(result) == 0 and pattern in C.LOCALHOST:
|
2014-01-20 23:26:14 +00:00
|
|
|
result = [pattern]
|
|
|
|
return result
|
2012-05-05 20:31:03 +00:00
|
|
|
|
|
|
|
def list_groups(self):
|
2013-01-23 16:43:24 +00:00
|
|
|
return sorted([ g.name for g in self.groups ], key=lambda x: x)
|
2012-04-13 12:39:54 +00:00
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
def restrict_to_hosts(self, restriction):
|
2012-08-10 06:45:29 +00:00
|
|
|
"""
|
|
|
|
Restrict list operations to the hosts given in restriction. This is used
|
2015-08-13 00:36:38 +00:00
|
|
|
to batch serial operations in main playbook code, don't use this for other
|
2012-08-10 06:45:29 +00:00
|
|
|
reasons.
|
|
|
|
"""
|
2015-08-21 20:08:21 +00:00
|
|
|
if restriction is None:
|
|
|
|
return
|
|
|
|
elif not isinstance(restriction, list):
|
2012-07-15 13:32:47 +00:00
|
|
|
restriction = [ restriction ]
|
|
|
|
self._restriction = restriction
|
2012-04-13 12:39:54 +00:00
|
|
|
|
2012-08-10 06:45:29 +00:00
|
|
|
def subset(self, subset_pattern):
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
"""
|
|
|
|
if subset_pattern is None:
|
|
|
|
self._subset = None
|
|
|
|
else:
|
2015-08-14 05:25:13 +00:00
|
|
|
if ';' in subset_pattern or ',' in subset_pattern:
|
|
|
|
display.deprecated("Use ':' instead of ',' or ';' to separate host patterns", version=2.0, removed=True)
|
|
|
|
|
2015-08-13 11:51:53 +00:00
|
|
|
subset_patterns = self._split_pattern(subset_pattern)
|
2013-04-08 16:36:01 +00:00
|
|
|
results = []
|
|
|
|
# allow Unix style @filename data
|
2015-08-13 11:02:11 +00:00
|
|
|
for x in subset_patterns:
|
2013-04-10 20:37:49 +00:00
|
|
|
if x.startswith("@"):
|
|
|
|
fd = open(x[1:])
|
|
|
|
results.extend(fd.read().split("\n"))
|
|
|
|
fd.close()
|
|
|
|
else:
|
|
|
|
results.append(x)
|
2013-04-08 16:36:01 +00:00
|
|
|
self._subset = results
|
2012-08-10 06:45:29 +00:00
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
def remove_restriction(self):
|
2012-04-13 12:39:54 +00:00
|
|
|
""" Do not restrict list operations """
|
2012-05-08 03:16:20 +00:00
|
|
|
self._restriction = None
|
2012-08-18 13:52:13 +00:00
|
|
|
|
2012-07-20 13:43:45 +00:00
|
|
|
def is_file(self):
|
|
|
|
""" did inventory come from a file? """
|
|
|
|
if not isinstance(self.host_list, basestring):
|
|
|
|
return False
|
|
|
|
return os.path.exists(self.host_list)
|
|
|
|
|
|
|
|
def basedir(self):
|
|
|
|
""" if inventory came from a file, what's the directory? """
|
|
|
|
if not self.is_file():
|
|
|
|
return None
|
2013-06-02 20:01:09 +00:00
|
|
|
dname = os.path.dirname(self.host_list)
|
2013-08-11 02:50:47 +00:00
|
|
|
if dname is None or dname == '' or dname == '.':
|
2013-06-02 20:01:09 +00:00
|
|
|
cwd = os.getcwd()
|
2013-10-31 00:48:53 +00:00
|
|
|
return os.path.abspath(cwd)
|
|
|
|
return os.path.abspath(dname)
|
2013-06-01 14:38:16 +00:00
|
|
|
|
2013-08-10 10:59:17 +00:00
|
|
|
def src(self):
|
|
|
|
""" if inventory came from a file, what's the directory and file name? """
|
|
|
|
if not self.is_file():
|
|
|
|
return None
|
|
|
|
return self.host_list
|
|
|
|
|
2013-06-01 14:38:16 +00:00
|
|
|
def playbook_basedir(self):
|
|
|
|
""" returns the directory of the current playbook """
|
|
|
|
return self._playbook_basedir
|
|
|
|
|
2015-07-14 13:26:24 +00:00
|
|
|
def set_playbook_basedir(self, dir_name):
|
2013-06-01 14:38:16 +00:00
|
|
|
"""
|
2014-03-21 18:05:18 +00:00
|
|
|
sets the base directory of the playbook so inventory can use it as a
|
|
|
|
basedir for host_ and group_vars, and other things.
|
|
|
|
"""
|
|
|
|
# Only update things if dir is a different playbook basedir
|
2015-07-14 13:26:24 +00:00
|
|
|
if dir_name != self._playbook_basedir:
|
|
|
|
self._playbook_basedir = dir_name
|
2014-03-21 18:05:18 +00:00
|
|
|
# get group vars from group_vars/ files
|
2015-07-14 13:26:24 +00:00
|
|
|
# FIXME: excluding the new_pb_basedir directory may result in group_vars
|
|
|
|
# files loading more than they should, however with the file caching
|
|
|
|
# we do this shouldn't be too much of an issue. Still, this should
|
|
|
|
# be fixed at some point to allow a "first load" to touch all of the
|
|
|
|
# directories, then later runs only touch the new basedir specified
|
2014-03-21 18:05:18 +00:00
|
|
|
for group in self.groups:
|
2015-07-14 13:26:24 +00:00
|
|
|
#group.vars = combine_vars(group.vars, self.get_group_vars(group, new_pb_basedir=True))
|
|
|
|
group.vars = combine_vars(group.vars, self.get_group_vars(group))
|
2014-03-21 18:05:18 +00:00
|
|
|
# get host vars from host_vars/ files
|
|
|
|
for host in self.get_hosts():
|
2015-07-14 13:26:24 +00:00
|
|
|
#host.vars = combine_vars(host.vars, self.get_host_vars(host, new_pb_basedir=True))
|
|
|
|
host.vars = combine_vars(host.vars, self.get_host_vars(host))
|
2014-07-14 13:21:33 +00:00
|
|
|
# invalidate cache
|
|
|
|
self._vars_per_host = {}
|
|
|
|
self._vars_per_group = {}
|
2014-03-21 18:05:18 +00:00
|
|
|
|
|
|
|
def get_host_vars(self, host, new_pb_basedir=False):
|
|
|
|
""" Read host_vars/ files """
|
2014-07-14 13:12:53 +00:00
|
|
|
return self._get_hostgroup_vars(host=host, group=None, new_pb_basedir=new_pb_basedir)
|
2013-06-01 14:38:16 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
def get_group_vars(self, group, new_pb_basedir=False):
|
|
|
|
""" Read group_vars/ files """
|
2014-07-14 13:12:53 +00:00
|
|
|
return self._get_hostgroup_vars(host=None, group=group, new_pb_basedir=new_pb_basedir)
|
2014-03-21 18:05:18 +00:00
|
|
|
|
|
|
|
def _get_hostgroup_vars(self, host=None, group=None, new_pb_basedir=False):
|
|
|
|
"""
|
|
|
|
Loads variables from group_vars/<groupname> and host_vars/<hostname> in directories parallel
|
|
|
|
to the inventory base directory or in the same directory as the playbook. Variables in the playbook
|
|
|
|
dir will win over the inventory dir if files are in both.
|
|
|
|
"""
|
|
|
|
|
|
|
|
results = {}
|
|
|
|
scan_pass = 0
|
|
|
|
_basedir = self.basedir()
|
2013-06-01 14:38:16 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
# look in both the inventory base directory and the playbook base directory
|
|
|
|
# unless we do an update for a new playbook base dir
|
|
|
|
if not new_pb_basedir:
|
|
|
|
basedirs = [_basedir, self._playbook_basedir]
|
|
|
|
else:
|
|
|
|
basedirs = [self._playbook_basedir]
|
2013-06-01 14:38:16 +00:00
|
|
|
|
2014-03-21 18:05:18 +00:00
|
|
|
for basedir in basedirs:
|
|
|
|
|
|
|
|
# this can happen from particular API usages, particularly if not run
|
|
|
|
# from /usr/bin/ansible-playbook
|
|
|
|
if basedir is None:
|
2015-07-14 13:26:24 +00:00
|
|
|
basedir = './'
|
2014-03-21 18:05:18 +00:00
|
|
|
|
|
|
|
scan_pass = scan_pass + 1
|
|
|
|
|
|
|
|
# it's not an eror if the directory does not exist, keep moving
|
|
|
|
if not os.path.exists(basedir):
|
|
|
|
continue
|
|
|
|
|
|
|
|
# save work of second scan if the directories are the same
|
|
|
|
if _basedir == self._playbook_basedir and scan_pass != 1:
|
|
|
|
continue
|
|
|
|
|
2015-05-04 02:47:26 +00:00
|
|
|
# FIXME: these should go to VariableManager
|
2014-03-21 18:05:18 +00:00
|
|
|
if group and host is None:
|
|
|
|
# load vars in dir/group_vars/name_of_group
|
2015-08-06 14:17:24 +00:00
|
|
|
base_path = os.path.realpath(os.path.join(basedir, "group_vars/%s" % group.name))
|
2015-06-16 15:55:26 +00:00
|
|
|
results = self._variable_manager.add_group_vars_file(base_path, self._loader)
|
2014-03-21 18:05:18 +00:00
|
|
|
elif host and group is None:
|
|
|
|
# same for hostvars in dir/host_vars/name_of_host
|
2015-08-06 14:17:24 +00:00
|
|
|
base_path = os.path.realpath(os.path.join(basedir, "host_vars/%s" % host.name))
|
2015-06-16 15:55:26 +00:00
|
|
|
results = self._variable_manager.add_host_vars_file(base_path, self._loader)
|
2014-03-21 18:05:18 +00:00
|
|
|
|
|
|
|
# all done, results is a dictionary of variables for this particular host.
|
|
|
|
return results
|
2013-06-01 14:38:16 +00:00
|
|
|
|
2015-07-18 19:24:44 +00:00
|
|
|
def refresh_inventory(self):
|
|
|
|
|
|
|
|
self.clear_pattern_cache()
|
|
|
|
|
|
|
|
self._hosts_cache = {}
|
|
|
|
self._vars_per_host = {}
|
|
|
|
self._vars_per_group = {}
|
|
|
|
self._groups_list = {}
|
2015-08-19 05:16:08 +00:00
|
|
|
self._groups_cache = {}
|
2015-07-18 19:24:44 +00:00
|
|
|
self.groups = []
|
|
|
|
|
|
|
|
self.parse_inventory(self.host_list)
|