What is the difference between `register`, `set_fact` and `vars`?
IntermediateConceptVariables, Facts and Precedence
Answer
varsdefines a value at a scope (play/block/task). It is lazily evaluated, only when used.registerstores a task's result in a variable for the rest of the play (per host).set_factcreates a host variable at run time from an expression; it is evaluated immediately and persists for the host until the run ends.
- ansible.builtin.command: cat /etc/version
register: v
- ansible.builtin.set_fact:
app_ver: "{{ v.stdout | trim }}"
Use vars for configuration, register to capture output, and set_fact to compute a value once and reuse it.
More on Variables, Facts and Precedence
Where can you define variables in Ansible?BeginnerHow do you reference a variable, and when must you quote it?BeginnerGive a summary of variable precedence.IntermediateWhat are the lowest and highest precedence sources, and why does that matter?IntermediateWhat is the difference between a role's `defaults/` and `vars/`?IntermediateWhat are facts and how are they gathered?Beginner