Add now() jinja2 global func for getting the date/time (#43792)

* Add now() jinja2 global func for getting the date/time

* Docs and changelog

* now isn't a lookup, it doesn't need disabled
pull/49673/head
Matt Martz 6 years ago committed by GitHub
parent 3d5d0d355f
commit 3a4d476512
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,2 @@
minor_changes:
- jinja2 - Add ``now()`` function for getting the current time

@ -18,6 +18,24 @@ Please note that all templating happens on the Ansible controller before the tas
playbooks_lookups
playbooks_python_version
.. _templating_now:
Get the current time
````````````````````
.. versionadded:: 2.8
The ``now()`` Jinja2 function, allows you to retrieve python datetime object or a string representation for the current time.
The ``now()`` function supports 2 arguments:
utc
Specify ``True`` to get the current time in UTC. Defaults to ``False``
fmt
Accepts a `strftime <https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior>`_ string that will be used
to return a formatted date time string
.. seealso::

@ -559,6 +559,18 @@ class Templar:
def _fail_lookup(self, name, *args, **kwargs):
raise AnsibleError("The lookup `%s` was found, however lookups were disabled from templating" % name)
def _now_datetime(self, utc=False, fmt=None):
'''jinja2 global function to return current datetime, potentially formatted via strftime'''
if utc:
now = datetime.datetime.utcnow()
else:
now = datetime.datetime.now()
if fmt:
return now.strftime(fmt)
return now
def _query_lookup(self, name, *args, **kwargs):
''' wrapper for lookup, force wantlist true'''
kwargs['wantlist'] = True
@ -669,6 +681,8 @@ class Templar:
t.globals['lookup'] = self._lookup
t.globals['query'] = t.globals['q'] = self._query_lookup
t.globals['now'] = self._now_datetime
t.globals['finalize'] = self._finalize
jvars = AnsibleJ2Vars(self, t.globals)

Loading…
Cancel
Save