-
Notifications
You must be signed in to change notification settings - Fork 1
Jinja2_Basics
This wiki page has been moved to [docs](https://github.com/reallyenglish/ansible-role-example/tree/master/docs)
and is no longer maintained.
- Jinja2 Basics
- Variables
- Loops
- Conditional
- See if a key exists in a dict
- Merging two dict variables
- Creating filters and tests
Jinja2 is the template engine of ansible. Honestly, I am not a fun of it. The documentation is sometimes cryptic and does not clearly explain what you should know. Here is a list of what you should know about jinja2 to write ansible roles and plays.
In a template, you have access to all ansible variables. In rare cases, you
need to create variables in a template. In those cases, remember that variables
declared in a template have no scope, meaning the variables are always in
global scope in the template. Use set
to declare a variable in a template.
{% set foo = 'bar' %}
{% if something is defined %}
{% set foo = 'baz' %} # NOT local to the `if` scope
{% endif %}
{{ foo }}
The both of foo
is same variable. If something
is defined, the result is
baz
, which might not be what you expect.
{% set l = [ 'foo', 'bar' ] %}
{% for i in l %}
{{ i }}
{% endfor %}
{% set d = { 'foo': 1, 'bar': 2 } %}
{% for k, v in d %}
{{ k }} = {{ v }}
{% endfor %}
But in almost all cases, you would need dictsort
because a dict is not
ordered, which breaks idempotentcy.
{% set d = { 'foo': 1, 'bar': 2 } %}
{% for k, v in d | dictsort %}
{{ k }} = {{ v }}
{% endfor %}
If you are not interested in values, simply use for
.
{% for key in d | dictsort %}
key == {{ key }}
{% endfor %}
{% if foo is defined %}
foo is defined
{% endif %}
It's elif
, not elseif
or elsif
..
{% if foo is defined %}
foo is defined
{% elif %}
foo is not defined
{% endif %}
No, jinja2 does not have case
. Use if ... elif ... elif ... endif
.
{% if 'the_key' in a_dict %}
... do something ...
{% endif %}
This is often used in tasks. The following example runs command when a dict, bar\_dict
has foo
in the keys.
- command: /path/to/command
when: "{{ 'foo' in bar_dict }}"
ansible
2.0 and later implements
combine,
which is useful to override keys when missing. See how it is used in a
role,
which overrides missing keys..