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:
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
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.
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.