Debian Codegraph @

lib/ansible/modules/pip.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Matt Wright <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = """
10 ---
11 module: pip
12 short_description: Manages Python library dependencies
13 description:
14 - "Manage Python library dependencies. To use this module, one of the following keys is required: O(name)
15 or O(requirements)."
16 version_added: "0.7"
17 options:
18 name:
19 description:
20 - The name of a Python library to install or the url(bzr+,hg+,git+,svn+) of the remote package.
21 - This can be a list (since 2.2) and contain version specifiers (since 2.7).
22 type: list
23 elements: str
24 version:
25 description:
26 - The version number to install of the Python library specified in the O(name) parameter.
27 type: str
28 requirements:
29 description:
30 - The path to a pip requirements file, which should be local to the remote system.
31 File can be specified as a relative path if using the O(chdir) option.
32 type: str
33 virtualenv:
34 description:
35 - An optional path to a I(virtualenv) directory to install into.
36 It cannot be specified together with the O(executable) parameter
37 (added in 2.1).
38 If the virtualenv does not exist, it will be created before installing
39 packages. The optional O(virtualenv_site_packages), O(virtualenv_command),
40 and O(virtualenv_python) options affect the creation of the virtualenv.
41 - When O(chdir) is set, a relative path is resolved relative to O(chdir).
42 type: path
43 virtualenv_site_packages:
44 description:
45 - Whether the virtual environment will inherit packages from the
46 global C(site-packages) directory. Note that if this setting is
47 changed on an already existing virtual environment it will not
48 have any effect, the environment must be deleted and newly
49 created.
50 type: bool
51 default: "no"
52 version_added: "1.0"
53 virtualenv_command:
54 description:
55 - The command or a pathname to the command to create the virtual
56 environment with. For example V(pyvenv), V(virtualenv),
57 V(virtualenv2), V(~/bin/virtualenv), V(/usr/local/bin/virtualenv).
58 type: path
59 default: virtualenv
60 version_added: "1.1"
61 virtualenv_python:
62 description:
63 - The Python executable used for creating the virtual environment.
64 For example V(python3.13). When not specified, the
65 Python version used to run the ansible module is used. This parameter
66 should not be used when O(virtualenv_command) is using V(pyvenv) or
67 the C(-m venv) module.
68 type: str
69 version_added: "2.0"
70 state:
71 description:
72 - The state of module.
73 - The V(forcereinstall) option is only available in Ansible 2.1 and above.
74 type: str
75 choices: [ absent, forcereinstall, latest, present ]
76 default: present
77 extra_args:
78 description:
79 - Extra arguments passed to C(pip).
80 type: str
81 version_added: "1.0"
82 editable:
83 description:
84 - Pass the editable flag to all packages.
85 type: bool
86 default: 'no'
87 version_added: "2.0"
88 chdir:
89 description:
90 - cd into this directory before running the command.
91 - When O(virtualenv) is a relative path, it is resolved relative to O(chdir).
92 type: path
93 version_added: "1.3"
94 executable:
95 description:
96 - The explicit executable or pathname for the C(pip) executable,
97 if different from the Ansible Python interpreter. For
98 example V(pip3.13), if there are multiple Python installations
99 in the system and you want to run pip for the Python 3.13 installation.
100 - Mutually exclusive with O(virtualenv) (added in 2.1).
101 - Does not affect the Ansible Python interpreter.
102 - The C(setuptools) package must be installed for both the Ansible Python interpreter
103 and for the version of Python specified by this option.
104 type: path
105 version_added: "1.3"
106 umask:
107 description:
108 - The system umask to apply before installing the pip package. This is
109 useful, for example, when installing on systems that have a very
110 restrictive umask by default (e.g., C(0077)) and you want to C(pip install)
111 packages which are to be used by all users. Note that this requires you
112 to specify desired umask mode as an octal string, (e.g., C(0022)).
113 type: str
114 version_added: "2.1"
115 break_system_packages:
116 description:
117 - Allow C(pip) to modify an externally-managed Python installation as defined by PEP 668.
118 - This is typically required when installing packages outside a virtual environment on modern systems.
119 type: bool
120 default: false
121 version_added: "2.17"
122 extends_documentation_fragment:
123 - action_common_attributes
124 attributes:
125 check_mode:
126 support: full
127 diff_mode:
128 support: none
129 platform:
130 platforms: posix
131 notes:
132 - Python installations marked externally-managed (as defined by PEP668) cannot be updated by pip versions >= 23.0.1 without the use of
133 a virtual environment or setting the O(break_system_packages) option.
134 - The virtualenv (U(http://www.virtualenv.org/)) must be
135 installed on the remote host if the virtualenv parameter is specified and
136 the virtualenv needs to be created.
137 - Although it executes using the Ansible Python interpreter, the pip module shells out to
138 run the actual pip command, so it can use any pip version you specify with O(executable).
139 By default, it uses the pip version for the Ansible Python interpreter.
140 - The interpreter used by Ansible
141 (see R(ansible_python_interpreter, ansible_python_interpreter))
142 requires the setuptools package, regardless of the version of pip set with
143 the O(executable) option.
144 requirements:
145 - pip
146 - virtualenv
147 - setuptools or packaging
148 author:
149 - Matt Wright (@mattupstate)
150 """
151
152 EXAMPLES = """
153 - name: Install bottle python package
154 ansible.builtin.pip:
155 name: bottle
156
157 - name: Install bottle python package on version 0.11
158 ansible.builtin.pip:
159 name: bottle==0.11
160
161 - name: Install bottle python package with version specifiers
162 ansible.builtin.pip:
163 name: bottle>0.10,<0.20,!=0.11
164
165 - name: Install multi python packages with version specifiers
166 ansible.builtin.pip:
167 name:
168 - django>1.11.0,<1.12.0
169 - bottle>0.10,<0.20,!=0.11
170
171 - name: Install python package using a proxy
172 ansible.builtin.pip:
173 name: six
174 environment:
175 http_proxy: 'http://127.0.0.1:8080'
176 https_proxy: 'https://127.0.0.1:8080'
177
178 # You do not have to supply '-e' option in extra_args
179 - name: Install MyApp using one of the remote protocols (bzr+,hg+,git+,svn+)
180 ansible.builtin.pip:
181 name: svn+http://myrepo/svn/MyApp#egg=MyApp
182
183 - name: Install MyApp using one of the remote protocols (bzr+,hg+,git+)
184 ansible.builtin.pip:
185 name: git+http://myrepo/app/MyApp
186
187 - name: Install MyApp from local tarball
188 ansible.builtin.pip:
189 name: file:///path/to/MyApp.tar.gz
190
191 - name: Install bottle into the specified (virtualenv), inheriting none of the globally installed modules
192 ansible.builtin.pip:
193 name: bottle
194 virtualenv: /my_app/venv
195
196 - name: Install bottle into the specified (virtualenv), inheriting globally installed modules
197 ansible.builtin.pip:
198 name: bottle
199 virtualenv: /my_app/venv
200 virtualenv_site_packages: yes
201
202 - name: Install bottle into the specified (virtualenv), using Python 3.13
203 ansible.builtin.pip:
204 name: bottle
205 virtualenv: /my_app/venv
206 virtualenv_command: virtualenv-3.13
207
208 - name: Install bottle within a user home directory
209 ansible.builtin.pip:
210 name: bottle
211 extra_args: --user
212
213 - name: Install specified python requirements
214 ansible.builtin.pip:
215 requirements: /my_app/requirements.txt
216
217 - name: Install specified python requirements in indicated (virtualenv)
218 ansible.builtin.pip:
219 requirements: /my_app/requirements.txt
220 virtualenv: /my_app/venv
221
222 - name: Install specified python requirements and custom Index URL
223 ansible.builtin.pip:
224 requirements: /my_app/requirements.txt
225 extra_args: -i https://example.com/pypi/simple
226
227 - name: Install specified python requirements offline from a local directory with downloaded packages
228 ansible.builtin.pip:
229 requirements: /my_app/requirements.txt
230 extra_args: "--no-index --find-links=file:///my_downloaded_packages_dir"
231
232 - name: Install bottle for Python 3.13 specifically, using the 'pip3.13' executable
233 ansible.builtin.pip:
234 name: bottle
235 executable: pip3.13
236
237 - name: Install bottle, forcing reinstallation if it's already installed
238 ansible.builtin.pip:
239 name: bottle
240 state: forcereinstall
241
242 - name: Install bottle while ensuring the umask is 0022 (to ensure other users can use it)
243 ansible.builtin.pip:
244 name: bottle
245 umask: "0022"
246 become: True
247
248 - name: Run a module inside a virtual environment
249 block:
250 - name: Ensure the virtual environment exists
251 pip:
252 name: psutil
253 virtualenv: "{{ venv_dir }}"
254 # On Debian-based systems the correct python*-venv package must be installed to use the `venv` module.
255 virtualenv_command: "{{ ansible_python_interpreter }} -m venv"
256
257 - name: Run a module inside the virtual environment
258 wait_for:
259 port: 22
260 vars:
261 # Alternatively, use a block to affect multiple tasks, or use set_fact to affect the remainder of the playbook.
262 ansible_python_interpreter: "{{ venv_python }}"
263
264 vars:
265 venv_dir: /tmp/pick-a-better-venv-path
266 venv_python: "{{ venv_dir }}/bin/python"
267 """
268
269 RETURN = """
270 cmd:
271 description: pip command used by the module
272 returned: success
273 type: str
274 sample: pip2 install ansible six
275 name:
276 description: list of python modules targeted by pip
277 returned: success
278 type: list
279 sample: ['ansible', 'six']
280 requirements:
281 description: Path to the requirements file
282 returned: success, if a requirements file was provided
283 type: str
284 sample: "/srv/git/project/requirements.txt"
285 version:
286 description: Version of the package specified in 'name'
287 returned: success, if a name and version were provided
288 type: str
289 sample: "2.5.1"
290 virtualenv:
291 description: Path to the virtualenv
292 returned: success, if a virtualenv path was provided
293 type: str
294 sample: "/tmp/virtualenv"
295 """
296
297 import argparse
298 import json
299 import os
300 import re
301 import sys
302 import tempfile
303 import operator
304 import shlex
305
306 from ansible.module_utils.compat.version import LooseVersion
307
308 PACKAGING_IMP_ERR = None
309 HAS_PACKAGING = False
310 HAS_SETUPTOOLS = False
311 try:
312 from packaging.requirements import Requirement as parse_requirement
313 HAS_PACKAGING = True
314 except Exception as ex:
315 # This is catching a generic Exception, due to packaging on EL7 raising a TypeError on import
316 HAS_PACKAGING = False
317 PACKAGING_IMP_ERR = ex
318 try:
319 from pkg_resources import Requirement
320 parse_requirement = Requirement.parse # type: ignore[misc,assignment]
321 del Requirement
322 HAS_SETUPTOOLS = True
323 except ImportError:
324 pass
325
326 from ansible.module_utils.common.text.converters import to_native
327 from ansible.module_utils.basic import AnsibleModule, is_executable, missing_required_lib
328 from ansible.module_utils.common.locale import get_best_parsable_locale
329
330
331 #: Python one-liners to be run at the command line that will determine the
332 # installed version for these special libraries. These are libraries that
333 # don't end up in the output of pip freeze.
334 _SPECIAL_PACKAGE_CHECKERS = {
335 'importlib': {
336 'setuptools': 'from importlib.metadata import version; print(version("setuptools"))',
337 'pip': 'from importlib.metadata import version; print(version("pip"))',
338 },
339 'pkg_resources': {
340 'setuptools': 'import setuptools; print(setuptools.__version__)',
341 'pip': 'import pkg_resources; print(pkg_resources.get_distribution("pip").version)',
342 }
343 }
344
345 _VCS_RE = re.compile(r'(svn|git|hg|bzr)\+')
346
347 op_dict = {">=": operator.ge, "<=": operator.le, ">": operator.gt,
348 "<": operator.lt, "==": operator.eq, "!=": operator.ne, "~=": operator.ge}
349
350
351 def _is_vcs_url(name):
352 """Test whether a name is a vcs url or not."""
353 return re.match(_VCS_RE, name)
354
355
356 def _is_venv_command(command):
357 venv_parser = argparse.ArgumentParser()
358 venv_parser.add_argument('-m', type=str)
359 argv = shlex.split(command)
360 if argv[0] == 'pyvenv':
361 return True
362 args, dummy = venv_parser.parse_known_args(argv[1:])
363 if args.m == 'venv':
364 return True
365 return False
366
367
368 def _is_package_name(name):
369 """Test whether the name is a package name or a version specifier."""
370 return not name.lstrip().startswith(tuple(op_dict.keys()))
371
372
373 def _recover_package_name(names):
374 """Recover package names as list from user's raw input.
375
376 :input: a mixed and invalid list of names or version specifiers
377 :return: a list of valid package name
378
379 eg.
380 input: ['django>1.11.1', '<1.11.3', 'ipaddress', 'simpleproject>1.1.0', '<2.0.0']
381 return: ['django>1.11.1,<1.11.3', 'ipaddress', 'simpleproject>1.1.0,<2.0.0']
382
383 input: ['django>1.11.1,<1.11.3,ipaddress', 'simpleproject>1.1.0,<2.0.0']
384 return: ['django>1.11.1,<1.11.3', 'ipaddress', 'simpleproject>1.1.0,<2.0.0']
385 """
386 # rebuild input name to a flat list so we can tolerate any combination of input
387 tmp = []
388 for one_line in names:
389 tmp.extend(one_line.split(","))
390 names = tmp
391
392 # reconstruct the names
393 name_parts = []
394 package_names = []
395 in_brackets = False
396 for name in names:
397 if _is_package_name(name) and not in_brackets:
398 if name_parts:
399 package_names.append(",".join(name_parts))
400 name_parts = []
401 if "[" in name:
402 in_brackets = True
403 if in_brackets and "]" in name:
404 in_brackets = False
405 name_parts.append(name)
406 package_names.append(",".join(name_parts))
407 return package_names
408
409
410 def _get_cmd_options(module, cmd):
411 thiscmd = cmd + " --help"
412 rc, stdout, stderr = module.run_command(thiscmd)
413 if rc != 0:
414 module.fail_json(msg="Could not get output from %s: %s" % (thiscmd, stdout + stderr))
415
416 words = stdout.strip().split()
417 cmd_options = [x for x in words if x.startswith('--')]
418 return cmd_options
419
420
421 def _get_packages(module, pip, chdir):
422 """Return results of pip command to get packages."""
423 # Try 'pip list' command first.
424 command = pip + ['list', '--format=freeze']
425 locale = get_best_parsable_locale(module)
426 lang_env = {'LANG': locale, 'LC_ALL': locale, 'LC_MESSAGES': locale}
427 rc, out, err = module.run_command(command, cwd=chdir, environ_update=lang_env)
428
429 # If there was an error (pip version too old) then use 'pip freeze'.
430 if rc != 0:
431 command = pip + ['freeze']
432 rc, out, err = module.run_command(command, cwd=chdir)
433 if rc != 0:
434 _fail(module, command, out, err)
435
436 return ' '.join(command), out, err
437
438
439 def _is_present(module, req, installed_pkgs, pkg_command):
440 """Return whether or not package is installed."""
441 for pkg in installed_pkgs:
442 if '==' in pkg:
443 pkg_name, pkg_version = pkg.split('==')
444 pkg_name = Package.canonicalize_name(pkg_name)
445 else:
446 continue
447
448 if pkg_name == req.package_name and req.is_satisfied_by(pkg_version):
449 return True
450
451 return False
452
453
454 def _get_pip(module, env=None, executable=None):
455 candidate_pip_basenames = ('pip3',)
456 pip = None
457 if executable is not None:
458 if os.path.isabs(executable):
459 pip = executable
460 else:
461 # If you define your own executable that executable should be the only candidate.
462 # As noted in the docs, executable doesn't work with virtualenvs.
463 candidate_pip_basenames = (executable,)
464 elif executable is None and env is None and _have_pip_module():
465 # If no executable or virtualenv were specified, use the pip module for the current Python interpreter if available.
466 pip = [sys.executable, '-m', 'pip']
467
468 if pip is None:
469 if env is None:
470 opt_dirs = []
471 for basename in candidate_pip_basenames:
472 pip = module.get_bin_path(basename, False, opt_dirs)
473 if pip is not None:
474 break
475 else:
476 # For-else: Means that we did not break out of the loop
477 # (therefore, that pip was not found)
478 module.fail_json(msg='Unable to find any of %s to use. pip'
479 ' needs to be installed.' % ', '.join(candidate_pip_basenames))
480 else:
481 # If we're using a virtualenv we must use the pip from the
482 # virtualenv
483 venv_dir = os.path.join(env, 'bin')
484 candidate_pip_basenames = (candidate_pip_basenames[0], 'pip')
485 for basename in candidate_pip_basenames:
486 candidate = os.path.join(venv_dir, basename)
487 if os.path.exists(candidate) and is_executable(candidate):
488 pip = candidate
489 break
490 else:
491 # For-else: Means that we did not break out of the loop
492 # (therefore, that pip was not found)
493 module.fail_json(msg='Unable to find pip in the virtualenv, %s, ' % env +
494 'under any of these names: %s. ' % (', '.join(candidate_pip_basenames)) +
495 'Make sure pip is present in the virtualenv.')
496
497 if not isinstance(pip, list):
498 pip = [pip]
499
500 return pip
501
502
503 def _have_pip_module(): # type: () -> bool
504 """Return True if the `pip` module can be found using the current Python interpreter, otherwise return False."""
505 try:
506 from importlib.util import find_spec
507 except ImportError:
508 find_spec = None # type: ignore[assignment] # type: ignore[no-redef]
509
510 if find_spec: # type: ignore[truthy-function]
511 # noinspection PyBroadException
512 try:
513 # noinspection PyUnresolvedReferences
514 found = bool(find_spec('pip'))
515 except Exception:
516 found = False
517 else:
518 # noinspection PyDeprecation
519 import imp
520
521 # noinspection PyBroadException
522 try:
523 # noinspection PyDeprecation
524 imp.find_module('pip')
525 except Exception:
526 found = False
527 else:
528 found = True
529
530 return found
531
532
533 def _fail(module, cmd, out, err):
534 msg = ''
535 if out:
536 msg += "stdout: %s" % (out, )
537 if err:
538 msg += "\n:stderr: %s" % (err, )
539 module.fail_json(cmd=cmd, msg=msg)
540
541
542 def _get_package_info(module, package, python_bin=None):
543 """This is only needed for special packages which do not show up in pip freeze
544
545 pip and setuptools fall into this category.
546
547 :returns: a string containing the version number if the package is
548 installed. None if the package is not installed.
549 """
550 if python_bin is None:
551 return
552
553 discovery_mechanism = 'pkg_resources'
554 importlib_rc = module.run_command([python_bin, '-c', 'import importlib.metadata'])[0]
555 if importlib_rc == 0:
556 discovery_mechanism = 'importlib'
557
558 rc, out, err = module.run_command([python_bin, '-c', _SPECIAL_PACKAGE_CHECKERS[discovery_mechanism][package]])
559 if rc:
560 formatted_dep = None
561 else:
562 formatted_dep = '%s==%s' % (package, out.strip())
563 return formatted_dep
564
565
566 def setup_virtualenv(module, env, chdir, out, err):
567 if module.check_mode:
568 module.exit_json(changed=True)
569
570 cmd = shlex.split(module.params['virtualenv_command'])
571
572 # Find the binary for the command in the PATH
573 # and switch the command for the explicit path.
574 if os.path.basename(cmd[0]) == cmd[0]:
575 cmd[0] = module.get_bin_path(cmd[0], True)
576
577 # Add the system-site-packages option if that
578 # is enabled, otherwise explicitly set the option
579 # to not use system-site-packages if that is an
580 # option provided by the command's help function.
581 if module.params['virtualenv_site_packages']:
582 cmd.append('--system-site-packages')
583 else:
584 cmd_opts = _get_cmd_options(module, cmd[0])
585 if '--no-site-packages' in cmd_opts:
586 cmd.append('--no-site-packages')
587
588 virtualenv_python = module.params['virtualenv_python']
589 # -p is a virtualenv option, not compatible with pyenv or venv
590 # this conditional validates if the command being used is not any of them
591 if not _is_venv_command(module.params['virtualenv_command']):
592 if virtualenv_python:
593 cmd.append('-p%s' % virtualenv_python)
594 else:
595 # This code mimics the upstream behaviour of using the python
596 # which invoked virtualenv to determine which python is used
597 # inside of the virtualenv (when none are specified).
598 cmd.append('-p%s' % sys.executable)
599
600 # if venv or pyvenv are used and virtualenv_python is defined, then
601 # virtualenv_python is ignored, this has to be acknowledged
602 elif module.params['virtualenv_python']:
603 module.fail_json(
604 msg='virtualenv_python should not be used when'
605 ' using the venv module or pyvenv as virtualenv_command'
606 )
607
608 cmd.append(env)
609 rc, out_venv, err_venv = module.run_command(cmd, cwd=chdir)
610 out += out_venv
611 err += err_venv
612 if rc != 0:
613 _fail(module, cmd, out, err)
614 return out, err, cmd
615
616
617 def _resolve_package_names(
618 module: AnsibleModule,
619 package_list: list[Package],
620 pip: list[str],
621 python_bin: str,
622 ) -> list[Package]:
623 """Resolve package references in the list.
624
625 This helper function downloads metadata from PyPI
626 using ``pip install``'s ability to return JSON.
627 """
628 pkgs_to_resolve = [pkg for pkg in package_list if not pkg.has_requirement]
629
630 if not pkgs_to_resolve:
631 return package_list
632
633 # pip install --dry-run is not available in pip versions older than 22.2 and it doesn't
634 # work correctly on all cases until 24.1, so check for this and use the non-resolved
635 # package names if pip is outdated.
636 pip_dep = _get_package_info(module, "pip", python_bin)
637
638 installed_pip = LooseVersion(pip_dep.split('==')[1])
639 minimum_pip = LooseVersion("24.1")
640
641 if installed_pip < minimum_pip:
642 module.warn("Using check mode with packages from vcs urls, file paths, or archives will not behave as expected when using pip versions <24.1.")
643 return package_list # Just use the default behavior
644
645 with tempfile.NamedTemporaryFile() as tmpfile:
646 # Uses a tmpfile instead of capturing and parsing stdout because it circumvents the need to fuss with ANSI color output
647 module.run_command(
648 [
649 *pip, 'install',
650 '--dry-run',
651 '--ignore-installed',
652 f'--report={tmpfile.name}',
653 *map(str, pkgs_to_resolve),
654 ],
655 check_rc=True,
656 )
657 report = json.load(tmpfile)
658
659 package_objects = (
660 Package(install_report['metadata']['name'], version_string=install_report['metadata']['version'])
661 for install_report in report['install']
662 )
663
664 other_packages = (pkg for pkg in package_list if pkg.has_requirement)
665 return [*other_packages, *package_objects]
666
667
668 class Package:
669 """Python distribution package metadata wrapper.
670
671 A wrapper class for Requirement, which provides
672 API to parse package name, version specifier,
673 test whether a package is already satisfied.
674 """
675
676 _CANONICALIZE_RE = re.compile(r'[-_.]+')
677
678 def __init__(self, name_string, version_string=None):
679 self._plain_package = False
680 self.package_name = name_string
681 self._requirement = None
682
683 if version_string:
684 version_string = version_string.lstrip()
685 separator = '==' if version_string[0].isdigit() else ' '
686 name_string = separator.join((name_string, version_string))
687 try:
688 self._requirement = parse_requirement(name_string)
689 # old pkg_resource will replace 'setuptools' with 'distribute' when it's already installed
690 project_name = Package.canonicalize_name(
691 getattr(self._requirement, 'name', None) or getattr(self._requirement, 'project_name', None)
692 )
693 if project_name == "distribute" and "setuptools" in name_string:
694 self.package_name = "setuptools"
695 else:
696 self.package_name = project_name
697 self._plain_package = True
698 except ValueError as e:
699 pass
700
701 @property
702 def has_version_specifier(self):
703 if self._plain_package:
704 return bool(getattr(self._requirement, 'specifier', None) or getattr(self._requirement, 'specs', None))
705 return False
706
707 def is_satisfied_by(self, version_to_test):
708 if not self._plain_package:
709 return False
710 try:
711 return self._requirement.specifier.contains(version_to_test, prereleases=True)
712 except AttributeError:
713 # old setuptools has no specifier, do fallback
714 version_to_test = LooseVersion(version_to_test)
715 return all(
716 op_dict[op](version_to_test, LooseVersion(ver))
717 for op, ver in self._requirement.specs
718 )
719
720 @property
721 def has_requirement(self) -> bool:
722 """Compute whether the object represents complex requirement."""
723 return self._requirement is not None
724
725 @staticmethod
726 def canonicalize_name(name):
727 # This is taken from PEP 503.
728 return Package._CANONICALIZE_RE.sub("-", name).lower()
729
730 def __str__(self):
731 if self._plain_package:
732 return to_native(self._requirement)
733 return self.package_name
734
735
736 def main():
737 state_map = dict(
738 present=['install'],
739 absent=['uninstall', '-y'],
740 latest=['install', '-U'],
741 forcereinstall=['install', '-U', '--force-reinstall'],
742 )
743
744 module = AnsibleModule(
745 argument_spec=dict(
746 state=dict(type='str', default='present', choices=list(state_map.keys())),
747 name=dict(type='list', elements='str'),
748 version=dict(type='str'),
749 requirements=dict(type='str'),
750 virtualenv=dict(type='path'),
751 virtualenv_site_packages=dict(type='bool', default=False),
752 virtualenv_command=dict(type='path', default='virtualenv'),
753 virtualenv_python=dict(type='str'),
754 extra_args=dict(type='str'),
755 editable=dict(type='bool', default=False),
756 chdir=dict(type='path'),
757 executable=dict(type='path'),
758 umask=dict(type='str'),
759 break_system_packages=dict(type='bool', default=False),
760 ),
761 required_one_of=[['name', 'requirements']],
762 mutually_exclusive=[
763 ['name', 'requirements'],
764 ['executable', 'virtualenv'],
765 ['editable', 'requirements'],
766 ],
767 supports_check_mode=True,
768 )
769
770 if not HAS_SETUPTOOLS and not HAS_PACKAGING:
771 module.fail_json(msg=missing_required_lib("packaging"),
772 exception=PACKAGING_IMP_ERR)
773
774 state = module.params['state']
775 name = module.params['name']
776 version = module.params['version']
777 requirements = module.params['requirements']
778 extra_args = module.params['extra_args']
779 chdir = module.params['chdir']
780 umask = module.params['umask']
781 env = module.params['virtualenv']
782 editable = module.params['editable']
783
784 venv_created = False
785 if env:
786 if chdir:
787 env = os.path.join(chdir, env)
788 env = os.path.abspath(env)
789
790 if umask and not isinstance(umask, int):
791 try:
792 umask = int(umask, 8)
793 except Exception:
794 module.fail_json(msg="umask must be an octal integer",
795 details=to_native(sys.exc_info()[1]))
796
797 old_umask = None
798 if umask is not None:
799 old_umask = os.umask(umask)
800 try:
801 if state == 'latest' and version is not None:
802 module.fail_json(msg='version is incompatible with state=latest')
803
804 if chdir is None:
805 # this is done to avoid permissions issues with privilege escalation and virtualenvs
806 chdir = tempfile.gettempdir()
807
808 err = ''
809 out = ''
810 venv_cmd = ''
811
812 if env:
813 if not os.path.exists(os.path.join(env, 'bin', 'activate')):
814 venv_created = True
815 out, err, venv_cmd = setup_virtualenv(module, env, chdir, out, err)
816 py_bin = os.path.join(env, 'bin', 'python')
817 else:
818 py_bin = module.params['executable'] or sys.executable
819
820 pip = _get_pip(module, env, module.params['executable'])
821
822 cmd = pip + state_map[state]
823
824 # If there's a virtualenv we want things we install to be able to use other
825 # installations that exist as binaries within this virtualenv. Example: we
826 # install cython and then gevent -- gevent needs to use the cython binary,
827 # not just a python package that will be found by calling the right python.
828 # So if there's a virtualenv, we add that bin/ to the beginning of the PATH
829 # in run_command by setting path_prefix here.
830 path_prefix = None
831 if env:
832 path_prefix = os.path.join(env, 'bin')
833
834 # Automatically apply -e option to extra_args when source is a VCS url. VCS
835 # includes those beginning with svn+, git+, hg+ or bzr+
836 has_vcs = False
837 if name:
838 for pkg in name:
839 if pkg and _is_vcs_url(pkg):
840 has_vcs = True
841 break
842
843 # convert raw input package names to Package instances
844 packages = [Package(pkg) for pkg in _recover_package_name(name)]
845 # check invalid combination of arguments
846 if version is not None:
847 if len(packages) > 1:
848 module.fail_json(
849 msg="'version' argument is ambiguous when installing multiple package distributions. "
850 "Please specify version restrictions next to each package in 'name' argument."
851 )
852 if packages[0].has_version_specifier:
853 module.fail_json(
854 msg="The 'version' argument conflicts with any version specifier provided along with a package name. "
855 "Please keep the version specifier, but remove the 'version' argument."
856 )
857 # if the version specifier is provided by version, append that into the package
858 packages[0] = Package(to_native(packages[0]), version)
859
860 if extra_args:
861 cmd.extend(shlex.split(extra_args))
862
863 if module.params['break_system_packages']:
864 # Using an env var instead of the `--break-system-packages` option, to avoid failing under pip 23.0.0 and earlier.
865 # See: https://github.com/pypa/pip/pull/11780
866 os.environ['PIP_BREAK_SYSTEM_PACKAGES'] = '1'
867
868 if name:
869 for p in packages:
870 if editable:
871 cmd.append('-e')
872 cmd.append(to_native(p))
873 elif requirements:
874 cmd.extend(['-r', requirements])
875 elif venv_created and not name and not requirements:
876 # ONLY creating an empty venv
877 module.exit_json(changed=venv_created, cmd=venv_cmd, name=name, version=version,
878 state=state, requirements=requirements, virtualenv=env,
879 stdout=out, stderr=err)
880 else:
881 module.warn("No valid name or requirements file found.")
882 module.exit_json(changed=False)
883
884 if module.check_mode:
885 if extra_args or requirements or state == 'latest' or not name:
886 module.exit_json(changed=True)
887
888 pkg_cmd, out_pip, err_pip = _get_packages(module, pip, chdir)
889
890 out += out_pip
891 err += err_pip
892
893 changed = False
894 if name:
895 pkg_list = [p for p in out.split('\n') if not p.startswith('You are using') and not p.startswith('You should consider') and p]
896
897 if pkg_cmd.endswith(' freeze') and ('pip' in name or 'setuptools' in name):
898 # Older versions of pip (pre-1.3) do not have pip list.
899 # pip freeze does not list setuptools or pip in its output
900 # So we need to get those via a specialcase
901 for pkg in ('setuptools', 'pip'):
902 if pkg in name:
903 formatted_dep = _get_package_info(module, pkg, py_bin)
904 if formatted_dep is not None:
905 pkg_list.append(formatted_dep)
906 out += '%s\n' % formatted_dep
907
908 normalized_package_list = _resolve_package_names(module, packages, pip, py_bin)
909
910 for package in normalized_package_list:
911 is_present = _is_present(module, package, pkg_list, pkg_cmd)
912 if (state == 'present' and not is_present) or (state == 'absent' and is_present):
913 changed = True
914 break
915 module.exit_json(changed=changed, cmd=pkg_cmd, stdout=out, stderr=err)
916
917 out_freeze_before = None
918 if requirements or has_vcs:
919 dummy, out_freeze_before, dummy = _get_packages(module, pip, chdir)
920
921 rc, out_pip, err_pip = module.run_command(cmd, path_prefix=path_prefix, cwd=chdir)
922 out += out_pip
923 err += err_pip
924 if rc == 1 and state == 'absent' and \
925 ('not installed' in out_pip or 'not installed' in err_pip):
926 pass # rc is 1 when attempting to uninstall non-installed package
927 elif rc != 0:
928 _fail(module, cmd, out, err)
929
930 if state == 'absent':
931 changed = 'Successfully uninstalled' in out_pip
932 else:
933 if out_freeze_before is None:
934 changed = 'Successfully installed' in out_pip
935 else:
936 dummy, out_freeze_after, dummy = _get_packages(module, pip, chdir)
937 changed = out_freeze_before != out_freeze_after
938
939 changed = changed or venv_created
940
941 module.exit_json(changed=changed, cmd=cmd, name=name, version=version,
942 state=state, requirements=requirements, virtualenv=env,
943 stdout=out, stderr=err)
944 finally:
945 if old_umask is not None:
946 os.umask(old_umask)
947
948
949 if __name__ == '__main__':
950 main()