如果我运行 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 提供了通用解决方案🎉:
- name: Update package cache
ansible.builtin.package:
update_cache: true
不幸的是,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 的官方最新文档,其中似乎没有记录有关 update_cache 的内容:
但是在家里测试,我让ansible失败,为了读取失败,update_cache似乎是可以使用的选项之一: