使用来自ansible的模块包时如何更新包缓存

How to update package cache when using module package from ansible

如果我运行 apt,我可以更新包缓存:

apt:
  name: postgresql
  state: present
  update_cache: yes

我现在正在尝试使用通用 package 命令,但我没有找到执行此操作的方法。

package:
  name: postgresql
  state: present

我是否必须 运行 对 运行 apt-get update 的显式命令,或者我可以使用包模块来执行此操作?

这是不可能的。

编写时的模块package只能处理包的存在,所以你必须直接使用包模块来刷新缓存。

不幸的是,您不能使用 package 模块,但是您可以执行两步操作,先更新缓存,然后再 运行 其余的 playbook。

- 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"