top.sls 是組態管理的入口檔案,一切都是從這裡開始,在master 主機上,預設存放在/srv/salt/目錄. top.sls 預設從 base 標籤開始解析執行,下一級是操作的目標,可以通過正則,grain模組,或分組名,來進行匹配,再下一級是要執行的state檔案,不包換副檔名。
一、建立 /srv/salt/top.sls
[root@localhost salt]# cat top.sls
base:
'*':
- apache
二、定義pillar檔案
[root@localhost pillar]# cat apache/init.sls
apache:
{% if grains.id == "salt-minion-01" %}
port: 8090
{% elif grains.id == "salt-minion-02" %}
port: 8093
{% else %}
port:80
{% endif %}
[root@localhost pillar]# pwd
/srv/pillar
#重新整理pillar資料
[root@localhost pillar]# salt '*' saltutil.refresh_pillar
salt '*' saltutil.refresh_pillar
salt-minion-01:
True
salt-minion-02:
True
#查看pillar中定義的所有的值
[root@localhost salt]# salt '*' pillar.data
salt-minion-01:
----------
apache:
----------
port:
8090
salt-minion-02:
----------
apache:
----------
port:
8093
#只是查看apache 的值
[root@localhost salt]# salt '*' pillar.get apache
salt-minion-02:
----------
port:
8093
salt-minion-01:
----------
port:
8090
[root@localhost salt]#
pillar VS grains
pillar是在master上定義變數,grains是擷取minion端的值
三、編寫apache檔案
[root@localhost salt]# pwd
/srv/salt
[root@localhost salt]# cat apache/init.sls
apache_install:
pkg:
- name: httpd
- installed
file.managed:
- source: salt://apache/files/httpd.conf
- name: /etc/httpd/conf/httpd.conf
- template: jinja
- defaults:
port: {{salt['pillar.get']('apache:port',80)}}
- require:
- pkg: apache_install
service.running:
- name: httpd
- enable: True
- reload: True
- watch:
- file: /etc/httpd/conf/httpd.conf
- pkg: apache_install
apache_install 是id號可以自訂
pkg,file,service 是 salt的 state module
require: 依賴某個state,在運行此state前,先運行依賴的state,依賴可以有多個
watch: 在某個state變化時運行此模
port:{{salt['pillar.get']('apache:port',80)}} 擷取pillar中定義的apache port的值
四、修改httpd.conf 的模板檔案
blob.png
這樣定義完成之後就發行就緒了
五、發布到salt-minion節點上去
salt '*' state.highstate
blob.png
補充:
1、 如果要安裝多個軟體包,啟動多個服務。這裡我們以安裝http和php-fpm軟體包為例
[root@localhost apache]# cat init.sls.bak
apache_install:
pkg:
- name: httpd
- pkgs:
- httpd
- php-fpm
- installed
file.managed:
- source: salt://apache/files/httpd.conf
- name: /etc/httpd/conf/httpd.conf
- template: jinja
- defaults:
port: 8029
- require:
- pkg: apache_install
service.running:
- name: httpd
- enable: True
- reload: True
- watch:
- file: /etc/httpd/conf/httpd.conf
- pkg: apache_install
php-fpm:
service.running:
- enable: True
- reload: True
- watch:
- pkg: apache_install
2、top.sls 檔案不僅僅支援正則還支援分組和grains。
通過正則進行匹配的樣本,
base:
'*':
- webserver
通過分組名進行匹配的樣本,必須要有 – match: nodegroup
base:
group1:
- match: nodegroup
- webserver
通過grain模組匹配的樣本,必須要有- match: grain
base:
'os:Fedora':
- match: grai
- webserver