Working with date and timestamp in Ansible

Getting the system timestamp is very useful in multiple types of scenarios while scripting. You can use it for just printing out the time for logging purpose, use it for naming a directory or use it in a conditional statement to control the flow of your program.

Ansible provides access to the remote system time using Ansible facts, which you can also store into other variables and use it as you need.

Ansible timestamp

The simplest way to get the time of the remote system is using the Ansible timestamp facts. You can use the debug module for printing the output.

The following example gets the date on the remote system. Make sure you use the var attribute in debug module and not the msg.

  tasks:
  - name: Ansible date fact example
    debug:
      var=ansible_date_time.date

The output will be
ok: [127.0.0.1] => {
“ansible_date_time.date”: “2017-07-27”
}

You can easily get other formats of the timestamp by changing the parameter after ansible_date_time, in this case, date, to any of the following.

"date": "2017-07-27",
"day": "27",
"epoch": "1501173540",
"hour": "22",
"iso8601": "2017-07-27T16:39:00Z",
"iso8601_basic": "20170727T220900129160",
"iso8601_basic_short": "20170727T220900",
"iso8601_micro": "2017-07-27T16:39:00.129240Z",
"minute": "09",
"month": "07",
"second": "00",
"time": "22:09:00",
"tz": "IST",
"tz_offset": "+0530",
"weekday": "Thursday",
"weekday_number": "4",
"weeknumber": "30",
"year": "2017"

For example, if you need to get the current time you can do the following.

  tasks:
  - name: Ansible date timestamp example
    debug:
      var=ansible_date_time.epoch

Note: Make sure you have not switched off the fact gathering. That is you should not be using “gather_facts: no”. If you do you will get an error like below.

ansible_date_time.date”: “VARIABLE IS NOT DEFINED

Ansible local date

You can use the facts with host variable set to localhost to get the time in the local system.

Assign timestamp filename

You can use the timestamp in other ansible tasks. For example, you can use the time to create a dynamic file name which depends on the current system time of the remote machine.

- hosts: all
  tasks:
  - name: Ansible timestamp filename example
    command: touch example{{ansible_date_time.date}}.log

 

Retrieving local system time stamp using Ansible lookup

You can get the timestamp of the local machine using the Ansible lookup plugins. The following task will print the current local system date in the following format – ‘Fri Sep 29 16:31:40 PST 2017’.

- hosts: all
  tasks:
    - debug: msg="{{ lookup('pipe','date') }}"

You can format the output in the same way you would change the usual Linux date command. For example, the below task would output the date in the following format.’2017-09-29-16-37-41′.

- hosts: all
  tasks:
    - debug: msg="{{ lookup('pipe','date +%Y-%m-%d-%H-%M-%S') }}