Reputation: 11922
I have this example role where I install some packages based on the OS and package manager:
# THIS IS IN tasks/main.yml
- name: Ensure archlinux-keyring is updated
community.general.pacman:
name: archlinux-keyring
state: latest
update_cache: yes
when: ansible_pkg_mgr == "pacman"
If this role is run as part of a playbook, Ansible will gather the facts and everything is just fine. However, if I run it as a standalone role:
ansible localhost -m include_role -a name=examplerole
I get this error
localhost | FAILED! => {
"msg": "The conditional check 'ansible_pkg_mgr == \"pacman\"' failed. The error was: error while evaluating conditional (ansible_pkg_mgr == \"pacman\"): 'ansible_pkg_mgr' is undefined
I know I can force Ansible to gather these facts inside the role, but gathering facts over and over again will be super slow (as this is a recurring problem I have with several roles, and I can't always include them in a playbook, and also, if they ARE in a playbook, this isn't needed).
Is there any way to check if facts were already gathered, and gather them inside of the role only when needed?
Upvotes: 4
Views: 14987
Reputation: 12017
Regarding
...Is there any way to check if facts were already gathered ... gather them inside of the role only when needed?
and if you like to gather facts based on conditionals only, you may have a look into the following example
- hosts: localhost
become: false
gather_facts: false
tasks:
- name: Show Gathered Facts
debug:
msg: "{{ hostvars['localhost'].ansible_facts }}"
- name: Gather date and time only
setup:
gather_subset:
- "date_time"
- "!min"
when: ansible_date_time is not defined
- name: Show Gathered Facts
debug:
msg: "{{ ansible_facts }}"
which is gathering date and time only and if not defined before.
This means, regarding
gathering facts over and over again will be super slow
it is recommended to get familiar with the data structure of the gathered facts and the possible subsets in order to gather only the information which is needed. And as well with Caching facts.
Further Documentation
Upvotes: 10