Ansible Jinjia2模块

Ansible Template使用jinjia2格式。

还可以使用jinjia2的filter来实现跟进一步的功能扩展:

  | to_json  | to_nice_json  | to_yaml  | to_nice_yaml

 

基本语法:

{% for i in range(1,10)%}
        server 172.16.1.{{i}};
{% endfor %}


#判断
{% if ansible_fqdn == "web01" %}
        echo 123
{% elif ansible_fqdn == "web02" %}
        echo 456
{% else %}
        echo 789
{% endif %}

 

template模块

    - name: Configure nginx Server
      template:
        src: /etc/conf.j2
        dest: /etc/test.conf

 

jinjia2模板

# jinjia2可以直接使用Ansible的魔法变量:hostvars  groups  inventory_hostname  group_names
# jinjia2也可以直接使用Ansible Facts的变量

{% for host in hosts %} {{ host }} {% endfor %}

 

示例1 生成host文件

yaml文件

---
- name: tempalte
  hosts: all
  tasks:
    - name: Create hosts
      template:
        src: template/hosts.j2
        dest: /tmp/hosts
      when: '"dev" in group_names'  # 只有dev组的才执行

template文件

{% for host in groups['all'] %}
{{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }}  {{ hostvars[host]['ansible_facts']['fqdn'] }}  {{ hostvars[host]['ansible_facts']['hostname'] }}
{% endfor %}

 

 

 

官网链接:

filters: https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html

posted @ 2020-03-29 11:14  Vincen_shen  阅读(879)  评论(0编辑  收藏  举报