上一節把整體配置概況列了出來,這節聚焦在 /etc/ansible/roles/tomcat 這個 role 目錄底下,每個子目錄各自負責什麼。
目錄結構如下:
.
├── files
│ └── tomcat-initscript.sh
├── handlers
│ └── main.yml
├── tasks
│ └── main.yml
└── templates
├── iptables-save
├── server.xml
└── tomcat-users.xml
tasks/main.yml 裡有這樣兩段:
- name: Configure Tomcat server template: src=server.xml dest=/usr/share/tomcat/conf/ notify: restart tomcat - name: Configure Tomcat user template: src=tomcat-users.xml dest=/usr/share/tomcat/conf/ notify: restart tomcat
template 模組官方說法是「把檔案以模板方式分送到遠端主機」。也就是說,當 src 指定的檔案內容發生變化時,就觸發 notify 後面的動作。
存放上述被分送的檔案,實務上多為各類設定檔。
handlers/main.yml 定義 notify 要跑的東西:
- name: restart tomcat service: name=tomcat state=restart
整體流程就是:templates 中的檔案變動 → 觸發 notify → 執行 handlers/main.yml 裡對應的動作。要注意 notify 後面的名稱必須與 handlers 中 name 的值完全一致,拼字差一個字就不會被觸發。
files 目錄放的是腳本一類的檔案,透過 copy 模組送到遠端主機,之後再由 notify 觸發 handlers 去執行它。
把 role 拆成這幾個目錄,playbook 就能保持乾淨,而設定變更時也能自動收斂到正確狀態,這是 roles 最大的價值。