Interview Prep/Ansible/Variables, Facts and Precedence

What is the difference between `register`, `set_fact` and `vars`?

IntermediateConceptVariables, Facts and Precedence
Answer
  • vars defines a value at a scope (play/block/task). It is lazily evaluated, only when used.
  • register stores a task's result in a variable for the rest of the play (per host).
  • set_fact creates 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.

All Ansible questions Roadmap: Ansible

More on Variables, Facts and Precedence