一、template模版和jinja2模版的关系
模板是一个文本文件,嵌套有脚本(使用模板编程语言编写)
jinja2 是 Python 的全功能模板引擎
Ansible如何使用jinja2:
ansible 使用 jinja2 模板需要借助 template 模块实现,那 template 模块是用来做什么的?
template 模块和 copy 模块完全一样,都是拷贝文件至远程主机,
区别在于template 模块会解析要拷贝的文件中变量的值,而 copy 则是原封不动的将文件拷贝至被控端。
jinja模板基本语法:
1、要想在配置文件中使用 jinja2 , playbook 中的 tasks 必须使用 template 模块
2、配置文件里面使用变量,比如使用 {{ facts变量 }}
二、jinja2模板逻辑关系
1、if 判断表达式
举例1:if
# vim if.txt.j2
file if.txt.j2
{% if username == "tom" %}
name: {{ name1 }}
age: {{ age1 }}
{% endif %}
# vim if.yaml
---
- hosts: web1
vars:
- name1: "tom"
age1: "18"
- name2: "jerry"
age2: "20"
- name3: "zhangsan"
age3: "22"
tasks:
- name: copy if.txt.j2
template:
src: /root/if.txt.j2
dest: /tmp/if.txt
# ansible-playbook if.yaml -e username=tom
举例2:if--elif
# vim file if.txt.j2
file if.txt.j2
{% if username == "tom" %}
name: {{ name1 }}
age: {{ age1 }}
{% elif username == "jerry" %}
name: {{ name2 }}
age: {{ age2 }}
{% elif username == "alluser" %}
name: {{ name1 }}
age: {{ age1 }}
name: {{ name2 }}
age: {{ age2 }}
name: {{ name3 }}
age: {{ age3 }}
{% endif %}
# vim if.yaml
---
- hosts: web1
vars:
- name1: "tom"
age1: "18"
- name2: "jerry"
age2: "20"
- name3: "zhangsan"
age3: "22"
tasks:
- name: copy if.txt.j2
template:
src: /root/if.txt.j2
dest: /tmp/if.txt
执行剧本时使用-e传递参数
# ansible-playbook if.yaml -e username=alluser
二、循环表达式
举例1:for
# vim for.txt.j2
file for.txt.j2
{% for userlist in username %}
{{ userlist }}
{% endfor %}
# vim for.yaml
---
- hosts: web1
vars:
- username: ["zhangsan","lisi","wangwu"]
tasks:
- name: copy for.txt.j2
template:
src: /root/for.txt.j2
dest: /tmp/for.txt
# ansible-playbook for.yaml
举例2:
# vim for.txt.j2
file for.txt.j2
{% for userlist in username %}
{{ userlist.name }}:{{ userlist.age }}
{% endfor %}
# vim for.yaml
---
- hosts: web1
vars:
- username:
- name: "tom"
age: "18"
- name: "jerry"
age: "20"
- name: "zhangsan"
age: "22"
tasks:
- name: copy for.txt.j2
template:
src: /root/for.txt.j2
dest: /tmp/for.txt
# ansible-playbook for.yaml
三、for循环+if判断
举例:
# vim for.yaml
---
- hosts: web1
vars:
- username:
- name: "zhangsan"
age: "18"
- name: "lisi"
age: "20"
- name: "wangwu"
age: "22"
tasks:
- name: copy for.txt.j2
template:
src: /root/for.txt.j2
dest: /tmp/for.txt
# vim file for.txt.j2
file for.txt.j2
{% for userlist in username %}
{% if userlist.name == "zhangsan" %} # {% if userlist.age == "zhangsan" %}
{{ userlist.name }}: {{ userlist.age }}
{% endif %}
{% endfor %}
# ansible-playbook for.yaml