Bootstrap FreeKB - Ansible - ansible_date_time fact
Ansible - ansible_date_time fact

Updated:   |  Ansible articles

There are a few different ways to do something with datetime in Ansible.

ansible_date_time is a fact so gather_facts must NOT be set to false.

Here is a simple example.

---
- hosts: localhost
  tasks:
  - debug: 
      var: ansible_date_time
...

 

Which should return something like this.

ok: [localhost] => {
    "ansible_date_time": {
        "date": "2023-07-06", 
        "day": "06", 
        "epoch": "1688625389", 
        "hour": "01", 
        "iso8601": "2023-07-06T06:36:29Z", 
        "iso8601_basic": "20230706T013629204597", 
        "iso8601_basic_short": "20230706T013629", 
        "iso8601_micro": "2023-07-06T06:36:29.204597Z", 
        "minute": "36", 
        "month": "07", 
        "second": "29", 
        "time": "01:36:29", 
        "tz": "CDT", 
        "tz_offset": "-0500", 
        "weekday": "Thursday", 
        "weekday_number": "4", 
        "weeknumber": "27", 
        "year": "2023"
    }
}

 

To return only the date.

---
- hosts: localhost
  tasks:
  - debug: 
      var: ansible_date_time.date
...

 

Something like this should be returned.

ok: [localhost] => {
    "ansible_date_time.date": "2023-07-06"
}

 

Or only the time.

---
- hosts: localhost
  tasks:
  - debug: 
      var: ansible_date_time.time
...

 

Something like this should be returned.

ok: [localhost] => {
    "ansible_date_time.time": "01:36:10"
}

 

Here is one way you could go about formatting the date and time.

---
- hosts: localhost
  vars:
    date: "{{ ansible_date_time.year }}-{{ ansible_date_time.month }}-{{ ansible_date_time.day }}"
    time: "{{ ansible_date_time.hour }}:{{ ansible_date_time.minute }}:{{ ansible_date_time.second }}"
  tasks:
  - debug:
      var: date

  - debug:
      var: time
...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b52864 in the box below so that we can be sure you are a human.