Is it possible to manipulate date in Ansible Playbook
We use ansible_date_time.hour
it ansible_date_time.minute
in one of my playlists.
But I need to add time to these facts (or in a variable) .. i.e. if it ansible_date_time.hour
returns 16 - I want to add a couple of hours or if it ansible_date_time.minute
returns 40 - I want it to be 50 ..
Of course there is a ceiling of 23 and 59 for hours and minutes ... as I was thinking about registering a variable:
- name: Register HH
shell: date '+%H'
register: HP_HH
- debug: msg="{{ HP_HH.stdout | int + 3 }}"
But obviously, if my game works after 9:00 pm, I'm out of luck.
Does anyone have a suggestion or workaround?
source to share
AFAIK, it is not possible to add / subtract time units from a window in Ansible.
You can convert strings to object datetime
with filter to_datetime
(Ansible 2.2+).
You can calculate the date difference. See this answer.
But if you don't mind using a simple filter plugin, here you go:
Place this code like ./filter_plugins/add_time.py
next to your book:
import datetime
def add_time(dt, **kwargs):
return dt + datetime.timedelta(**kwargs)
class FilterModule(object):
def filters(self):
return {
'add_time': add_time
}
And you can use your own filter add_time
like this:
- hosts: localhost
gather_facts: yes
tasks:
- debug:
msg: "Current datetime is {{ ansible_date_time.iso8601 }}"
- debug:
msg: "Current time +20 mins {{ ansible_date_time.iso8601[:19] | to_datetime(fmt) | add_time(minutes=20) }}"
vars:
fmt: "%Y-%m-%dT%H:%M:%S"
add_time
has the same parameters as timedelta in Python.
source to share