Debian Codegraph @

lib/ansible/inventory/host.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
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 annotations
19
20 import collections.abc as c
21 import typing as t
22
23 from collections.abc import Mapping, MutableMapping
24
25 from ansible.errors import AnsibleError
26 from ansible.inventory.group import Group, InventoryObjectType
27 from ansible.parsing.utils.addresses import patterns
28 from ansible.utils.display import Display
29 from ansible.utils.vars import combine_vars, get_unique_id, validate_variable_name
30
31 from . import helpers # this is left as a module import to facilitate easier unit test patching
32
33 __all__ = ['Host']
34
35
36 class Host:
37 """A single ansible host."""
38 base_type = InventoryObjectType.HOST
39
40 # __slots__ = [ 'name', 'vars', 'groups' ]
41
42 def __eq__(self, other):
43 if not isinstance(other, Host):
44 return False
45 return self._uuid == other._uuid
46
47 def __ne__(self, other):
48 return not self.__eq__(other)
49
50 def __hash__(self):
51 return hash(self.name)
52
53 def __str__(self):
54 return self.get_name()
55
56 def __repr__(self):
57 return self.get_name()
58
59 def __init__(self, name: str, port: int | str | None = None, gen_uuid: bool = True) -> None:
60 name = helpers.remove_trust(name)
61
62 self.vars: dict[str, t.Any] = {}
63 self.groups: list[Group] = []
64 self._uuid: str | None = None
65
66 self.name: str = name
67 self.address: str = name
68
69 if port:
70 self.set_variable('ansible_port', int(port))
71
72 if gen_uuid:
73 self._uuid = get_unique_id()
74
75 self.implicit: bool = False
76
77 def get_name(self) -> str:
78 return self.name
79
80 def populate_ancestors(self, additions: c.Iterable[Group] | None = None) -> None:
81 # populate ancestors
82 if additions is None:
83 for group in self.groups:
84 self.add_group(group)
85 else:
86 for group in additions:
87 if group not in self.groups:
88 self.groups.append(group)
89
90 def add_group(self, group: Group) -> bool:
91 added = False
92 # populate ancestors first
93 for oldg in group.get_ancestors():
94 if oldg not in self.groups:
95 self.groups.append(oldg)
96
97 # actually add group
98 if group not in self.groups:
99 self.groups.append(group)
100 added = True
101 return added
102
103 def remove_group(self, group: Group) -> bool:
104 removed = False
105 if group in self.groups:
106 self.groups.remove(group)
107 removed = True
108
109 # remove exclusive ancestors, xcept all!
110 for oldg in group.get_ancestors():
111 if oldg.name != 'all':
112 for childg in self.groups:
113 if oldg in childg.get_ancestors():
114 break
115 else:
116 self.remove_group(oldg)
117 return removed
118
119 def set_variable(self, key: str, value: t.Any) -> None:
120 key = helpers.remove_trust(key)
121
122 try:
123 validate_variable_name(key)
124 except AnsibleError as ex:
125 Display().deprecated(msg=f'Accepting inventory variable with invalid name {key!r}.', version='2.23', help_text=ex._help_text, obj=ex.obj)
126
127 if key in self.vars and isinstance(self.vars[key], MutableMapping) and isinstance(value, Mapping):
128 self.vars = combine_vars(self.vars, {key: value})
129 else:
130 self.vars[key] = value
131
132 def get_groups(self) -> list[Group]:
133 return self.groups
134
135 def get_magic_vars(self) -> dict[str, t.Any]:
136 results: dict[str, t.Any] = dict(
137 inventory_hostname=self.name,
138 )
139
140 # FUTURE: these values should be dynamically calculated on access ala the rest of magic vars
141 if patterns['ipv4'].match(self.name) or patterns['ipv6'].match(self.name):
142 results['inventory_hostname_short'] = self.name
143 else:
144 results['inventory_hostname_short'] = self.name.split('.')[0]
145
146 results['group_names'] = sorted([g.name for g in self.get_groups() if g.name != 'all'])
147
148 return results
149
150 def get_vars(self) -> dict[str, t.Any]:
151 return combine_vars(self.vars, self.get_magic_vars())