From 3a4d476512924d81471ac326fb0bf2c3b59faef3 Mon Sep 17 00:00:00 2001 From: Matt Martz Date: Fri, 7 Dec 2018 11:25:53 -0600 Subject: [PATCH] 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 --- changelogs/fragments/jinja-now.yml | 2 ++ .../rst/user_guide/playbooks_templating.rst | 18 ++++++++++++++++++ lib/ansible/template/__init__.py | 14 ++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 changelogs/fragments/jinja-now.yml diff --git a/changelogs/fragments/jinja-now.yml b/changelogs/fragments/jinja-now.yml new file mode 100644 index 0000000000..4a0353d5ae --- /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 79cce0b41e..766aefec70 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 e336860b4e..2183b97f4c 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)