一、JinJa2 介绍

  1. Jinja2是基于Python书写的模板引擎。功能类似于PHP smarty模板。
  • jinja2 ⽂件以 .j2 为后缀, 也可以不写后缀
  • jinja2 中存在 三种定界符
    • 注释: {# 注释内容 #}
    • 变量引⽤: {{ var }}
    • 逻辑表达: {% %}

      二、JinJa2 逻辑控制

      1. 条件表达

      {% if %}
      ...
      {% elif %}
      ...
      {% else %}
      ...
      {% endif %}
      

      Example:

      如果定义了 idc 变量, 则输出
      {% if idc is defined %}
      {{ idc }}
      {% elif %}
      没有定义
      {% endif %}
      

      2. 循环控制

      {% for xxx in *** %}
      ...
      ...
      {% endfor %}
      

      Example:

      列举出 dbservers 这个 group 中的所有主机
      {% for hosts in groups['dbservers'] %}
      {{ hosts }}
      {% endfor %}
      
      注意:与Python 语法不同,JinJa2模板中的循环不能使用break或continue,但可以在迭代中过滤序列来跳过某些项
      ```shell {# 打印dbservers 组中的所有主机,但是不打印1.1.1.1 这台主机 #}

{% for host in groups[‘dbservers’] if host != “1.1.1.1” %} {{host}} {% endfor %}

<a name="xxVJ3"></a>
### 3. Jinja2 模板的使用
<a name="x7nDf"></a>
####  1)基于FactsJinja2 实例 
[root@localhost ~]# vim  config.j2
```shell
{# use variable example #}
wlecome host {{ ansible_hostname }}, os is {{ ansible_os_family }} today is {{ ansible_date_time.date }} cpucore numbers {{ ansible_processor_vcpus }}

{# use condition example #}
{% if ansible_processor_vcpus > 1 %}
OS CPU more than one core
{% endif %}

{% for m in ansible_mounts if m['mount'] != "/" %}
mount {{ m['mount'] }}, total size is {{m['size_total']}}, free size is {{m['size_available']}}
{% endfor %}

2)在Ansible 中使用Jinja2 模板

---
- name: a template example
  hosts: all
  remote_user: root
  tasks:
    - name: update jinja2 config
      template: src=config.j2 dest=/tmp/config.conf