Definition
Why would you need ansible_managed
in Ansible?
ansible_managed
is a special variable created exclusively for the ansible.builtin.template
and ansible.windows.win_template
modules, which allows you to leave a special identifying mark in the generated templates
According to ansible best-practice, every Jinja2 template should have such a mark at the beginning of the template so that it can be easily determined which files were created or modified using Ansible
There are additional subvariables for ansible_managed
:
{file}
— full path to template (on controller host){host}
— hostname of controller{uid}
— username on controller hoststrftime
timestamp —%Y-%m-%d %H:%M:%S
(man strftime 3
)
Note that using any of the above variables (especially timestamp) may break idempotency!
It is recommended to use {{ ansible_managed | comment }}
instead of # {{ ansible_managed }}
, since the comment filter can automatically match the comment to the file type and the number of comment characters when processing multi-line, for example with the following configuration:
[defaults]
ansible_managed = This file is managed by Ansible.%n
template: {file}
date: %Y-%m-%d %H:%M:%S
user: {uid}
host: {host}
Practice
The # {{ ansible_managed }}
option will add (the values are taken as an example):
# This file is managed by Ansible.
template: tmpl.j2
date: 2024-01-01 01:01:01
user: admin
host: localhost
At the same time, the {{ ansible_managed | comment }}
option will add:
#
# This file is managed by Ansible.
#
# template: tmpl.j2
# date: 2024-01-01 01:01:01
# user: admin
# host: localhost
#
Well, since Ansible allows you to extend its functionality using plugins, we can define any lookup plugin and substitute its value in ansible_managed. For example, this is how you can add the latest project commit to the template (example was taken from here https://jpmens.net/2020/09/29/using-ansible-managed/):
[defaults]
ansible_managed = "$Ansible {{{{ template_path|basename + lookup('pipe', 'git log --format=",%%h %%ad %%ae" -1 --date=format:"%%Y/%%m/%%d %%H:%%M" ' + template_fullpath|quote)|default(",UNCOMMITED", True) }}}}$"