- 1 year ago
How to iterate over facts in Ansible
To iterate over facts in Ansible, you can use the with_items
loop and the ansible_facts
variable. The ansible_facts
variable contains all the facts gathered from the target hosts during the playbook execution. Here's an example of how you can iterate over facts in Ansible:
yaml- name: Iterate over facts
hosts: your_host
gather_facts: true
tasks:
- name: Display fact values
debug:
msg: "Fact: {{ item.key }}, Value: {{ item.value }}"
with_items: "{{ ansible_facts | dict2items }}"
In this example:
- The
gather_facts
parameter is set totrue
to ensure that facts are gathered from the target host. - The
debug
module is used to display the fact key-value pairs. - The
ansible_facts
variable is passed to thedict2items
filter to convert the dictionary of facts into a list of key-value pairs. - The
with_items
loop is used to iterate over the list of fact key-value pairs.
When the playbook runs, it will iterate over each fact in ansible_facts
, displaying the fact key and value using the debug
module.
You can customize the tasks and actions within the loop based on your specific requirements. For example, you can filter specific facts using the when
condition or perform additional operations using the fact values within the loop.
By utilizing the with_items
loop and the ansible_facts
variable, you can iterate over facts in Ansible and perform tasks or actions based on the fact values.