Ansible Jinja Snippets

Templating Basics

Variables

{{ ... }}

Comments are ignored and will not be shown in the deployed file

{# ... #}

Code for loops and conditionals)

{% ... %}

For loop with if/else

{% for dir in dirs if dir != '/' %}
{% if loop.first %}
folders = {{ dir }}{{ ',' if not loop.last }}
{% else %}
          {{ dir }}{{ ',' if not loop.last }}
{% endif %}
{% endfor %}

Default filter

Fall back to default value if variable is not set

{{ custom_size | default(128) }}

or ignore the key if the value is missing

- name: install packages with pip
  pip: name= {{ item.name }} version={{ item.ver | default(omit) }}
  with_items: pip_packages

Ternary filter

The ternary expression is a nice abbreviation for if/else clauses:

{{ some_bool | ternary("value_if_true", "value_if_false") }}

Combine filter

Use the combine filter to merge data structures and override specific keys.

{{ some_dict | combine({'some_key': 'overwrite with new value'}) }}

Lookup filter

Use lookup to retrieve data from outside

{{ lookup('env', 'PATH') }}
{{ lookup('pipe', 'date') }}

or return the contents of first found file

{{
  lookup('file',
    lookup('first_found', [
      lookup('env', 'HOME') + '/prefered_file',
      lookup('env', 'HOME') + '/fallback_file'
    ])
  )
}}

Ansible special variables

Docs

  • group_names: list of groups assigned to current host
  • inventory_hostname: hostname of the current host as defined in the inventory
  • ansible_hostname: short hostname of the current host as discovered by ansible
  • ansible_fqdn: full hostname of the current host as discovered by ansible
  • ansible_distribution: linux distribution (eg debian) as discovered by ansible
  • ansible_distribution_release: linux distribution release (eg buster) as discovered by ansible
  • ansible_default_ipv4.address: default IPv4 address as discovered by ansible

Most nested variables can be retrieved either as dict

{{ ansible_eth0['ipv4']['address'] }}

or using the dot notation

{{ ansible_eth0.ipv4.address }}