There is an undocumented^* but intentional interaction between
*ansible.builtin.set_fact* and the *run_once* parameter. You are in
luck, because it solves exactly this problem in a clean way. When you
use *set_fact* to create a variable with *run_once: true*, it sets the
variable for all hosts in the play. So you can say:
*- name: Snarf the playbook start time on all host**s
**ansible.builtin.set_fact:****ansible_playbook_starttime: "{{ now('True',
'%F_%H%M%S') }}"****run_once: true*
After this step runs, all hosts will have the same
*ansible_playbook_starttime* variable with a fully templated out value.
This differs from, say, setting the same variable in *group_vars/all* or
in your playbook's *vars:* section. If you create the variable any of
these other ways, "lazy evaluation" will cause the variable's template
to be re-evaluated each time it is used. In contrast, *set_fact* will
produce ‘static’ values, i.e. not subject to or requiring further
template evaluation on subsequent uses.
^*Arguably one could read *ansible-doc -t module set_fact* with a
lawyer's eye and discern this behavior, but I've read it a dozen or more
times and never once did it occur to me that *run_once: true* would have
this effect across all hosts. There is a bug report
<https://github.com/ansible/ansible/issues/47509> about it from October
2018 that spells it out. Otherwise it's one of those serendipitous
discoveries that either makes your day or ruins your weekend.
On 3/23/23 1:19 PM, dulhaver via Ansible Project wrote:
ok that works to some extent. But I probably seem to need someting not toooo
dynamic after all :-/
I did not get this entirely when we started.
I need to create the variable value once at the beginning of the playbook but
need to get back to it later down the road with the same initial value. So more
like it works inside a bash script (despite the fact it's a playbook).
I can think of a workaround for my current task, but still would be wondering
whether this can be done.
On 03/23/2023 11:18 AM CET Dick Visser<[email protected]> wrote:
You are using shell command inside an ansible vars file. That will not work.
Take a look
athttps://docs.ansible.com/ansible/latest/collections/ansible/builtin/strftime_filter.html
On Thu, 23 Mar 2023 at 10:58, dulhaver via Ansible Project
<[email protected]> wrote:
I am trying to define a variable in defaults.yml with some kind of dynamic.
Conrete creating a directory with the current timestamp at the end of the name.
data_dir: /file/to/dir_$(date +%F_%H%M%S)
gives me exactly the directory name 'dir_$(date +%F_%H%M%S)' and not
dir_2023_03_23_115122.
How can I achieve such?
--
Todd
--
You received this message because you are subscribed to the Google Groups "Ansible
Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/ansible-project/76356325-1fe5-a678-2964-5640949050aa%40gmail.com.