Debian Codegraph @

ansible_collections/community/general/plugins/modules/uv_python.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2026 Mariam Ahhttouche <[email protected]>
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: uv_python
10 short_description: Manage Python versions and installations using the C(uv) Python package manager
11 description:
12 - Install, uninstall or upgrade Python versions managed by C(uv).
13 version_added: "13.0.0"
14 requirements:
15 - C(uv) must be installed and available in E(PATH) and must be at least 0.8.0.
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 version:
25 description:
26 - Python version to manage.
27 - "Not all canonical Python versions are supported in this release. Valid version numbers consist of two or three dot-separated
28 numeric components, with an optional 'pre-release' tag at the end such as V(3.12), V(3.12.3), V(3.15.0a5)."
29 - Advanced uv selectors such as V(>=3.12,<3.13) or V([email protected]) are not supported in this release.
30 - When you specify only a major.minor version, make sure the number is enclosed in quotes so that it gets parsed correctly.
31 Note that in case only a major.minor version are specified behavior depends on the O(state) parameter.
32 type: str
33 required: true
34 state:
35 description:
36 - Desired state of the specified Python version.
37 - "V(present) ensures the specified version is installed. If you specify a full patch version (for example O(version=3.12.3)),
38 that exact version is be installed if not already present. If you only specify a minor version (for example V(3.12)),
39 the latest available patch version for that minor release is installed only if no patch version for that minor release
40 is currently installed (including patch versions not managed by C(uv)). RV(python_versions) and RV(python_paths)
41 lengths are always equal to one for this state."
42 - "V(absent) ensures the specified version is removed. If you specify a full patch version, only that exact patch version
43 is removed. If you only specify a minor version (for example V(3.12)), all installed patch versions for that minor
44 release are removed. If you specify a version that is not installed, no changes are made. RV(python_versions) and
45 RV(python_paths) lengths can be higher or equal to one in this state."
46 - V(latest) ensures the latest available patch version for the specified version is installed. If you only specify
47 a minor version (for example V(3.12)), the latest available patch version for that minor release is always installed.
48 If another patch version is already installed but is not the latest, the latest patch version is installed. The latest
49 patch version installed depends on the C(uv) version, since available Python versions are frozen per C(uv) release.
50 RV(python_versions) and RV(python_paths) lengths are always equal to one in this state. This state does not use C(uv python upgrade).
51 type: str
52 choices: [present, absent, latest]
53 default: present
54 seealso:
55 - name: C(uv) documentation
56 description: Python versions management with C(uv).
57 link: https://docs.astral.sh/uv/concepts/python-versions/
58 - name: C(uv) CLI documentation
59 description: C(uv) CLI reference guide.
60 link: https://docs.astral.sh/uv/reference/cli/#uv-python
61 author: Mariam Ahhttouche (@mriamah)
62 """
63
64 EXAMPLES = r"""
65 - name: Install Python 3.14
66 community.general.uv_python:
67 version: "3.14"
68
69 - name: Upgrade Python 3.14
70 community.general.uv_python:
71 version: "3.14"
72 state: latest
73
74 - name: Remove Python 3.13.5
75 community.general.uv_python:
76 version: 3.13.5
77 state: absent
78 """
79
80 RETURN = r"""
81 python_versions:
82 description: List of Python versions changed.
83 returned: success
84 type: list
85 elements: str
86 sample:
87 - "3.13.5"
88 python_paths:
89 description: List of installation paths of Python versions changed.
90 returned: success
91 type: list
92 elements: str
93 sample:
94 - "/root/.local/share/uv/python/cpython-3.13.5-linux-x86_64-gnu/bin/python3.13"
95 stdout:
96 description: Stdout of the executed command.
97 returned: success
98 type: str
99 sample: ""
100 stderr:
101 description: Stderr of the executed command.
102 returned: success
103 type: str
104 sample: ""
105 rc:
106 description: Return code of the executed command.
107 returned: success
108 type: int
109 sample: 0
110 """
111
112 import json
113 import re
114 from pathlib import Path
115
116 from ansible.module_utils.basic import AnsibleModule
117 from ansible.module_utils.compat.version import LooseVersion, StrictVersion
118
119 MINIMUM_UV_VERSION = "0.8.0"
120
121
122 class UV:
123 """
124 Module for managing Python versions and installations using "uv python" command
125 """
126
127 def __init__(self, module: AnsibleModule) -> None:
128 self.module = module
129 self.bin_path = self.module.get_bin_path("uv", required=True)
130 self._ensure_min_uv_version()
131 try:
132 self.python_version = StrictVersion(module.params["version"])
133 self.python_version_str = str(self.python_version)
134 except (ValueError, AttributeError):
135 self.module.fail_json(
136 msg=(
137 "Unsupported version format. Valid version numbers consist of two or three dot-separated numeric components"
138 " with an optional 'pre-release' tag on the end (for example 3.12, 3.12.3, 3.15.0a5) are supported in this release."
139 )
140 )
141
142 def _ensure_min_uv_version(self) -> None:
143 cmd = [self.bin_path, "--version", "--color", "never"]
144 dummy_rc, out, dummy_err = self.module.run_command(cmd, check_rc=True)
145 try:
146 detected = re.search(r"\b\d+(?:\.\d+)+\b", out).group() # type: ignore[union-attr]
147 if LooseVersion(detected) < LooseVersion(MINIMUM_UV_VERSION):
148 self.module.fail_json(
149 msg=f"uv_python module requires uv >= {MINIMUM_UV_VERSION}",
150 detected_version=detected,
151 required_version=MINIMUM_UV_VERSION,
152 )
153 except AttributeError:
154 self.module.warn("Could not get installed uv version, skipping uv version check")
155
156 def install_python(self) -> tuple[bool, str, str, int, list[str], list[str]]:
157 """
158 Runs command 'uv python install X.Y.Z' which installs specified python version.
159 If patch version is not specified uv installs latest available patch version.
160 Returns:
161 - boolean to indicate if method changed state
162 - command's stdout
163 - command's stderr
164 - command's return code
165 - list of installed versions
166 - list of installation paths for each installed version
167 """
168 find_rc, existing_version, dummy_err = self._find_python("--show-version")
169 if find_rc == 0:
170 dummy_rc, version_path, dummy_err = self._find_python()
171 return False, "", "", 0, [existing_version], [version_path]
172 if self.module.check_mode:
173 latest_version, dummy_path = self._get_latest_patch_release("--managed-python")
174 # when uv does not find any available patch version the install command will fail
175 if not latest_version:
176 self.module.fail_json(msg=(f"Version {self.python_version_str} is not available."))
177 return True, "", "", 0, [latest_version], [""]
178 rc, out, err = self._exec(self.python_version_str, "install", check_rc=True)
179 latest_version, path = self._get_latest_patch_release("--only-installed", "--managed-python")
180 return True, out, err, rc, [latest_version], [path]
181
182 def uninstall_python(self) -> tuple[bool, str, str, int, list, list]:
183 """
184 Runs command 'uv python uninstall X.Y.Z' which removes specified python version from environment.
185 If patch version is not specified all correspending installed patch versions are removed.
186 Returns:
187 tuple [bool, str, str, int, list, list]
188 - boolean to indicate if method changed state
189 - command's stdout
190 - command's stderr
191 - command's return code
192 - list of uninstalled versions
193 - list of previous installation paths for each uninstalled version
194 """
195 installed_versions, install_paths = self._get_installed_versions("--managed-python")
196 if not installed_versions:
197 return False, "", "", 0, [], []
198 if self.module.check_mode:
199 return True, "", "", 0, installed_versions, install_paths
200 rc, out, err = self._exec(self.python_version_str, "uninstall", check_rc=True)
201 return True, out, err, rc, installed_versions, install_paths
202
203 def upgrade_python(self) -> tuple[bool, str, str, int, list, list]:
204 """
205 Runs command 'uv python install X.Y.Z' with latest patch version available.
206 Returns:
207 - boolean to indicate if method changed state
208 - command's stdout
209 - command's stderr
210 - command's return code
211 - list of installed versions
212 - list of installation paths for each installed version
213 """
214 rc, installed_version_str, dummy_err = self._find_python("--show-version")
215 installed_version = self._parse_version(installed_version_str)
216 latest_version_str, dummy_path = self._get_latest_patch_release("--managed-python")
217 if not latest_version_str:
218 self.module.fail_json(msg=f"Version {self.python_version_str} is not available.")
219 if rc == 0 and installed_version >= StrictVersion(latest_version_str):
220 dummy_rc, install_path, dummy_err = self._find_python()
221 return False, "", "", rc, [installed_version_str], [install_path]
222 if self.module.check_mode:
223 return True, "", "", 0, [latest_version_str], []
224 # it's possible to have latest version already installed but not used as default
225 # so in this case 'uv python install' will set latest version as default
226 rc, out, err = self._exec(latest_version_str, "install", check_rc=True)
227 latest_version_str, latest_path = self._get_latest_patch_release("--only-installed", "--managed-python")
228 return True, out, err, rc, [latest_version_str], [latest_path]
229
230 def _exec(self, python_version: str, command: str, *args, check_rc: bool = False) -> tuple[int, str, str]:
231 """
232 Execute a uv python subcommand.
233 Args:
234 python_version: Python version specifier (e.g. "3.12", "3.12.3").
235 command (str): uv python subcommand (e.g. "install", "uninstall", "find").
236 *args: Additional positional arguments passed to the command.
237 check_rc (bool): Whether to fail if the command exits with non-zero return code.
238 """
239 cmd = [
240 self.bin_path,
241 "python",
242 command,
243 python_version,
244 "--color",
245 "never",
246 *args,
247 ]
248 rc, out, err = self.module.run_command(cmd, check_rc=check_rc)
249 return rc, out, err
250
251 def _find_python(self, *args, check_rc: bool = False) -> tuple[int, str, str]:
252 """
253 Runs command 'uv python find' which returns path of installed patch releases for a given python version.
254 If multiple patch versions are installed, "uv python find" returns the one used by default
255 if inside a virtualenv otherwise it returns latest installed patch version.
256 Args:
257 *args: Additional positional arguments passed to _exec.
258 check_rc (bool): Whether to fail if the command exits with non-zero return code.
259 """
260 rc, out, err = self._exec(self.python_version_str, "find", *args, check_rc=check_rc)
261 if rc == 0:
262 out = out.strip()
263 return rc, out, err
264
265 def _list_python(self, *args, check_rc: bool = False) -> tuple[int, list, str]:
266 """
267 Runs command 'uv python list' (which returns list of installed patch releases for a given python version).
268 Official documentation https://docs.astral.sh/uv/reference/cli/#uv-python-list
269 Args:
270 *args: Additional positional arguments passed to _exec.
271 check_rc (bool): Whether to fail if the command exits with non-zero return code.
272 """
273 rc, out, err = self._exec(
274 self.python_version_str,
275 "list",
276 "--output-format",
277 "json",
278 *args,
279 check_rc=check_rc,
280 )
281 pythons_installed = []
282 try:
283 pythons_installed = json.loads(out)
284 # convert path to absolute path since in some recent uv releases "uv python list" returns relative install paths instead of absolute paths
285 for result in pythons_installed:
286 path = result.get("path", "")
287 if path and not Path(path).is_absolute():
288 result["path"] = str(Path(path).resolve())
289 except json.decoder.JSONDecodeError:
290 self.module.debug("No Python installation found.")
291 return rc, pythons_installed, err
292
293 def _get_latest_patch_release(self, *args) -> tuple[str, str]:
294 """
295 Returns latest available patch release for a given python version.
296 Args:
297 *args: Additional positional arguments passed to _list_python.
298 Returns:
299 - latest found patch version in format X.Y.Z
300 - installation path of latest patch version if version exists
301 """
302 latest_version = path = ""
303 # 'uv python list' returns versions in descending order but we sort them just in case future uv behavior changes
304 dummy_rc, results, dummy_err = self._list_python(*args)
305 valid_results = self._filter_valid_versions(results)
306 if valid_results:
307 version = max(valid_results, key=lambda result: result["parsed_version"])
308 latest_version = version.get("version", "")
309 path = version.get("path", "")
310 return latest_version, path
311
312 def _get_installed_versions(self, *args) -> tuple[list, list]:
313 """
314 Returns installed patch releases for a given python version.
315 Args:
316 *args: Additional positional arguments passed to _list_python.
317 Returns:
318 - list of latest found patch versions
319 - list of installation paths of installed versions
320 """
321 dummy_rc, results, dummy_err = self._list_python("--only-installed", *args)
322 if results:
323 return [result.get("version") for result in results], [result.get("path") for result in results]
324 return [], []
325
326 def _filter_valid_versions(self, results: list):
327 valid_results = []
328 for result in results:
329 version = result.get("version", "")
330 try:
331 result["parsed_version"] = StrictVersion(version)
332 valid_results.append(result)
333 except ValueError:
334 self.module.debug(f"Filtering out version {version!r} since it's not supported by uv_python module.")
335 return valid_results
336
337 @staticmethod
338 def _parse_version(version_str: str):
339 try:
340 return StrictVersion(version_str)
341 except ValueError:
342 return StrictVersion("0")
343
344
345 def main():
346 module = AnsibleModule(
347 argument_spec=dict(
348 version=dict(type="str", required=True),
349 state=dict(type="str", default="present", choices=["present", "absent", "latest"]),
350 ),
351 supports_check_mode=True,
352 )
353
354 result = dict(
355 changed=False,
356 stdout="",
357 stderr="",
358 rc=0,
359 python_versions=[],
360 python_paths=[],
361 failed=False,
362 )
363 state = module.params["state"]
364 exec_result = {}
365 uv = UV(module)
366
367 if state == "present":
368 exec_result = dict(
369 zip(
370 [
371 "changed",
372 "stdout",
373 "stderr",
374 "rc",
375 "python_versions",
376 "python_paths",
377 ],
378 uv.install_python(),
379 )
380 )
381 elif state == "absent":
382 exec_result = dict(
383 zip(
384 [
385 "changed",
386 "stdout",
387 "stderr",
388 "rc",
389 "python_versions",
390 "python_paths",
391 ],
392 uv.uninstall_python(),
393 )
394 )
395 elif state == "latest":
396 exec_result = dict(
397 zip(
398 [
399 "changed",
400 "stdout",
401 "stderr",
402 "rc",
403 "python_versions",
404 "python_paths",
405 ],
406 uv.upgrade_python(),
407 )
408 )
409
410 result.update(exec_result)
411
412 module.exit_json(**result)
413
414
415 if __name__ == "__main__":
416 main()