我有一個Ansible作爲init.d守護程序部署Java應用程序的手冊。使用Ansible檢查服務是否存在
作爲Ansible和Linux的初學者,我很難根據主機的狀態有條件地執行主機上的任務。
即我有一些主機已經存在和運行的服務,我想在做任何事情之前停止它。然後可能會有新的主機,它們還沒有服務。所以我不能簡單地使用service: name={{service_name}} state=stopped
,因爲這會在新主機上失敗。
我該如何做到這一點?這是我到目前爲止:
- name: Check if Service Exists
shell: "if chkconfig --list | grep -q my_service; then echo true; else echo false; fi;"
register: service_exists
# This should only execute on hosts where the service is present
- name: Stop Service
service: name={{service_name}} state=stopped
when: service_exists
register: service_stopped
# This too
- name: Remove Old App Folder
command: rm -rf {{app_target_folder}}
when: service_exists
# This should be executed on all hosts, but only after the service has stopped, if it was present
- name: Unpack App Archive
unarchive: src=../target/{{app_tar_name}} dest=/opt
你也可以使用'ignore_errors',尤其是與寄存器,以DET等等。 – tedder42
是的,我避開了ignore_errors,因爲我害怕由於錯字等原因造成的錯誤否定。另外,我試圖說服我的團隊投入自動化配置管理,並且不希望首先讓他們看起來像是某種黑客行爲。 :) – EagleBeak
解決方案也適用於Ubuntu,並且應該可能適用於大多數Linux發行版。 –