用 Ansible 發布單一 Tomcat 很簡單,但當線上同時有手機端、Web 端與管理後台三套 Tomcat 時,如果每套都寫一份 playbook,腳本會迅速膨脹且難以維護。本文示範如何把部署流程抽成共用模板,靠變數與 hosts 分組一次搞定多個实例。
實作过一次發布之後會發現,真正的差異只在「war 包路徑」與「Tomcat 根目錄」兩件事上,其餘的停機、清空、解壓、啟動流程完全一致。因此把這些差異抽成變數,流程本身即可重複利用。
假設要發布三套服務,分別位於不同主機:
接著編輯 /etc/ansible/hosts,把三套服務各自建成一個群組:
[tomcat-mobile] tomcat-mobile-01 ansible_ssh_host=192.168.100.101 ansible_ssh_port=22 ansible_ssh_user=root [tomcat-web] tomcat-web-01 ansible_ssh_host=192.168.100.102 ansible_ssh_port=22 ansible_ssh_user=root [tomcat-admin] tomcat-admin-01 ansible_ssh_host=192.168.100.103 ansible_ssh_port=22 ansible_ssh_user=root
這份模板是整個方案的關鍵,其中 tomcat_root 與 war_file 都是變數,由各自的部署 yml 傳入:
- name: stop tomcat
command: /bin/sh {{ tomcat_root }}/../../bin/catalina.sh stop -force
ignore_errors: yes
async: 10
- name: rm ROOT
file: state=absent dest="{{ tomcat_root }}"
- name: mkdir ROOT
file: state=directory dest="{{ tomcat_root }}"
- name: unzip war
unarchive: src="{{ war_file }}" dest="{{ tomcat_root }}" copy: yes
- name: rm war
file: state=absent dest="{{ war_file }}"
- name: start tomcat
command: /bin/sh {{ tomcat_root }}/../../bin/catalina.sh start
ignore_errors: yes
async: 10
tomcat-mobile.yml:
---
- name: install tomcat-mobile
hosts: tomcat-mobile
sudo: False
vars:
war_file: /data/build/tomcat-mobile.war
tomcat_root: /data/tomcat-mobile/webapps/ROOT
tasks:
- name: Include local facts
tasks: include: tomcat.yml
tomcat-web.yml:
---
- name: install tomcat-web
hosts: tomcat-web
sudo: False
vars:
war_file: /data/build/tomcat-web.war
tomcat_root: /data/tomcat-web/webapps/ROOT
tasks:
- name: Include local facts
tasks: include: tomcat.yml
tomcat-admin.yml:
---
- name: install tomcat-admin
hosts: tomcat-admin
sudo: False
vars:
war_file: /data/build/tomcat-admin.war
tomcat_root: /data/tomcat-admin/webapps/ROOT
tasks:
- name: Include local facts
tasks: include: tomcat.yml
發布時只需針對目標 playbook 執行:
/usr/bin/ansible-playbook tomcat-mobile.yml
這套做法的價值在於三點:以 include 消除重複腳本;以變數隔離差異;以 hosts 分組決定發布範圍。日後 tomcat-web 要擴成五台,只要把 SSH 打通、在 hosts 群組裡補上主機,就能按組擴展,不必再動任何流程碼。