
There are a few different ways to do something with datetime in Ansible.
- Using ansible_date_time
- Using strftime (string format time)
- Using the lookup plugin and date (this article)
- Using to_datetime to determine the difference between two dates
The lookup plugin is always executed on the control node (that's your Ansible server), which is to say that the lookup plugin does not do something on your managed nodes (the target systems).
To use the pipe plugin, the Python pipe.py script must be in your Ansible plugins lookup directory, such as /usr/lib/python2.7/site-packages/ansible/plugins/lookup/pipe.py.
In this example, the debug module is used output the current date time.
---
- hosts: all
tasks:
- name: current datetime
ansible.builtin.debug:
msg: "{{ lookup('pipe','date') }}"
...
Something like this should be returned. The output is identical to the Linux date command.
TASK [current datetime]
ok: [server1.example.com] => {
"msg": "Fri Dec 11 02:04:14 CST 2020"
}
Usually, you are going to want to format the output, like this.
---
- hosts: all
tasks:
- name: current datetime
ansible.builtin.debug:
msg: "{{ lookup('pipe','date +%Y-%m-%d_%H:%M:%S') }}"
...
Something like this should be returned.
TASK [current datetime]
ok: [server1.example.com] => {
"msg": "2020-12-11_02:07:37"
}
Or even better, create a date and time variables.
---
- hosts: all
vars:
date: "{{ lookup('pipe','date +%Y-%m-%d') }}"
time: "{{ lookup('pipe','date +%H:%M:%S') }}"
tasks:
- ansible.builtin.debug:
var: date
- ansible.builtin.debug:
var: time
...
Sometimes, you'll be working with an epoch formatted datetime. For example, when using the find module or stat module, the accessed datetime (atime), changed datetime (ctime), and modified datetime (mtime) of the file will be epoch formated, like this.
"mtime": 158338361.5600421
The strftime (string format time) filter can be used to convert epoch to human readable, like this.
---
- hosts: all
tasks:
- ansible.builtin.debug:
msg: "{{ '%Y-%m-%d' | strftime(item.mtime) }}"
with_items: "{{ out.files }}"
...
Did you find this article helpful?
If so, consider buying me a coffee over at