Store Timestamp As A Constant Value

I’m trying to save the timestamp corresponding to when a playbook runs in a variable.
I plan to use this variable across the playbook but I’m facing issues particularly since

the lookup plugin runs and generates a new value each time.

module_defaults:
group/ns.col.session:
session_id: “{{ lookup(‘pipe’,‘date "+%Y-%m-%d-%H%M"’) }}”

The value is looked up at the time that it is needed

I could use set_fact: but it only works inside of the tasks: block and I’d like to set it to some value before any task can run i.e. right after hosts.

  • hosts:
  • localhost

module_defaults:
group/ns.col.session:
session_id: …

How do I achieve this WITHOUT using set_fact OR without using the lookup() ?
In other words, how to save or copy the value of a lookup to some variable ?

Thanks
Dhiwakar

If you must do this before anything else you could provide the value as a command line extra variable to ansible-playbook

Thank you, so from that reply, I’m assuming there isn’t any viable alternative ?

Use set_fact as the first task in the playbook.
You disqualified that, but tbh I don’t understand the reasoning behind that?
Can you elaborate?

So, I disqualified it because in Ansible 2.12, there is an ability to define defaults for module collections, more on that here.

In ansible-core 2.12, collections can define their own groups in the meta/runtime.yml file. module_defaults does not take the collections keyword into account, so the fully qualified group name must be used for new groups in module_defaults.

This means my playbook requires a value to begin with.

module_defaults:
group/ns.col.session:
session_id:

Now, if I’m going to use set_fact, this is what my playbook looks like.

I’ve done it like this. Perhaps this will be useful to you.

- hosts: all
tasks:
- name: Snarf the playbook start time on the first host.
# We'll use this time stamp on backup files in the next play.
set_fact:
ansible_playbook_starttime: "{{ ansible_date_time.date + ' at ' + ansible_date_time.time }}"
when: ansible_play_hosts_all | first == ansible_fqdn
run_once: yes

- hosts: all
vars:
ansible_playbook_starttime: "{{ hostvars[ansible_play_hosts_all | first]['ansible_playbook_starttime'] }}"
tasks:
[...]