如果我运行apt,我可以更新包缓存:
apt:
name: postgresql
state: present
update_cache: yes
我现在正在尝试使用通用package
命令,但我看不到执行此操作的方法。
package:
name: postgresql
state: present
我是否必须运行显式命令才能运行apt-get update
,或者我可以使用包模块执行此操作?
是不可能的。
在撰写本文时package
模块只能处理包存在,因此您必须直接使用包模块来刷新缓存。
不幸的是,你不能使用包模块,但你可以执行两个步骤,先更新缓存,然后再运行其余的剧本。
- hosts: all
become: yes
tasks:
- name: Update Package Cache (apt/Ubuntu)
tags: always
apt:
update_cache: yes
changed_when: false
when: ansible_distribution == "Ubuntu"
- name: Update Package Cache (dnf/CentOS)
tags: always
dnf:
update_cache: yes
changed_when: false
when: ansible_distribution == "CentOS"
- name: Update Package Cache (yum/Amazon)
tags: always
yum:
update_cache: yes
changed_when: false
when: ansible_distribution == "Amazon"
不幸的是,Ansible 尚未提供通用解决方案。
但是,变量ansible_pkg_mgr
提供有关已安装的包管理器的可靠信息。反过来,您可以使用此信息来调用特定的 Ansible 包模块。请随函附上所有常见包管理器的示例。
- hosts: all
become: yes
tasks:
- name: update apt cache
ansible.builtin.apt:
update_cache: yes
when: ansible_pkg_mgr == "apt"
- name: update yum cache
ansible.builtin.yum:
update_cache: yes
when: ansible_pkg_mgr == "yum"
- name: update apk cache
community.general.apk:
update_cache: yes
when: ansible_pkg_mgr == "apk"
- name: update dnf cache
ansible.builtin.dnf:
update_cache: yes
when: ansible_pkg_mgr == "dnf"
- name: update zypper cache
community.general.zypper:
name: zypper
update_cache: yes
when: ansible_pkg_mgr == "zypper"
- name: update pacman cache
community.general.pacman:
update_cache: yes
when: ansible_pkg_mgr == "pacman"
是的。
只需在调用ansible.builtin.package
模块时包括update_cache: yes
:
package:
name: postgresql
state: present
update_cache: yes
这是有效的,因为截至 2020 年,Ansible 将任何其他参数传递给底层包管理器:
虽然所有参数都将传递到基础模块,但并非所有模块都支持相同的参数。本文档仅介绍所有打包模块支持的模块参数的最小交集。
来源:包模块文档