[feat req] Improving set_fact scoping and lifetime

tl;dr Add a scope parameter to set_fact module, improving usability.

The current behavior of set_fact is to create a run-time only variable, in 2.x with private_role_vars this variable is scoped(*) to the role it is defined within.

It is helpful to be able to specify global facts in a few circumstances, such as passing information between roles or implementing once-per-playbook roles.

What I’d like to see is the set_fact module extended to support a scope parameter:

  • playbook
  • runtime lifetime.
  • 1.x like behavior.
  • 2.x behavior when private_role_vars is not enabled.
  • role
  • runtime lifetime.
  • 2.x behavior when private_role_vars is enabled.
  • corollary: should roles maintain state (set_fact’ed variables loaded back up) within the same playbook?

Additionally, the process for creating persistent facts in a role is a wee bit clunky (write out a json blob in facts.d, and force a potentially expensive fact reload).

So, a lifetime parameter:

  • runtime
  • default behavior
  • persistent
  • record fact to host’s facts.d, erroring if unable to do so.
  • add fact to host’s in-memory ansible_local facts.
  • optimization: does not trigger a fact reload.

(*) “Scoped” might be the wrong word here as the variable is deleted when the role ends. If the role is executed later in the playbook, the variable will not be defined.