Skip to content

Commit 3a4d476

Browse files
authored
Add now() jinja2 global func for getting the date/time (ansible#43792)
* Add now() jinja2 global func for getting the date/time * Docs and changelog * now isn't a lookup, it doesn't need disabled
1 parent 3d5d0d3 commit 3a4d476

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

changelogs/fragments/jinja-now.yml

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

docs/docsite/rst/user_guide/playbooks_templating.rst

+18
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,24 @@ Please note that all templating happens on the Ansible controller before the tas
1818
playbooks_lookups
1919
playbooks_python_version
2020

21+
.. _templating_now:
22+
23+
Get the current time
24+
````````````````````
25+
26+
.. versionadded:: 2.8
27+
28+
The ``now()`` Jinja2 function, allows you to retrieve python datetime object or a string representation for the current time.
29+
30+
The ``now()`` function supports 2 arguments:
31+
32+
utc
33+
Specify ``True`` to get the current time in UTC. Defaults to ``False``
34+
35+
fmt
36+
Accepts a `strftime <https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior>`_ string that will be used
37+
to return a formatted date time string
38+
2139

2240
.. seealso::
2341

lib/ansible/template/__init__.py

+14
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,18 @@ def _finalize(self, thing):
559559
def _fail_lookup(self, name, *args, **kwargs):
560560
raise AnsibleError("The lookup `%s` was found, however lookups were disabled from templating" % name)
561561

562+
def _now_datetime(self, utc=False, fmt=None):
563+
'''jinja2 global function to return current datetime, potentially formatted via strftime'''
564+
if utc:
565+
now = datetime.datetime.utcnow()
566+
else:
567+
now = datetime.datetime.now()
568+
569+
if fmt:
570+
return now.strftime(fmt)
571+
572+
return now
573+
562574
def _query_lookup(self, name, *args, **kwargs):
563575
''' wrapper for lookup, force wantlist true'''
564576
kwargs['wantlist'] = True
@@ -669,6 +681,8 @@ def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=
669681
t.globals['lookup'] = self._lookup
670682
t.globals['query'] = t.globals['q'] = self._query_lookup
671683

684+
t.globals['now'] = self._now_datetime
685+
672686
t.globals['finalize'] = self._finalize
673687

674688
jvars = AnsibleJ2Vars(self, t.globals)

0 commit comments

Comments
 (0)