1

In Ansible I can use a task such as:

- name: Gather the package facts
  package_facts:
    manager: auto

to gather the package facts and a condition such as:

when: "'foobar' in ansible_facts.packages"

to only execute a task when package foobar is installed. Gathering the package facts is a rather lengthy process compared to many of the other tasks in my playbooks.

For the sake of this question we can also assume that instead of manager: auto I'm using manager: apt.

Now I was unable to find any information regarding if or when the fact ansible_facts.packages gets invalidated after a subsequent package manager operation and a look at the fact via debug module doesn't give me any indication as to when it was gathered. Similarly I found no obvious way of checking against the cache time of the package manager. So in essence I was unable to come up with a means of only gathering (or re-gathering) the package facts when necessary.

So, questions:

  1. does the ansible_facts.packages fact get invalidated after subsequent package manager operations?
  2. if not: how can I get close to the desired "only gather package facts if something changed"?

NB: according to ansible --version I am running version 2.10.7.

2

Package facts (as any other facts like devices, disks and their partitions, IP addresses...) don't refresh automagically.

In your case, you can use a handler and notify it from any task that can possibly invalidate the cache. Here is a quickNdirty example:

- name: Pseudo code demo for package facts refresh
  hosts: localhost
  
  tasks:

    - name: Gather the package facts unconditionally at play start
      package_facts:

    - name: Make sure package X is installed
      package:
        name: package_X
      notify: refresh_package_facts
    
    # By default, handlers run at the end of the play.
    # If you want to force them to run at a certain point,
    # you need the following meta task.
    # Note => this will run !!ALL!! notified handlers
    - name: Run handlers if notified
      meta: flush_handlers

    - name: This task will run with an up-to-date cache
      debug:
        msg: "{{ ansible_facts.packages | length }} packages are installed"

  handlers:

    - name: Refresh the package facts
      package_facts:
      listen: refresh_package_facts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.