Ansible: Date and Time

Anyone who works with Ansible knows how to access the current date and time. But have you ever dealt with something a bit more advanced? There are a few tips you may find helpful.

I worked on the certificate validation report. From a programming and automation standpoint, it's boring:

  • Access target and read certificate from keystore
  • Grab the expiration date from the output. Let's say it's a string "12/15/22"
  • Test if it expires within two months from today

Ansible doesn't offer much for current date/time manipulations. Fact -  ansible_date_time, and converter to_datetime. For all the rest, one should rely on Jinja2 and Python. Ansible is well known for smart types conversion, but the first attempt fails:

- name: Get Days from Today
  set_fact:
    lifecount: "{{ some_date - today }}"
  vars:
    today: "{{ ansible_date_time.iso8601 }}"
    some_date: "{{ '12/15/22' | to_datetime('%m/%d/%y')) }}"
Use ISO date in the hope that Ansible/Jinja does the conversion.

The task above fails miserably. Function to_datetime returns a value of Python's datetime, yet the variable today is just a string. Let's convert everything to datetime. Please make a note that now I use ansible_date_time.date not iso8601

- name: Get Days from Today
  set_fact:
    lifecount: "{{ some_date - today }}"
  vars:
    today: "{{ ansible_date_time.date | to_datetime('%Y-%m-%d') }}"
    some_date: "{{ '12/15/22' | to_datetime('%m/%d/%y')) }}"
Line up variable types 

To my surprise, this task has failed too. After a quick research and a set of trials and errors with multiple Ansible versions, I found a solution.

- name: Ansible Date Operations
  hosts: all
  tasks:
    - name: Get Days from Today
      set_fact:
        lifecount: "{{ (some_date |to_datetime - today|to_datetime).days }}"
      vars:
        today: "{{ ansible_date_time.date | to_datetime('%Y-%m-%d') }}"
        some_date: "{{ '12/15/22' | to_datetime('%m/%d/%y') }}"

    - name: Show Facts
      debug:
        msg: "You have  {{ lifecount }} days left."
Calculate time interval

It doesn't matter what type your object has inside the Jinja template. Jinja2 engine converts an object to its String representation before returning the result to Ansible.  

You can find the source code in our GitHub repository.