Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update package cache when using module package from ansible

If I run apt, I can update the package cache:

apt:
  name: postgresql
  state: present
  update_cache: yes

I'm now trying to use the generic package command, but I don't see a way to do this.

package:
  name: postgresql
  state: present

Do I have to run an explicit command to run apt-get update, or can I do this using the package module?

like image 710
Justin Blank Avatar asked Mar 03 '18 17:03

Justin Blank


3 Answers

You can't with the package module, unfortunately, but you can do a two-step where you update the cache first before running the rest of your playbook(s).

- 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"
like image 85
Michael Auerswald Avatar answered Oct 22 '22 04:10

Michael Auerswald


This is not possible.

The module package as of writing is just capable to handle package presence, so you have to use directly the package module to refresh the cache.

like image 43
Baptiste Mille-Mathias Avatar answered Oct 22 '22 04:10

Baptiste Mille-Mathias


Unfortunately, Ansible does not yet offer a generic solution.

However, the variable ansible_pkg_mgr provides reliable information about the installed package manager. In turn, you can use this information to call the specific Ansible package modules. Please find attached an example for all common package managers.

- 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"
like image 1
Philipp Waller Avatar answered Oct 22 '22 06:10

Philipp Waller