o nnh@sddlmZdZdZddlZddlZddlmZmZddl m Z ddl m Z ddl mZdd lmZdd lmZmZmZdd lmZmZdaGd d d eZddZedkr[edSdS)) annotationsa* --- module: dnf version_added: 1.9 short_description: Manages packages with the I(dnf) package manager description: - Installs, upgrade, removes, and lists packages and groups with the I(dnf) package manager. options: use_backend: description: - Backend module to use. default: "auto" choices: auto: Automatically select the backend based on the C(ansible_facts.pkg_mgr) fact. yum: Alias for V(auto) (see Notes) dnf: M(ansible.builtin.dnf) yum4: Alias for V(dnf) dnf4: Alias for V(dnf) dnf5: M(ansible.builtin.dnf5) type: str version_added: 2.15 name: description: - "A package name or package specifier with version, like C(name-1.0). When using state=latest, this can be '*' which means run: dnf -y update. You can also pass a url or a local path to an rpm file. To operate on several packages this can accept a comma separated string of packages or a list of packages." - Comparison operators for package version are valid here C(>), C(<), C(>=), C(<=). Example - C(name >= 1.0). Spaces around the operator are required. - You can also pass an absolute path for a binary which is provided by the package to install. See examples for more information. aliases: - pkg type: list elements: str default: [] list: description: - Various (non-idempotent) commands for usage with C(/usr/bin/ansible) and I(not) playbooks. Use M(ansible.builtin.package_facts) instead of the O(list) argument as a best practice. type: str state: description: - Whether to install (V(present), V(latest)), or remove (V(absent)) a package. - Default is V(None), however in effect the default action is V(present) unless the O(autoremove) option is enabled for this module, then V(absent) is inferred. choices: ['absent', 'present', 'installed', 'removed', 'latest'] type: str enablerepo: description: - I(Repoid) of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a ",". type: list elements: str default: [] disablerepo: description: - I(Repoid) of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a ",". type: list elements: str default: [] conf_file: description: - The remote dnf configuration file to use for the transaction. type: str disable_gpg_check: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if O(state) is V(present) or V(latest). - This setting affects packages installed from a repository as well as "local" packages installed from the filesystem or a URL. type: bool default: 'no' installroot: description: - Specifies an alternative installroot, relative to which all packages will be installed. version_added: "2.3" default: "/" type: str releasever: description: - Specifies an alternative release from which all packages will be installed. version_added: "2.6" type: str autoremove: description: - If V(true), removes all "leaf" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when O(state) is V(absent) type: bool default: "no" version_added: "2.4" exclude: description: - Package name(s) to exclude when state=present, or latest. This can be a list or a comma separated string. version_added: "2.7" type: list elements: str default: [] skip_broken: description: - Skip all unavailable packages or packages with broken dependencies without raising an error. Equivalent to passing the --skip-broken option. type: bool default: "no" version_added: "2.7" update_cache: description: - Force dnf to check if cache is out of date and redownload if needed. Has an effect only if O(state) is V(present) or V(latest). type: bool default: "no" aliases: [ expire-cache ] version_added: "2.7" update_only: description: - When using latest, only update installed packages. Do not install packages. - Has an effect only if O(state) is V(latest) default: "no" type: bool version_added: "2.7" security: description: - If set to V(true), and O(state=latest) then only installs updates that have been marked security related. - Note that, similar to C(dnf upgrade-minimal), this filter applies to dependencies as well. type: bool default: "no" version_added: "2.7" bugfix: description: - If set to V(true), and O(state=latest) then only installs updates that have been marked bugfix related. - Note that, similar to C(dnf upgrade-minimal), this filter applies to dependencies as well. default: "no" type: bool version_added: "2.7" enable_plugin: description: - I(Plugin) name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction. version_added: "2.7" type: list elements: str default: [] disable_plugin: description: - I(Plugin) name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction. version_added: "2.7" type: list default: [] elements: str disable_excludes: description: - Disable the excludes defined in DNF config files. - If set to V(all), disables all excludes. - If set to V(main), disable excludes defined in [main] in dnf.conf. - If set to V(repoid), disable excludes defined for given repo id. version_added: "2.7" type: str validate_certs: description: - This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to V(false), the SSL certificates will not be validated. - This should only set to V(false) used on personally controlled sites using self-signed certificates as it avoids verifying the source site. type: bool default: "yes" version_added: "2.7" sslverify: description: - Disables SSL validation of the repository server for this transaction. - This should be set to V(false) if one of the configured repositories is using an untrusted or self-signed certificate. type: bool default: "yes" version_added: "2.13" allow_downgrade: description: - Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction). type: bool default: "no" version_added: "2.7" install_repoquery: description: - This is effectively a no-op in DNF as it is not needed with DNF. - This option is deprecated and will be removed in ansible-core 2.20. type: bool default: "yes" version_added: "2.7" download_only: description: - Only download the packages, do not install them. default: "no" type: bool version_added: "2.7" lock_timeout: description: - Amount of time to wait for the dnf lockfile to be freed. required: false default: 30 type: int version_added: "2.8" install_weak_deps: description: - Will also install all packages linked by a weak dependency relation. type: bool default: "yes" version_added: "2.8" download_dir: description: - Specifies an alternate directory to store packages. - Has an effect only if O(download_only) is specified. type: str version_added: "2.8" allowerasing: description: - If V(true) it allows erasing of installed packages to resolve dependencies. required: false type: bool default: "no" version_added: "2.10" nobest: description: - This is the opposite of the O(best) option kept for backwards compatibility. - Since ansible-core 2.17 the default value is set by the operating system distribution. required: false type: bool version_added: "2.11" best: description: - When set to V(true), either use a package with the highest version available or fail. - When set to V(false), if the latest version cannot be installed go with the lower version. - Default is set by the operating system distribution. required: false type: bool version_added: "2.17" cacheonly: description: - Tells dnf to run entirely from system cache; does not download or update metadata. type: bool default: "no" version_added: "2.12" extends_documentation_fragment: - action_common_attributes - action_common_attributes.flow attributes: action: details: dnf has 2 action plugins that use it under the hood, M(ansible.builtin.dnf) and M(ansible.builtin.package). support: partial async: support: none bypass_host_loop: support: none check_mode: support: full diff_mode: support: full platform: platforms: rhel notes: - When used with a C(loop:) each package will be processed individually, it is much more efficient to pass the list directly to the I(name) option. - Group removal doesn't work if the group was installed with Ansible because upstream dnf's API doesn't properly mark groups as installed, therefore upon removal the module is unable to detect that the group is installed (https://bugzilla.redhat.com/show_bug.cgi?id=1620324) - While O(use_backend=yum) and the ability to call the action plugin as M(ansible.builtin.yum) are provided for syntax compatibility, the YUM backend was removed in ansible-core 2.17 because the required libraries are not available for any supported version of Python. If you rely on this functionality, use an older version of Ansible. requirements: - "python >= 2.6" - python-dnf - for the autoremove option you need dnf >= 2.0.1" author: - Igor Gnatenko (@ignatenkobrain) - Cristian van Ee (@DJMuggs) - Berend De Schouwer (@berenddeschouwer) - Adam Miller (@maxamillion) aR - name: Install the latest version of Apache ansible.builtin.dnf: name: httpd state: latest - name: Install Apache >= 2.4 ansible.builtin.dnf: name: httpd >= 2.4 state: present - name: Install the latest version of Apache and MariaDB ansible.builtin.dnf: name: - httpd - mariadb-server state: latest - name: Remove the Apache package ansible.builtin.dnf: name: httpd state: absent - name: Install the latest version of Apache from the testing repo ansible.builtin.dnf: name: httpd enablerepo: testing state: present - name: Upgrade all packages ansible.builtin.dnf: name: "*" state: latest - name: Update the webserver, depending on which is installed on the system. Do not install the other one ansible.builtin.dnf: name: - httpd - nginx state: latest update_only: yes - name: Install the nginx rpm from a remote repo ansible.builtin.dnf: name: 'http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm' state: present - name: Install nginx rpm from a local file ansible.builtin.dnf: name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state: present - name: Install Package based upon the file it provides ansible.builtin.dnf: name: /usr/bin/cowsay state: present - name: Install the 'Development tools' package group ansible.builtin.dnf: name: '@Development tools' state: present - name: Autoremove unneeded packages installed as dependencies ansible.builtin.dnf: autoremove: yes - name: Uninstall httpd but keep its dependencies ansible.builtin.dnf: name: httpd state: absent autoremove: no - name: Install a modularity appstream with defined stream and profile ansible.builtin.dnf: name: '@postgresql:9.6/client' state: present - name: Install a modularity appstream with defined stream ansible.builtin.dnf: name: '@postgresql:9.6' state: present - name: Install a modularity appstream with defined profile ansible.builtin.dnf: name: '@postgresql/client' state: present N) to_nativeto_text) fetch_file) LooseVersion) AnsibleModule)get_best_parsable_locale) has_respawnedprobe_interpreters_for_modulerespawn_module)YumDnfyumdnf_argument_speccseZdZdZfddZddZddZdd Zd d Zd)ddZ ddZ ddZ ddZ ddZ ddZd*ddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(ZZS)+ DnfModulez4 DNF Ansible module back-end implementation csJtt|||d|_ztjj|_WdSt y$d|_YdSw)NdnfF) superr__init__ _ensure_dnf pkg_mgr_namerbase WITH_MODULES with_modulesAttributeError)selfmodule __class__>/usr/local/lib/python3.10/dist-packages/ansible/modules/dnf.pyrs  zDnfModule.__init__cCs.tdt|vstdt|vrd|S|S)z For unhandled dnf.exceptions.Error scenarios, there are certain error messages we want to filter in an install scenario. Do that here. no package matchedNo match for argument:No package {0} available.)rformatrspecerrorrrr_sanitize_dnf_error_msg_installs z)DnfModule._sanitize_dnf_error_msg_installcCs.dt|vs dt|vrdd|fSd|fS)z For unhandled dnf.exceptions.Error scenarios, there are certain error messages we want to ignore in a removal scenario as known benign failures. Do that here. rrFz{0} is not installedT)rr!r"rrr_sanitize_dnf_error_msg_removes  z(DnfModule._sanitize_dnf_error_msg_removecCsd|j|jt|j|j|j|jd}djd i||d<|d|d<|jdkr,d|d<|Sd|d<|S) z3Return a dictionary of information for the package.)namearchepochreleaseversionrepoz){epoch}:{name}-{version}-{release}.{arch}envranevrar availableyumstate installedNr) r'r(strr)r*r+repoidr! installtime)rpackageresultrrr _package_dicts  zDnfModule._package_dictcCst|j}|tjd<tjd<|tjd<tjd<zddladdladdladdladdladdl ad}Wn t y@d}Ynw|rEdSgd}t sWt |d }|rWt ||jjd tjtjd d |gd dS)NLC_ALL LC_MESSAGESLANGUAGELANGrTF)z/usr/libexec/platform-pythonz/usr/bin/python3z/usr/bin/python2z/usr/bin/pythonrzCould not import the dnf python module using {0} ({1}). Please install `python3-dnf` or `python2-dnf` package or ensure you have specified the correct ansible_python_interpreter. (attempted {2}) msgresults)rrosenvironr dnf.constdnf.exceptions dnf.package dnf.subjectdnf.util ImportErrorr r r fail_jsonr!sys executabler+replace)rlocaleHAS_DNFsystem_interpreters interpreterrrrrs4    zDnfModule._ensure_dnf/Tc Csf|j}|rt|tjs|jjd|gdn||_|d|_| |_ | |_ d|_ ||_ ||_ |j||jrHt|j}||j||_|jr^t|j}|j|vr^||j||_|jduri|j|jd<|jddur||jdd|jd<|jrd|_|jdur|j |_n |jdur|j|_|jrd|_|jr|j|_|j rd|_ |j!|_"|j#|_#dS) zConfigure the dnf Base object.zcannot read configuration file)r? conf_filer@rTN releaseverzUUnable to detect release version (use "releasever" option to specify release version)r=)$confrAaccessR_OKrrIconfig_file_pathread debuglevelgpgchecklocalpkg_gpgcheck assumeyes sslverify installroot substitutionsupdate_from_etcexcludelistextenddisable_excludesappendrSgetwarn skip_brokenstrictnobestbest download_only downloadonly download_dirdestdir cacheonly autoremoveclean_requirements_on_removeinstall_weak_deps) rrrRdisable_gpg_checkr^r]rT _excludes_disable_excludesrrr_configure_bases\             zDnfModule._configure_basecCs||j}|D]}|r||D]}|qq |D]}|r,||D]}|q%q|jD] }|jr=d|_d|_q2dS)z?Enable and disable repositories matching the provided patterns.FN) read_all_reposrepos get_matchingdisableenable iter_enabledrtrZ repo_gpgcheck)rr disablerepo enablerepory repo_patternr,rrr_specify_repositoriesvs$  zDnfModule._specify_repositoriesc Cst}||||||z|Wn tyYnwz|t|jt|j| Wn ty8Ynw| |||z| Wn tyOYnwz4|j r}z| Wn"tj jy|}z|jjdt|gddWYd}~nd}~ww|jddWn"tj jy}z|jjdt|gddWYd}~nd}~wwt|dd} t| ri} |jr| dgd |jr| dgd | r| d i| |Sg} |jrd d i} | |jjdi| |jrd d i} | |jjdi| | r | |_|S)z*Return a fully configured dnf Base object.z{0}r?r@rcNauto)load_system_repoadd_security_filterstypesbugfixsecurityeqadvisory_type__eq)rr)rBaserw setup_loggersr init_pluginssetdisable_plugin enable_pluginpre_configure_pluginsrconfigure_plugins update_cache exceptions RepoErrorrrIr!r fill_sackgetattrcallabler setdefaultrersackqueryupgradesfilter_update_security_filters) rrRrtrrr^r]rerfilterskeyrrr_basesx             zDnfModule._basecs|dkrd}|dvrfddtjj|D}n$|dvr,ddjjD}ntj| jj}fdd|D}j j d |d d S) z'List package info based on the command.updatesr)r1rr/cg|]}|qSrr7.0r5rrr sz(DnfModule.list_items..)ry repositoriescSsg|]}|jddqS)enabled)r3state)id)rr,rrrrs crrrrrrrrsr=r>N) rrrrryr}rsubjectSubjectget_best_queryr exit_json)rcommandr@packagesrrr list_itemss  zDnfModule.list_itemscCsjtj|j|jjd}tj|r1tj|j|jjd }dd|Ddd|D St |S)NrcSsh|]}|jqSrr'rprrr sz*DnfModule._is_installed..) rrrrrrr1utilis_glob_patternr/bool)rpkginstalled_queryavailable_queryrrr _is_installeds  zDnfModule._is_installedcCsz6t|tjjr |}nttj|j|jj d d}t|jj j|jd d}W||kSty@YdSw)NrrF) isinstancerr5Packagesortedrrrrrr/runrr1rr' IndexError)rpkg_namer/r1rrr_is_newer_version_installeds( z%DnfModule._is_newer_version_installedFc Cs||}||}d}zD|r7|jr5|r)|r|j|n2|jj||jjjdn&|jj||jjjdn n|rD|rB|j|n n |jj||jjjdWntj j y}z%d |}|jjjryd|d |t |fdgdWYd}~SWYd}~ncd}~wtj jy}zdd |d |t |fdgdWYd}~Sd}~wtj jy}z,td t|vrd ddd WYd}~Sdd |d |t |fdgdWYd}~Sd}~wwd |dddS)zMark the package for install.r=rir T r)failedr?failurerr@Nz(Depsolve Error occurred for package {0}.already installedF)rr?rz'Unknown Error occurred for package {0}.r)rr?rr)rrallow_downgraderupgradeinstallrTrirr MarkingErrorr!joinr DepsolveErrorErrorr)rpkg_specris_newer_version_installed is_installedr?rrrr_mark_package_installsb       zDnfModule._mark_package_installc Cs2ggggf\}}}}d}|jD]}d|vr!t|j|}||q|dr,||q|drT|jjj ||d }|rK||dj q|j sS||q|ds]d|vr|sf|jd}|d d}|jr|j|} | dr||q||q||q||q||||fS) NFz://z.rpmrQ)providesfiler@Tr)namesrrreendswith startswithrrrrr1rr' update_only read_compsstripr module_base _get_modules) r pkg_specs grp_specs module_specs filenamesalready_loaded_compsr'r1grp_env_mdl_candidatemdlrrr_parse_spec_group_file=s8              z DnfModule._parse_spec_group_filec Csg}|D]Q}|t|tjjr||dn|rPzt|tjjr(|j|n|j|Wqt yO}z|j j d t |gddWYd}~qd}~ww||q|S)Nr.z4Error occurred attempting update_only operation: {0}rr)rrrr5rr7rpackage_upgrader ExceptionrrIr!rre)rpkgs not_installedrrrrr _update_onlybs(   zDnfModule._update_onlyc CsRttjdddkrtt|jt|dd}nrd0|d <|jj9d7i|z,|j:r|j?r|jj@jArtjBC|jj@jA|jj@jA|jjDE_F|jG|jj;j<Wn"tjjHy}z|jj d1tI|gdWYd}~nd}~ww|jJs"|jj;j.cSrrr)rfrrrrrcss|]}|VqdS)Nr)rgrrr sz#DnfModule.ensure..zNo group {0} available.r>)r1presentr@z Installed {0}zModule {0} installed.r rzGroup {0} already installed.zGroup {0} installed.z8Depsolve Error occurred attempting to install group: {0}z>Depsolve Error occurred attempting to install environment: {0}z@Packages providing %s not installed due to update_only specifiedrrzModule {0} upgraded.zGroup {0} upgraded.T)rz3Cannot remove paths -- please specify package name.zModule {0} removed.z {0} - {1}r) allow_erasingz0Failed to install some of the specified packagesz Nothing to dor  Downloaded Installedz{0}: {1}z Removed: {0}z@Check mode: No changes made, but would have if not in check modez Failed to download packages: {0}z-Failed to validate GPG signature for {0}: {1}zDepsolve Error occurred: {0}rzPackage already installed: {0}zUnknown Error occurred: {0}r)Rrrqrr upgrade_allrrrrrIrcompsgroup_by_patternrerenvironment_by_patternr!rrrrrr| MarkingErrorsrr group_installconstGROUP_PACKAGE_TYPESrenvironment_installrrrr%r group_upgrade CompsErrorenvironment_upgraderemover{reset group_removerenvironment_removerrr1rr&rrrrr2 allowerasingresolverrl transaction install_set remove_set check_modernrTror ensure_dirryallpkgdirdownload_packages DownloadErrorrrt_sig_check_pkg_get_key_for_packagedo_transactionhistoryold return_codeoutput)!rresponsefailure_responserr group_specsrrgroups environments group_specgroup environmentrrgroup_pkg_count_installedrr#rinstall_resultr1 is_failurehandled_remove_error installed_pkgrinstall_actionr5failgpgresgpgerrr?tidr*rrrensuresF      (  * *        *  **      *                 zDnfModule.ensurecCsl|jrttjtdkr|jjdtjgd|jr.ttjtdkr.|jjdtjgd|jrR|jsR|j sR| |j |j |j |j|j|j|_|jjddgdd |jd urZd |_|j rv| |j |j |j |j|j|j|_||j d S|jstjs|jjd gd| |j |j |j |j|j|j|_|jrtjj|j|_z |W|jd S|jw) zThe main function.z2.0.1z9Autoremove requires dnf>=2.0.1. Current dnf version is %sr>z2.6.2z;download_dir requires dnf>=2.6.2. Current dnf version is %sz Cache updatedFrrNr1z/This command has to be run under the root user.)rqrrrrrIrnrrrbrrRrtrrr^r]rrrrrlr am_i_rootrr ModuleBaserLcloserrrrrsZ        z DnfModule.run)rQT)F)__name__ __module__ __qualname____doc__rr%r&r7rrwrrrrrrrrrrrLr __classcell__rrrrrs,    +_= F% Xrc Cstdgddtdd<td it}t|}z|WdStjjyA}z|jd t |dgdd WYd}~dSd}~ww) Nr)rryumyum4dnf4dnf5)defaultchoices argument_spec use_backendz#Failed to synchronize repodata: {0}rF)r?rr@r r) dictr rrrrrrrIr!r)rmodule_implementationderrrmain?s   r`__main__) __future__r DOCUMENTATIONEXAMPLESrArJ+ansible.module_utils.common.text.convertersrransible.module_utils.urlsr#ansible.module_utils.compat.versionransible.module_utils.basicr"ansible.module_utils.common.localer#ansible.module_utils.common.respawnr r r ansible.module_utils.yumdnfr r rrr`rPrrrrs6 .X    "