官网:http://docs.saltstack.cn/ref/renderers/all/salt.renderers.jinja.html#module-salt.renderers.jinja
1.JINJA模板
Jinja是一种基于python的模板引擎,在SLS文件里可以直接使用jinja模板来做一些操作。
通过jinja模板可以为不同服务器定义各自的变量。
• 两种分隔符: {% … %} 和 {{ … }},前者用于执行诸如 for 循环 或赋值的语句,后者把表达式的结果打印到模板上
[root@server11 salt]# pwd
/srv/salt
[root@server11 salt]# vim test.sls
[root@server11 salt]# cat test.sls
/mnt/testfile:
file.append:
{% if grains['fqdn'] == 'server12' %}
- text: server12
{% elif grains['fqdn'] == 'server13' %}
- text: server13
{% endif %}
[root@server11 salt]# salt '*' state.sls test
#查看效果:
[root@server12 minion]# cd /mnt/
[root@server12 mnt]# ls
testfile
[root@server12 mnt]# cat testfile
server12
2.变量引用
[root@server11 salt]# cd apache/
[root@server11 apache]# pwd
/srv/salt/apache
[root@server11 apache]# ls
files init.sls
[root@server11 apache]# vim init.sls
#后面添加
/var/www/html/index.html:
file.managed:
- source: salt://apache/files/index.html
- template: jinja
- context:
NAME: server12##定义变量
[root@server11 apache]# vim files/index.html
[root@server11 apache]# cat files/index.html #NAME是变量,引用变量
{{ NAME }}
[root@server11 apache]# salt server12 state.sls apache
#查看效果:
[root@server12 mnt]# cat /var/www/html/index.html
server12
[root@server11 apache]# vim files/index.html
[root@server11 apache]# cat files/index.html
{{ grains['os'] }} - {{ grains['fqdn'] }}
{{ NAME }}
[root@server11 apache]# vim init.sls
#更改最后一行:
NAME: {{ grains['ipv4'][-1] }}
[root@server11 apache]# salt server2 state.sls apache
#查看效果:
[root@server12 mnt]# cat /var/www/html/index.html
RedHat - server12
192.168.100.242
[root@server11 apache]# vim init.sls
[root@server11 apache]# cat init.sls
apache:
pkg.installed:
- pkgs:
- httpd
- php
- php-mysql
file.managed:
- source: salt://apache/files/httpd.conf
- name: /etc/httpd/conf/httpd.conf
- template: jinja
- context:
port: 80
bind: {{ grains['ipv4'][-1] }}
service.running:
- name: httpd
- enable: true
- watch:
- file: apache
#/etc/httpd/conf/httpd.conf:
# file.managed:
# - source: salt://apache/files/httpd.conf
/var/www/html/index.html:
file.managed:
- source: salt://apache/files/index.html
- template: jinja
- context:
NAME: {{ grains['ipv4'][-1] }}
#更改地方:
file.managed:
- source: salt://apache/files/httpd.conf
- name: /etc/httpd/conf/httpd.conf
- template: jinja
- context:
port: 80
bind: {{ grains['ipv4'][-1] }}
[root@server11 apache]# vim files/httpd.conf
#更改地方:
Listen {{ bind }}:{{ port }}
[root@server11 apache]# salt server12 state.sls apache
#查看效果:
[root@server12 mnt]# netstat -antlp|grep 80
tcp 0 0 192.168.100.242:80 0.0.0.0:* LISTEN 5049/httpd
[root@server12 mnt]# cat /etc/httpd/conf/httpd.conf
Listen 192.168.100.242:80