diff --git a/changelogs/fragments/jinja-now.yml b/changelogs/fragments/jinja-now.yml new file mode 100644 index 00000000000..4a0353d5ae6 --- /dev/null +++ b/changelogs/fragments/jinja-now.yml @@ -0,0 +1,2 @@ +minor_changes: +- jinja2 - Add ``now()`` function for getting the current time diff --git a/docs/docsite/rst/user_guide/playbooks_templating.rst b/docs/docsite/rst/user_guide/playbooks_templating.rst index 79cce0b41e3..766aefec707 100644 --- a/docs/docsite/rst/user_guide/playbooks_templating.rst +++ b/docs/docsite/rst/user_guide/playbooks_templating.rst @@ -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 `_ string that will be used + to return a formatted date time string + .. seealso:: diff --git a/lib/ansible/template/__init__.py b/lib/ansible/template/__init__.py index e336860b4e1..2183b97f4c8 100644 --- a/lib/ansible/template/__init__.py +++ b/lib/ansible/template/__init__.py @@ -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)