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

问题描述 投票:0回答:5

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

apt:
  name: postgresql
  state: present
  update_cache: yes

我现在正在尝试使用通用的

package
命令,但我没有找到执行此操作的方法。

package:
  name: postgresql
  state: present

我是否必须运行显式命令才能运行

apt-get update
,或者我可以使用包模块来执行此操作吗?

ansible package-managers
5个回答
14
投票

这是不可能的。

模块

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


7
投票

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

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

7
投票

更新

如今,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"

4
投票

是的。

只需在对

update_cache: yes
模块的调用中包含
ansible.builtin.package
即可:

package:
  name: postgresql
  state: present
  update_cache: yes

这之所以有效,是因为 截至 2020 年,Ansible 将任何其他参数传递给底层包管理器:

虽然所有参数都会传递给底层模块,但并非所有模块都支持相同的参数。本文档仅涵盖所有打包模块支持的模块参数的最小交集。

来源:包模块文档


0
投票

实际上,我阅读了 Ansible 的官方最新文档,其中似乎没有记录有关 update_cache 的内容:

ansible_doc

但是在家里测试,我让ansible失败,为了读取失败,update_cache似乎是可以使用的选项之一:

© www.soinside.com 2019 - 2024. All rights reserved.