How to set date time to Ansible variable

Tue, Oct 18, 2016

#Ansible #Jenkins #devops

Problem: To create a variable in Ansible playbook using current date and time.

Solution: Use set_fact and lookup plugins in Ansible.

---
- hosts: localhost
  vars:
  tasks:
    - name: new variable with current date time
      set_fact: temp="{{lookup('pipe','date \"+%Y-%m-%d %H:%M\"')}}"
    - name: print variable
      debug: msg="Current date and time is {{temp}}"

And the result of running it

$ ansible-playbook ansible.yml 
[WARNING]: Host file not found: /etc/ansible/hosts

[WARNING]: provided hosts list is empty, only localhost is available


PLAY [localhost] ***************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [new variable with current date time] *************************************
ok: [localhost]

TASK [print variable] **********************************************************
ok: [localhost] => {
  "msg": "Current date and time is 2016-10-18 13:58"
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0  

That’s it. The lookup plugins allow us to run shell command and pass the result back to the playbook, and thus we can assign the result to a variable using set_fact

Summary


In this post we’ve learned how to assign current date time to a variable in Ansible playbook. This might come in handy when we need to output the date time of this Ansible playbook is run to a log file or notification system.