Ansible: embedding a timestamp in a file name

If you are creating a log file or perhaps an archive directory, it can be a convenience to end users to use a sortable timestamp in the file name itself, similar to “YYYYMMDD-HHMMSS”.  This allows them to easily find the file relevant to their needs.

Here are a couple of ways to implement this logic in Ansible:

  • using the ‘ansible_date_time’ variable gathered as a fact
  • using a lookup with ‘pipe‘ to a formatted date command

ansible_date_time

When Ansible gathers facts, one of the variables produced is ‘ansible_date_time’.  You can use its ‘iso8601_basic_short’ field as an OS-agnostic way of pulling a timestamp in YYYYMMDDTHHMMDD format.

The downside is that this timestamp only gets created and updated when facts are gathered, which means it could be cached and have an older value.  And you must ensure the playbook/role has gathered_facts enabled.

# requires 'gather_facts'
- set_fact:
    facts_timestamp: "{{ ansible_date_time.iso8601_basic_short }}"
- debug:
    msg: "from facts: {{ facts_timestamp }}"

When run, this would produce output like below.

ok: [localhost] => {
"msg": "from facts: 20220923T220219"
}

pipe lookup

The pipe lookup can run a shell on the Ansible orchestrator to gather output.  In this case, the date command from the Linux shell is run in order to produce the timestamp.

- set_fact:
    pipe_timestamp: "{{ lookup('pipe', 'date +%Y%m%dT%H%M%S') }}"
- debug:
    msg: "from pipe: {{pipe_timestamp}}"

When run, this would produce output like below.

ok: [localhost] => {
"msg": "from pipe: 20220923T220220"
}

 

Here is a link to playbook-timestamp.yml, where I test both these methods.

 

REFERENCES

github fabianlee, playbook that tests timestamps

ansible docs, ansible_date_time gathered as fact, use pipe if you want current time

mydailytutorials.com, discussion on ansible_date_time

stackoverflow, ansible_date_time output

stackoverflow, using lookup ‘pipe’ to date