一、JINJA2模板介绍
Jinja2是Python下一个被广泛应用的模版引擎 他的设计思想来源于Django的模板引擎, 并扩展了其语法和一系列强大的功能。 其中最显著的一个是增加了沙箱执行功能和可选的自动转义功能
二、书写规则
1.示例
vim 3.yml
1 ---
2 - name: demo
3 hosts: server
4 tasks:
5 - template:
6 src: ./1.j2
7 dest: /mnt/westos
vim 1.j2
1 {# /mnt/westos
2 hello word
3 {{ ansible_facts['all_ipv4_addresses'] }} {{ ansible_facts['lvm']['lvs']}}
2.for循环的写法
vim demo.j2
1 {% for westos in name %}
2 {{loop.index0}}-{{westos}}
3 {% endfor %}
vim name.yml
1 ---
2 - name: demo
3 hosts: server
4 gather_facts: no
5 vars_files:
6 ./bianliang.yml
7 tasks:
8 - template:
9 src: ./demo.j2
10 dest: /mnt/westos
三、if语句的基本使用
vim demo.j2
1 {% for westos in name if not name == "linux" %}
2 {{loop.index0}} - {{westos}} {{ansible_facts['fqdn']}}
3 {% endfor %}
vim name.yml
1 ---
2 - name: demo
3 hosts: server
4 vars:
5 - name:
6 - linux:
7 - westos:
8 - ansible:
9 tasks:
10 - template:
11 src: ./demo.j2
12 dest: /mnt/westos
vim demo.j2
1 {% for westos in name %}
2 {% if westos['group'] is defined %}
3 {{westos}}group:{{westos['group']}}
4 {% endif %}
5 {% if westos['password'] is defined %}
6 {{westos}}password:{{westos['password']}}
7 {% endif %}
8 {% if westos['uid'] is defined %}
9 {{wesos}}uid:{{westos['uid']}}
10 {% endif %}
11 {% if westos['group'] is not defined %}
12 {{loop.index}}-{{westos}}
13 {% endif %}
14 {% endfor %}
vim name.yml
1 ---
2 - name: demo
3 hosts: server
4 vars:
5 - name:
6 - linux:
7 uid: 0
8 group: westos
9 password: linux
10 - westos:
11 udi: 1000
12 group: linux
13 password: 1000
14 - ansible:
15 - age:
16 - password:
17 - apache:
18 uid: 20
19 group: http
20 password:
21 tasks:
22 - template:
23 src: ./demo.j2
24 dest: /mnt/westos
4.文件加密控制
ansible-vault view westos.yml
ansible-vault create westos.yml
ansible-vault create --vault-password-file=password westos
ansible-vault decrypt westos.yml
ansible-vault encrypt westos.yml
ansible-playbook name.yml --ask-vault-pass
ansible-vualt encrypt_string 'name' --name 'westos'
ansible-vault rekey westos.yml
上面的输出表明密码已使用AES 256加密进行了加密。之后,从!vault |拷贝整个加密的代码。前往剧本文件,删除明文密码值,然后粘贴加密后的值,如下所示。
总结
|