Debian Codegraph @

ansible_collections/community/general/plugins/connection/incus.py

raw
1 # Based on lxd.py (c) 2016, Matt Clay <[email protected]>
2 # (c) 2023, Stephane Graber <[email protected]>
3 # Copyright (c) 2023 Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 author: Stéphane Graber (@stgraber)
11 name: incus
12 short_description: Run tasks in Incus instances using the Incus CLI
13 description:
14 - Run commands or put/fetch files to an existing Incus instance using Incus CLI.
15 version_added: "8.2.0"
16 notes:
17 - When using this collection for Windows virtual machines, set C(ansible_shell_type) to C(powershell) or C(cmd) as a variable to the host in
18 the inventory.
19 options:
20 remote_addr:
21 description:
22 - The instance identifier.
23 type: string
24 default: inventory_hostname
25 vars:
26 - name: inventory_hostname
27 - name: ansible_host
28 - name: ansible_incus_host
29 executable:
30 description:
31 - The shell to use for execution inside the instance.
32 type: string
33 default: /bin/sh
34 vars:
35 - name: ansible_executable
36 - name: ansible_incus_executable
37 incus_become_method:
38 description:
39 - Become command used to switch to a non-root user.
40 - Is only used when O(remote_user) is not V(root).
41 type: str
42 default: /bin/su
43 vars:
44 - name: incus_become_method
45 version_added: 10.4.0
46 remote:
47 description:
48 - The name of the Incus remote to use (per C(incus remote list)).
49 - Remotes are used to access multiple servers from a single client.
50 type: string
51 default: local
52 vars:
53 - name: ansible_incus_remote
54 remote_user:
55 description:
56 - User to login/authenticate as.
57 - Can be set from the CLI with the C(--user) or C(-u) options.
58 type: string
59 default: root
60 vars:
61 - name: ansible_user
62 env:
63 - name: ANSIBLE_REMOTE_USER
64 ini:
65 - section: defaults
66 key: remote_user
67 keyword:
68 - name: remote_user
69 version_added: 10.4.0
70 project:
71 description:
72 - The name of the Incus project to use (per C(incus project list)).
73 - Projects are used to divide the instances running on a server.
74 type: string
75 default: default
76 vars:
77 - name: ansible_incus_project
78 """
79
80 import os
81 import re
82 from subprocess import PIPE, Popen, call
83
84 from ansible.errors import AnsibleConnectionFailure, AnsibleError, AnsibleFileNotFound
85 from ansible.module_utils.common.process import get_bin_path
86 from ansible.module_utils.common.text.converters import to_bytes, to_text
87 from ansible.plugins.connection import ConnectionBase
88
89
90 class Connection(ConnectionBase):
91 """Incus based connections"""
92
93 transport = "incus"
94 has_pipelining = True
95
96 def __init__(self, play_context, new_stdin, *args, **kwargs):
97 super().__init__(play_context, new_stdin, *args, **kwargs)
98
99 self._incus_cmd = get_bin_path("incus")
100
101 if not self._incus_cmd:
102 raise AnsibleError("incus command not found in PATH")
103
104 if getattr(self._shell, "_IS_WINDOWS", False):
105 # Initializing regular expression patterns to match on a PowerShell or cmd command line.
106 self.powershell_regex_pattern = re.compile(
107 r'^"?(?P<executable>(?:[a-z]:\\)?[a-z0-9 ()\\.]*powershell(?:\.exe)?)"?\s+(?P<args>.*)(?P<command>-c(?:ommand)?)\s+(?P<post_args>.*(\n.*)*)',
108 re.IGNORECASE,
109 )
110 self.cmd_regex_pattern = re.compile(
111 r'^"?(?P<executable>(?:[a-z]:\\)?[a-z0-9 ()\\.]*cmd(?:\.exe)?)"?\s+(?P<args>.*)(?P<command>/c)\s+(?P<post_args>.*)',
112 re.IGNORECASE,
113 )
114
115 # Basic setup for a Windows host.
116 self.has_native_async = True
117 self.always_pipeline_modules = True
118 self.module_implementation_preferences = (".ps1", ".exe", "")
119 self.allow_executable = False
120
121 def _connect(self):
122 """connect to Incus (nothing to do here)"""
123 super()._connect()
124
125 if not self._connected:
126 self._display.vvv(
127 f"ESTABLISH Incus CONNECTION FOR USER: {self.get_option('remote_user')}", host=self._instance()
128 )
129 self._connected = True
130
131 def _build_command(self, cmd) -> list[str]:
132 """build the command to execute on the incus host"""
133
134 # Force pseudo-terminal allocation if the active become plugin
135 # requires one (e.g. community.general.machinectl), otherwise the
136 # become helper runs without a controlling tty and silently fails.
137 require_tty = self.become is not None and getattr(self.become, "require_tty", False)
138
139 exec_cmd: list[str] = [
140 self._incus_cmd,
141 "--project",
142 self.get_option("project"),
143 "exec",
144 *(["-T"] if getattr(self._shell, "_IS_WINDOWS", False) else []),
145 *(["-t"] if require_tty and not getattr(self._shell, "_IS_WINDOWS", False) else []),
146 f"{self.get_option('remote')}:{self._instance()}",
147 "--",
148 ]
149
150 if getattr(self._shell, "_IS_WINDOWS", False):
151 if regex_match := self.powershell_regex_pattern.match(cmd):
152 regex_pattern = self.powershell_regex_pattern
153 elif regex_match := self.cmd_regex_pattern.match(cmd):
154 regex_pattern = self.cmd_regex_pattern
155
156 if regex_match:
157 self._display.vvvvvv(
158 f'Found keyword: "{regex_match.group("command")}" based on regex: {regex_pattern.pattern}',
159 host=self._instance(),
160 )
161
162 # To avoid splitting on a space contained in the path, set the executable as the first argument.
163 exec_cmd.append(regex_match.group("executable"))
164 if args := regex_match.group("args"):
165 exec_cmd.extend(args.strip().split(" "))
166 # Set the command argument depending on cmd or powershell and the rest of it
167 exec_cmd.append(regex_match.group("command"))
168 if post_args := regex_match.group("post_args"):
169 exec_cmd.append(post_args.strip())
170 else:
171 # For anything else using -EncodedCommand or else, just split on space.
172 exec_cmd.extend(cmd.split(" "))
173 else:
174 if self.get_option("remote_user") != "root":
175 self._display.vvv(
176 f"INFO: Running as non-root user: {self.get_option('remote_user')}, \
177 trying to run 'incus exec' with become method: {self.get_option('incus_become_method')}",
178 host=self._instance(),
179 )
180 exec_cmd.extend([self.get_option("incus_become_method"), self.get_option("remote_user"), "-c"])
181
182 exec_cmd.extend([self.get_option("executable"), "-c", cmd])
183
184 return exec_cmd
185
186 def _instance(self):
187 # Return only the leading part of the FQDN as the instance name
188 # as Incus instance names cannot be a FQDN.
189 return self.get_option("remote_addr").split(".")[0]
190
191 def exec_command(self, cmd, in_data=None, sudoable=True):
192 """execute a command on the Incus host"""
193 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
194
195 self._display.vvv(f"EXEC {cmd}", host=self._instance())
196
197 local_cmd = self._build_command(cmd)
198 self._display.vvvvv(f"EXEC {local_cmd}", host=self._instance())
199
200 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
201 in_data = to_bytes(in_data, errors="surrogate_or_strict", nonstring="passthru")
202
203 process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
204 stdout, stderr = process.communicate(in_data)
205
206 stdout = to_text(stdout)
207 stderr = to_text(stderr)
208
209 if stderr.startswith("Error: ") and stderr.rstrip().endswith(": Instance is not running"):
210 raise AnsibleConnectionFailure(
211 f"instance not running: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
212 )
213
214 if stderr.startswith("Error: ") and stderr.rstrip().endswith(": Instance not found"):
215 raise AnsibleConnectionFailure(
216 f"instance not found: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
217 )
218
219 if stderr.startswith("Error: ") and ": User does not have permission " in stderr:
220 raise AnsibleConnectionFailure(
221 f"instance access denied: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
222 )
223
224 if stderr.startswith("Error: ") and ": User does not have entitlement " in stderr:
225 raise AnsibleConnectionFailure(
226 f"instance access denied: {self._instance()} (remote={self.get_option('remote')}, project={self.get_option('project')})"
227 )
228
229 return process.returncode, stdout, stderr
230
231 def _get_remote_uid_gid(self) -> tuple[int, int]:
232 """Get the user and group ID of 'remote_user' from the instance."""
233
234 rc, uid_out, err = self.exec_command("/bin/id -u")
235 if rc != 0:
236 raise AnsibleError(f"Failed to get remote uid for user {self.get_option('remote_user')}: {err}")
237 uid = uid_out.strip()
238
239 rc, gid_out, err = self.exec_command("/bin/id -g")
240 if rc != 0:
241 raise AnsibleError(f"Failed to get remote gid for user {self.get_option('remote_user')}: {err}")
242 gid = gid_out.strip()
243
244 return int(uid), int(gid)
245
246 def put_file(self, in_path, out_path):
247 """put a file from local to Incus"""
248 super().put_file(in_path, out_path)
249
250 self._display.vvv(f"PUT {in_path} TO {out_path}", host=self._instance())
251
252 if not os.path.isfile(to_bytes(in_path, errors="surrogate_or_strict")):
253 raise AnsibleFileNotFound(f"input path is not a file: {in_path}")
254
255 if not getattr(self._shell, "_IS_WINDOWS", False) and self.get_option("remote_user") != "root":
256 uid, gid = self._get_remote_uid_gid()
257 local_cmd = [
258 self._incus_cmd,
259 "--project",
260 self.get_option("project"),
261 "file",
262 "push",
263 "--uid",
264 str(uid),
265 "--gid",
266 str(gid),
267 "--quiet",
268 in_path,
269 f"{self.get_option('remote')}:{self._instance()}/{out_path}",
270 ]
271 else:
272 local_cmd = [
273 self._incus_cmd,
274 "--project",
275 self.get_option("project"),
276 "file",
277 "push",
278 "--quiet",
279 in_path,
280 f"{self.get_option('remote')}:{self._instance()}/{out_path}",
281 ]
282
283 self._display.vvvvv(f"PUT {local_cmd}", host=self._instance())
284
285 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
286
287 call(local_cmd)
288
289 def fetch_file(self, in_path, out_path):
290 """fetch a file from Incus to local"""
291 super().fetch_file(in_path, out_path)
292
293 self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self._instance())
294
295 local_cmd = [
296 self._incus_cmd,
297 "--project",
298 self.get_option("project"),
299 "file",
300 "pull",
301 "--quiet",
302 f"{self.get_option('remote')}:{self._instance()}/{in_path}",
303 out_path,
304 ]
305
306 local_cmd = [to_bytes(i, errors="surrogate_or_strict") for i in local_cmd]
307
308 call(local_cmd)
309
310 def close(self):
311 """close the connection (nothing to do here)"""
312 super().close()
313
314 self._connected = False