1.編輯文件,添加jinja模塊
[root@server1 apache]# cat install.sls
install-apache:
pkg.installed:
- pkgs:
- httpd
file.managed:
- name: /etc/httpd/conf/httpd.conf
- source: salt://apache/files/httpd.conf
- template: jinja ##導入jinja模塊
- context:
port: 80
host: 172.25.31.2
service.running:
- name: httpd
- reload: True
- watch:
- file: install-apache
[root@server1 apache]# vim files/httpd.conf
42 Listen {{ host }}:{{ port}}
2.可以在一個文件中定義變量並且在httpd的配置文件中將變量進行導入,操作如下:
[root@server1 apache]# pwd
/srv/salt/apache
[root@server1 apache]# ls
apache.sls files install.sls lib.sls
[root@server1 apache]# cat lib.sls
{% set host = '172.25.31.2' %}
[root@server1 apache]# cat install.sls
install-apache:
pkg.installed:
- pkgs:
- httpd
file.managed:
- name: /etc/httpd/conf/httpd.conf
- source: salt://apache/files/httpd.conf
- template: jinja
- context:
port: 80
service.running:
- name: httpd
- reload: True
- watch:
- file: install-apache
[root@server1 apache]# vim files/httpd.conf
第一行插入:
測試:
[root@server1 apache]# salt server2 state.sls apache.install
server2的http配置文件第一行爲空
jinja結合grains的使用
[root@server1 apache]# vim install.sls
[root@server1 apache]# cat install.sls
install-apache:
pkg.installed:
- pkgs:
- httpd
file.managed:
- name: /etc/httpd/conf/httpd.conf
- source: salt://apache/files/httpd.conf
- template: jinja
- context:
port: 80
host: {{ grains['ipv4'][1] }}
service.running:
- name: httpd
- reload: True
- watch:
- file: install-apache
[root@server1 apache]# vim files/httpd.conf
[root@server1 apache]# salt server2 state.sls apache.install
jinja模版結合pillar
[root@server1 apache]# vim install.sls
[root@server1 apache]# cat install.sls
install-apache:
pkg.installed:
- pkgs:
- httpd
file.managed:
- name: /etc/httpd/conf/httpd.conf
- source: salt://apache/files/httpd.conf
- template: jinja
- context:
port: {{ pillar['port'] }} ##引入pillar
host: {{ pillar['ip'] }}
service.running:
- name: httpd
- reload: True
- watch:
- file: install-apache
[root@server1 apache]# vim /srv/pillar/web/vars.sls
[root@server1 apache]# cat /srv/pillar/web/vars.sls
{% if grains['fqdn'] == 'server2' %}
webserver: httpd
ip: 172.25.31.2
port: 80
{% elif grains['fqdn'] == 'server3' %}
webserver: nginx
ip:172.25.31.3
port: 80
{% endif %}
測試:
[root@server1 apache]# salt server2 state.sls apache.install