Debian Codegraph @

lib/ansible/inventory/data.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 #############################################
19 from __future__ import annotations
20
21 import sys
22 import typing as t
23
24 from ansible import constants as C
25 from ansible.errors import AnsibleError
26 from ansible.inventory.group import Group
27 from ansible.inventory.host import Host
28 from ansible.utils.display import Display
29 from ansible.utils.vars import combine_vars
30 from ansible.utils.path import basedir
31
32 from . import helpers # this is left as a module import to facilitate easier unit test patching
33
34
35 display = Display()
36
37
38 class InventoryData:
39 """
40 Holds inventory data (host and group objects).
41 Using its methods should guarantee expected relationships and data.
42 """
43
44 def __init__(self) -> None:
45
46 self.groups: dict[str, Group] = {}
47 self.hosts: dict[str, Host] = {}
48
49 # provides 'groups' magic var, host object has group_names
50 self._groups_dict_cache: dict[str, list[str]] = {}
51
52 # current localhost, implicit or explicit
53 self.localhost: Host | None = None
54
55 self.current_source: str | None = None
56 self.processed_sources: list[str] = []
57
58 # Always create the 'all' and 'ungrouped' groups,
59 for group in ('all', 'ungrouped'):
60 self.add_group(group)
61
62 self.add_child('all', 'ungrouped')
63
64 def _create_implicit_localhost(self, pattern: str) -> Host:
65
66 if self.localhost:
67 new_host = self.localhost
68 else:
69 new_host = Host(pattern)
70
71 new_host.address = "127.0.0.1"
72 new_host.implicit = True
73
74 # set localhost defaults
75 py_interp = sys.executable
76 if not py_interp:
77 # sys.executable is not set in some cornercases. see issue #13585
78 py_interp = '/usr/bin/python'
79 display.warning('Unable to determine python interpreter from sys.executable. Using /usr/bin/python default. '
80 'You can correct this by setting ansible_python_interpreter for localhost')
81 new_host.set_variable("ansible_python_interpreter", py_interp)
82 new_host.set_variable("ansible_connection", 'local')
83
84 self.localhost = new_host
85
86 return new_host
87
88 def reconcile_inventory(self) -> None:
89 """Ensure inventory basic rules, run after updates."""
90
91 display.debug('Reconcile groups and hosts in inventory.')
92 self.current_source = None
93
94 group_names = set()
95 # set group vars from group_vars/ files and vars plugins
96 for g in self.groups:
97 group = self.groups[g]
98 group_names.add(group.name)
99
100 # ensure all groups inherit from 'all'
101 if group.name != 'all' and not group.get_ancestors():
102 self.add_child('all', group.name)
103
104 host_names = set()
105 # get host vars from host_vars/ files and vars plugins
106 for host in self.hosts.values():
107 host_names.add(host.name)
108
109 mygroups = host.get_groups()
110
111 if self.groups['ungrouped'] in mygroups:
112 # clear ungrouped of any incorrectly stored by parser
113 if set(mygroups).difference({self.groups['all'], self.groups['ungrouped']}):
114 self.groups['ungrouped'].remove_host(host)
115
116 elif not host.implicit:
117 # add ungrouped hosts to ungrouped, except implicit
118 length = len(mygroups)
119 if length == 0 or (length == 1 and self.groups['all'] in mygroups):
120 self.add_child('ungrouped', host.name)
121
122 # special case for implicit hosts
123 if host.implicit:
124 host.vars = combine_vars(self.groups['all'].get_vars(), host.vars)
125
126 # warn if overloading identifier as both group and host
127 for conflict in group_names.intersection(host_names):
128 display.warning("Found both group and host with same name: %s" % conflict)
129
130 self._groups_dict_cache = {}
131
132 def get_host(self, hostname: str) -> Host | None:
133 """Fetch host object using name deal with implicit localhost."""
134
135 hostname = helpers.remove_trust(hostname)
136
137 matching_host = self.hosts.get(hostname, None)
138
139 # if host is not in hosts dict
140 if matching_host is None and hostname in C.LOCALHOST:
141 # might need to create implicit localhost
142 matching_host = self._create_implicit_localhost(hostname)
143
144 return matching_host
145
146 def add_group(self, group: str) -> str:
147 """Adds a group to inventory if not there already, returns named actually used."""
148
149 if group:
150 if not isinstance(group, str):
151 raise AnsibleError("Invalid group name supplied, expected a string but got %s for %s" % (type(group), group))
152 if group not in self.groups:
153 g = Group(group)
154 group = g.name # the group object may have sanitized the group name; use whatever it has
155 if group not in self.groups:
156 self.groups[group] = g
157 self._groups_dict_cache = {}
158 display.debug("Added group %s to inventory" % group)
159 else:
160 display.debug("group %s already in inventory" % group)
161 else:
162 raise AnsibleError("Invalid empty/false group name provided: %s" % group)
163
164 return group
165
166 def remove_group(self, group: Group) -> None:
167
168 if group.name in self.groups:
169 del self.groups[group.name]
170 display.debug("Removed group %s from inventory" % group.name)
171 self._groups_dict_cache = {}
172
173 for host in self.hosts:
174 h = self.hosts[host]
175 h.remove_group(group)
176
177 def add_host(self, host: str, group: str | None = None, port: int | str | None = None) -> str:
178 """Adds a host to inventory and possibly a group if not there already."""
179
180 host = helpers.remove_trust(host)
181
182 if host:
183 if not isinstance(host, str):
184 raise AnsibleError("Invalid host name supplied, expected a string but got %s for %s" % (type(host), host))
185
186 # TODO: add to_safe_host_name
187 g = None
188 if group:
189 if group in self.groups:
190 g = self.groups[group]
191 else:
192 raise AnsibleError("Could not find group %s in inventory" % group)
193
194 if host not in self.hosts:
195 h = Host(host, port)
196 self.hosts[host] = h
197 if self.current_source: # set to 'first source' in which host was encountered
198 self.set_variable(host, 'inventory_file', self.current_source)
199 self.set_variable(host, 'inventory_dir', basedir(self.current_source))
200 else:
201 self.set_variable(host, 'inventory_file', None)
202 self.set_variable(host, 'inventory_dir', None)
203 display.debug("Added host %s to inventory" % host)
204
205 # set default localhost from inventory to avoid creating an implicit one. Last localhost defined 'wins'.
206 if host in C.LOCALHOST:
207 if self.localhost is None:
208 self.localhost = self.hosts[host]
209 display.vvvv("Set default localhost to %s" % h)
210 else:
211 display.warning("A duplicate localhost-like entry was found (%s). First found localhost was %s" % (h, self.localhost.name))
212 else:
213 h = self.hosts[host]
214
215 if g:
216 g.add_host(h)
217 self._groups_dict_cache = {}
218 display.debug("Added host %s to group %s" % (host, group))
219 else:
220 raise AnsibleError("Invalid empty host name provided: %s" % host)
221
222 return host
223
224 def remove_host(self, host: Host) -> None:
225
226 if host.name in self.hosts:
227 del self.hosts[host.name]
228
229 for group in self.groups:
230 g = self.groups[group]
231 g.remove_host(host)
232
233 def set_variable(self, entity: str, varname: str, value: t.Any) -> None:
234 """Sets a variable for an inventory object."""
235
236 inv_object: Host | Group
237
238 if entity in self.groups:
239 inv_object = self.groups[entity]
240 elif entity in self.hosts:
241 inv_object = self.hosts[entity]
242 else:
243 raise AnsibleError("Could not identify group or host named %s" % entity)
244
245 inv_object.set_variable(varname, value)
246 display.debug('set %s for %s' % (varname, entity))
247
248 def add_child(self, group: str, child: str) -> bool:
249 """Add host or group to group."""
250 if group in self.groups:
251 g = self.groups[group]
252 if child in self.groups:
253 added = g.add_child_group(self.groups[child])
254 elif child in self.hosts:
255 added = g.add_host(self.hosts[child])
256 else:
257 raise AnsibleError("%s is not a known host nor group" % child)
258 self._groups_dict_cache = {}
259 display.debug('Group %s now contains %s' % (group, child))
260 else:
261 raise AnsibleError("%s is not a known group" % group)
262 return added
263
264 def get_groups_dict(self) -> dict[str, list[str]]:
265 """
266 We merge a 'magic' var 'groups' with group name keys and hostname list values into every host variable set. Cache for speed.
267 """
268 if not self._groups_dict_cache:
269 for group_name, group in self.groups.items():
270 self._groups_dict_cache[group_name] = [h.name for h in group.get_hosts()]
271
272 return self._groups_dict_cache