Debian Codegraph @

test/lib/ansible_test/_internal/inventory.py

raw
1 """Inventory creation from host profiles."""
2
3 from __future__ import annotations
4
5 import shutil
6 import sys
7 import typing as t
8
9 from .config import (
10 EnvironmentConfig,
11 )
12
13 from .util import (
14 sanitize_host_name,
15 exclude_none_values,
16 )
17
18 from .host_configs import (
19 ControllerConfig,
20 PosixRemoteConfig,
21 )
22
23 from .host_profiles import (
24 ControllerHostProfile,
25 ControllerProfile,
26 HostProfile,
27 Inventory,
28 NetworkInventoryProfile,
29 NetworkRemoteProfile,
30 SshTargetHostProfile,
31 WindowsInventoryProfile,
32 WindowsRemoteProfile,
33 DebuggableProfile,
34 )
35
36 from .ssh import (
37 ssh_options_to_str,
38 )
39
40
41 def get_common_variables(target_profile: HostProfile, controller: bool = False) -> dict[str, t.Any]:
42 """Get variables common to all scenarios, but dependent on the target profile."""
43 target_config = target_profile.config
44
45 if controller or isinstance(target_config, ControllerConfig):
46 # The current process is running on the controller, so consult the controller directly when it is the target.
47 macos = sys.platform == 'darwin'
48 elif isinstance(target_config, PosixRemoteConfig):
49 # The target is not the controller, so consult the remote config for that target.
50 macos = target_config.name.startswith('macos/')
51 else:
52 # The target is a type which either cannot be macOS or for which the OS is unknown.
53 # There is currently no means for the user to override this for user provided hosts.
54 macos = False
55
56 common_variables: dict[str, t.Any] = {}
57
58 if macos:
59 # When using sudo on macOS we may encounter permission denied errors when dropping privileges due to inability to access the current working directory.
60 # To compensate for this we'll perform a `cd /` before running any commands after `sudo` succeeds.
61 common_variables.update(ansible_sudo_chdir='/')
62
63 if isinstance(target_profile, DebuggableProfile):
64 common_variables.update(target_profile.get_ansiballz_inventory_variables())
65
66 return common_variables
67
68
69 def create_controller_inventory(args: EnvironmentConfig, path: str, controller_host: ControllerHostProfile) -> None:
70 """Create and return inventory for use in controller-only integration tests."""
71 testhost: dict[str, str | int | None] = get_common_variables(controller_host, controller=True) | dict(
72 ansible_connection='local',
73 ansible_pipelining='yes',
74 ansible_python_interpreter=controller_host.python.path,
75 ansible_pwsh_interpreter=controller_host.powershell.path,
76 )
77
78 testhost = exclude_none_values(testhost)
79
80 inventory = Inventory(
81 host_groups=dict(
82 testgroup=dict(
83 testhost=testhost,
84 ),
85 ),
86 )
87
88 inventory.write(args, path)
89
90
91 def create_windows_inventory(args: EnvironmentConfig, path: str, target_hosts: list[HostProfile]) -> None:
92 """Create and return inventory for use in target Windows integration tests."""
93 first = target_hosts[0]
94
95 if isinstance(first, WindowsInventoryProfile):
96 if args.explain:
97 return
98
99 try:
100 shutil.copyfile(first.config.path, path)
101 except shutil.SameFileError:
102 pass
103
104 return
105
106 target_hosts = t.cast(list[WindowsRemoteProfile], target_hosts)
107 hosts = [(target_host, target_host.wait_for_instance().connection) for target_host in target_hosts]
108 windows_hosts = {sanitize_host_name(host.config.name): host.get_inventory_variables() for host, connection in hosts}
109
110 inventory = Inventory(
111 host_groups=dict(
112 windows=windows_hosts,
113 ),
114 # The `testhost` group is needed to support the `binary_modules_winrm` integration test.
115 # The test should be updated to remove the need for this.
116 extra_groups={
117 'testhost': ['windows'],
118 },
119 )
120
121 inventory.write(args, path)
122
123
124 def create_network_inventory(args: EnvironmentConfig, path: str, target_hosts: list[HostProfile]) -> None:
125 """Create and return inventory for use in target network integration tests."""
126 first = target_hosts[0]
127
128 if isinstance(first, NetworkInventoryProfile):
129 if args.explain:
130 return
131
132 try:
133 shutil.copyfile(first.config.path, path)
134 except shutil.SameFileError:
135 pass
136
137 return
138
139 target_hosts = t.cast(list[NetworkRemoteProfile], target_hosts)
140 host_groups: dict[str, dict[str, dict[str, t.Union[str, int]]]] = {target_host.config.platform: {} for target_host in target_hosts}
141
142 for target_host in target_hosts:
143 host_groups[target_host.config.platform][sanitize_host_name(target_host.config.name)] = target_host.get_inventory_variables()
144
145 inventory = Inventory(
146 host_groups=host_groups,
147 # The `net` group was added to support platform agnostic testing. It may not longer be needed.
148 # see: https://github.com/ansible/ansible/pull/34661
149 # see: https://github.com/ansible/ansible/pull/34707
150 extra_groups={
151 'net': list(sorted(host_groups)),
152 },
153 )
154
155 inventory.write(args, path)
156
157
158 def create_posix_inventory(args: EnvironmentConfig, path: str, target_hosts: list[HostProfile], needs_ssh: bool = False) -> None:
159 """Create and return inventory for use in POSIX integration tests."""
160 target_hosts = t.cast(list[SshTargetHostProfile], target_hosts)
161
162 if len(target_hosts) != 1:
163 raise Exception()
164
165 target_host = target_hosts[0]
166
167 testhost: dict[str, str | int | None] = get_common_variables(target_host)
168
169 if isinstance(target_host, ControllerProfile) and not needs_ssh:
170 testhost |= dict(
171 ansible_connection='local',
172 ansible_pipelining='yes',
173 ansible_python_interpreter=target_host.python.path,
174 ansible_pwsh_interpreter=target_host.powershell.path,
175 )
176 else:
177 connections = target_host.get_controller_target_connections()
178
179 if len(connections) != 1:
180 raise Exception()
181
182 ssh = connections[0]
183
184 testhost |= dict(
185 ansible_connection='ssh',
186 ansible_pipelining='yes',
187 ansible_python_interpreter=ssh.settings.python_interpreter,
188 ansible_pwsh_interpreter=ssh.settings.powershell_interpreter,
189 ansible_host=ssh.settings.host,
190 ansible_port=ssh.settings.port,
191 ansible_user=ssh.settings.user,
192 ansible_ssh_private_key_file=ssh.settings.identity_file,
193 ansible_ssh_extra_args=ssh_options_to_str(ssh.settings.options),
194 )
195
196 if ssh.become:
197 testhost.update(
198 ansible_become='yes',
199 ansible_become_method=ssh.become.method,
200 )
201
202 testhost = exclude_none_values(testhost)
203
204 inventory = Inventory(
205 host_groups=dict(
206 testgroup=dict(
207 testhost=testhost,
208 ),
209 ),
210 )
211
212 inventory.write(args, path)