What does ansible.builtin.set_fact do, and how does it shorten long variable paths?
It creates a new variable for the current host during the play, whose value can come from other variables. Typing custom_host['users'] instead of ansible_facts['ansible_local']['custom']['users'] makes plays shorter and easier to read.
* set_fact names a deep path once; later tasks use the short name. *
- name: Shorter name for the custom facts
ansible.builtin.set_fact:
custom_host: "{{ ansible_facts['ansible_local']['custom'] }}"
- name: Shorter name for the vda partitions
ansible.builtin.set_fact:
vda_parts: "{{ ansible_facts['devices']['vda']['partitions'] }}"
After these tasks:
| Short | Instead of |
|---|---|
custom_host['packages'] |
ansible_facts['ansible_local']['custom']['packages'] |
vda_parts['vda1']['size'] |
ansible_facts['devices']['vda']['partitions']['vda1']['size'] |
set_fact works on any value: system facts, custom facts, or registered variables. The new variable is per host (each host gets its own vda_parts) and is available to later tasks and later plays in the same run.
Beyond saving typing, it gives a deep path a meaningful name, and you can compute a value once (for example with a Jinja2 filter) and reuse the result.
Go deeper:
ansible.builtin.set_fact module (official docs) — scope, precedence and caching of facts set this way.