本文整理汇总了Python中ansible.inventory.host.Host类的典型用法代码示例。如果您正苦于以下问题:Python Host类的具体用法?Python Host怎么用?Python Host使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Host类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_host
def add_host(self, host_ip, add_to_root=True, group_list=[], var_list={}):
"""Add a host ip to the ansible host file
This is a simple function to add hosts to
add_to_root = Adds the host to the root group (unnamed)
groups_list: List of groupnames where the host should appears.
var_list: Variable list. see allowed_variables."""
#root group in unnamed, but in the inventory object
# is the 'ungrouped' group
self.__dirty = True
new_host = Host(host_ip)
for key,value in var_list.iteritems():
if self.is_allowed_variable(key):
new_host.set_variable(key,value)
if add_to_root:
if 'ungrouped' not in group_list:
group_list.append('ungrouped')
#Check groups. The ansible inventory should contain each of the groups.
for group in group_list:
if not self.__inventory.get_group(group):
new_group= Group(group)
self.__inventory.add_group(new_group)
grp = self.__inventory.get_group(group)
host_names = [host.name for host in grp.get_hosts()]
if new_host.name not in host_names:
grp.add_host(new_host)
示例2: _parse_base_groups
def _parse_base_groups(self):
# FIXME: refactor
ungrouped = Group(name='ungrouped')
all = Group(name='all')
all.add_child_group(ungrouped)
self.groups = dict(all=all, ungrouped=ungrouped)
active_group_name = 'ungrouped'
for line in self.lines:
if line.startswith("["):
active_group_name = line.replace("[","").replace("]","").strip()
if line.find(":vars") != -1 or line.find(":children") != -1:
active_group_name = None
else:
new_group = self.groups[active_group_name] = Group(name=active_group_name)
all.add_child_group(new_group)
elif line.startswith("#") or line == '':
pass
elif active_group_name:
tokens = shlex.split(line)
if len(tokens) == 0:
continue
hostname = tokens[0]
port = C.DEFAULT_REMOTE_PORT
# Two cases to check:
# 0. A hostname that contains a range pesudo-code and a port
# 1. A hostname that contains just a port
if (hostname.find("[") != -1 and
hostname.find("]") != -1 and
hostname.find(":") != -1 and
(hostname.rindex("]") < hostname.rindex(":")) or
(hostname.find("]") == -1 and hostname.find(":") != -1)):
tokens2 = hostname.rsplit(":", 1)
hostname = tokens2[0]
port = tokens2[1]
host = None
_all_hosts = []
if hostname in self.hosts:
host = self.hosts[hostname]
_all_hosts.append(host)
else:
if detect_range(hostname):
_hosts = expand_hostname_range(hostname)
for _ in _hosts:
host = Host(name=_, port=port)
self.hosts[_] = host
_all_hosts.append(host)
else:
host = Host(name=hostname, port=port)
self.hosts[hostname] = host
_all_hosts.append(host)
if len(tokens) > 1:
for t in tokens[1:]:
(k,v) = t.split("=")
host.set_variable(k,v)
for _ in _all_hosts:
self.groups[active_group_name].add_host(_)
示例3: test_serialize_then_deserialize
def test_serialize_then_deserialize(self):
group = Group('some_group')
self.hostA.add_group(group)
hostA_data = self.hostA.serialize()
hostA_clone = Host()
hostA_clone.deserialize(hostA_data)
self.assertEquals(self.hostA, hostA_clone)
示例4: _create_implicit_localhost
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")
ungrouped = self.get_group("ungrouped")
if ungrouped is None:
self.add_group(Group('ungrouped'))
ungrouped = self.get_group('ungrouped')
ungrouped.add_host(new_host)
return new_host
示例5: _create_implicit_localhost
def _create_implicit_localhost(self, pattern):
# 如果pattern不在all礼拜中,则创建新的local Host,并添加到ungrouped组(没有则创建),然后返回Host对象
new_host = Host(pattern)
new_host.set_variable("ansible_python_interpreter", sys.executable)
new_host.set_variable("ansible_connection", "local")
ungrouped = self.get_group("ungrouped")
if ungrouped is None:
self.add_group(Group('ungrouped'))
ungrouped = self.get_group('ungrouped')
self.get_group('all').add_child_group(ungrouped)
ungrouped.add_host(new_host)
return new_host
示例6: _create_implicit_localhost
def _create_implicit_localhost(self, pattern):
if self.localhost:
new_host = self.localhost
else:
new_host = Host(pattern)
# use 'all' vars but not part of all group
new_host.vars = self.groups['all'].get_vars()
new_host.address = "127.0.0.1"
new_host.implicit = True
if "ansible_python_interpreter" not in new_host.vars:
py_interp = sys.executable
if not py_interp:
# sys.executable is not set in some cornercases. #13585
py_interp = '/usr/bin/python'
display.warning('Unable to determine python interpreter from sys.executable. Using /usr/bin/python default. '
'You can correct this by setting ansible_python_interpreter for localhost')
new_host.set_variable("ansible_python_interpreter", py_interp)
if "ansible_connection" not in new_host.vars:
new_host.set_variable("ansible_connection", 'local')
self.localhost = new_host
return new_host
示例7: _add_host
def _add_host(self, host_info):
'''
Helper function to add a new host to inventory based on a task result.
'''
host_name = host_info.get('host_name')
# Check if host in cache, add if not
if host_name in self._inventory._hosts_cache:
new_host = self._inventory._hosts_cache[host_name]
else:
new_host = Host(name=host_name)
self._inventory._hosts_cache[host_name] = new_host
allgroup = self._inventory.get_group('all')
allgroup.add_host(new_host)
# Set/update the vars for this host
# FIXME: probably should have a set vars method for the host?
new_vars = host_info.get('host_vars', dict())
new_host.vars = self._inventory.get_host_vars(new_host)
new_host.vars.update(new_vars)
new_groups = host_info.get('groups', [])
for group_name in new_groups:
if not self._inventory.get_group(group_name):
new_group = Group(group_name)
self._inventory.add_group(new_group)
new_group.vars = self._inventory.get_group_variables(group_name)
else:
new_group = self._inventory.get_group(group_name)
new_group.add_host(new_host)
# add this host to the group cache
if self._inventory.groups is not None:
if group_name in self._inventory.groups:
if new_host not in self._inventory.get_group(group_name).hosts:
self._inventory.get_group(group_name).hosts.append(new_host.name)
# clear pattern caching completely since it's unpredictable what
# patterns may have referenced the group
# FIXME: is this still required?
self._inventory.clear_pattern_cache()
示例8: TestHostWithPort
class TestHostWithPort(TestHost):
ansible_port = 8822
def setUp(self):
self.hostA = Host(name='a', port=self.ansible_port)
self.hostB = Host(name='b', port=self.ansible_port)
def test_get_vars_ansible_port(self):
host_vars = self.hostA.get_vars()
self.assertEquals(host_vars['ansible_port'], self.ansible_port)
示例9: _create_implicit_localhost
def _create_implicit_localhost(self, pattern):
new_host = Host(pattern)
new_host.address = "127.0.0.1"
new_host.vars = self.get_host_vars(new_host)
new_host.set_variable("ansible_connection", "local")
if "ansible_python_interpreter" not in new_host.vars:
new_host.set_variable("ansible_python_interpreter", sys.executable)
self.get_group("ungrouped").add_host(new_host)
return new_host
示例10: _parse_base_groups
def _parse_base_groups(self):
ungrouped = Group(name='ungrouped')
all = Group(name='all')
all.add_child_group(ungrouped)
self.groups = dict(all=all, ungrouped=ungrouped)
active_group_name = 'ungrouped'
for line in self.lines:
if line.startswith("["):
active_group_name = line.replace("[","").replace("]","").strip()
if line.find(":vars") != -1 or line.find(":children") != -1:
active_group_name = None
else:
new_group = self.groups[active_group_name] = Group(name=active_group_name)
all.add_child_group(new_group)
elif line.startswith("#") or line == '':
pass
elif active_group_name:
tokens = line.split()
if len(tokens) == 0:
continue
hostname = tokens[0]
port = C.DEFAULT_REMOTE_PORT
if hostname.find(":") != -1:
tokens2 = hostname.split(":")
hostname = tokens2[0]
port = tokens2[1]
host = None
if hostname in self.hosts:
host = self.hosts[hostname]
else:
host = Host(name=hostname, port=port)
self.hosts[hostname] = host
if len(tokens) > 1:
for t in tokens[1:]:
(k,v) = t.split("=")
host.set_variable(k,v)
self.groups[active_group_name].add_host(host)
示例11: __init__
def __init__(self, play, inventory, variable_manager, loader):
self._lookup = dict()
self._loader = loader
self._play = play
self._variable_manager = variable_manager
hosts = inventory.get_hosts(ignore_limits_and_restrictions=True)
# check to see if localhost is in the hosts list, as we
# may have it referenced via hostvars but if created implicitly
# it doesn't sow up in the hosts list
has_localhost = False
for host in hosts:
if host.name in C.LOCALHOST:
has_localhost = True
break
if not has_localhost:
new_host = Host(name='localhost')
new_host.set_variable("ansible_python_interpreter", sys.executable)
new_host.set_variable("ansible_connection", "local")
new_host.address = '127.0.0.1'
hosts.append(new_host)
for host in hosts:
self._lookup[host.name] = host
示例12: __init__
def __init__(self, vars_manager, play, inventory, loader):
self._lookup = {}
self._loader = loader
# temporarily remove the inventory filter restriction
# so we can compile the variables for all of the hosts
# in inventory
restriction = inventory._restriction
inventory.remove_restriction()
hosts = inventory.get_hosts(ignore_limits_and_restrictions=True)
inventory.restrict_to_hosts(restriction)
# check to see if localhost is in the hosts list, as we
# may have it referenced via hostvars but if created implicitly
# it doesn't sow up in the hosts list
has_localhost = False
for host in hosts:
if host.name in C.LOCALHOST:
has_localhost = True
break
# we don't use the method in inventory to create the implicit host,
# because it also adds it to the 'ungrouped' group, and we want to
# avoid any side-effects
if not has_localhost:
new_host = Host(name='localhost')
new_host.set_variable("ansible_python_interpreter", sys.executable)
new_host.set_variable("ansible_connection", "local")
new_host.ipv4_address = '127.0.0.1'
hosts.append(new_host)
for host in hosts:
self._lookup[host.name] = vars_manager.get_vars(loader=loader, play=play, host=host, include_hostvars=False)
示例13: run_module
def run_module(hosts, module_name, args, **complex_args):
import ansible.inventory
pattern = "all"
inventory = ansible.inventory.Inventory(',')
all_group = inventory.get_group("all")
from ansible.inventory.host import Host
for h in hosts:
host = Host(h["host"], h.get("port"))
for key, value in h["settings"].iteritems():
host.set_variable(key, value)
all_group.add_host(host)
# в конструкторе кэш посчитался заранее
inventory.clear_pattern_cache()
# сам Ansible использует отдельный Runner для каждого действия в playbook,
# так что вот готов отдельный кирпичик для системы развертывания
import ansible.runner
runner = ansible.runner.Runner(
module_name=module_name,
module_args=args,
complex_args=complex_args,
pattern=pattern,
inventory=inventory,
)
results = runner.run()
# :COPY_N_PASTE_REALIZATION: bin/ansible
if results['dark']:
assert False, "Couldn't connect to %s" % results['dark']
total = 0
for result in results['contacted'].values():
if 'failed' in result or result.get('rc', 0) != 0:
assert False, result
total += 1
assert total == len(hosts), "The host was not connected to"
示例14: _create_implicit_localhost
def _create_implicit_localhost(self, pattern='localhost'):
new_host = Host(pattern)
new_host.address = "127.0.0.1"
new_host.implicit = True
new_host.vars = self.get_host_vars(new_host)
new_host.set_variable("ansible_connection", "local")
if "ansible_python_interpreter" not in new_host.vars:
py_interp = sys.executable
if not py_interp:
# sys.executable is not set in some cornercases. #13585
display.warning('Unable to determine python interpreter from sys.executable. Using /usr/bin/python default. You can correct this by setting ansible_python_interpreter for localhost')
py_interp = '/usr/bin/python'
new_host.set_variable("ansible_python_interpreter", py_interp)
self.get_group("ungrouped").add_host(new_host)
return new_host
示例15: _create_implicit_localhost
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")
new_host.ipv4_address = "127.0.0.1"
ungrouped = self.get_group("ungrouped")
if ungrouped is None:
self.add_group(Group("ungrouped"))
ungrouped = self.get_group("ungrouped")
self.get_group("all").add_child_group(ungrouped)
ungrouped.add_host(new_host)
return new_host