2015-05-19 2080 views
19

我有一個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 

回答

22

當然,我也可以檢查包裝腳本是否存在於/etc/init.d中。所以這是我結束了:

- name: Check if Service Exists 
    stat: path=/etc/init.d/{{service_name}} 
    register: service_status 

    - name: Stop Service 
    service: name={{service_name}} state=stopped 
    when: service_status.stat.exists 
    register: service_stopped 
+0

你也可以使用'ignore_errors',尤其是與寄存器,以DET等等。 – tedder42

+1

是的,我避開了ignore_errors,因爲我害怕由於錯字等原因造成的錯誤否定。另外,我試圖說服我的團隊投入自動化配置管理,並且不希望首先讓他們看起來像是某種黑客行爲。 :) – EagleBeak

+0

解決方案也適用於Ubuntu,並且應該可能適用於大多數Linux發行版。 –

6

這將是很好,如果「服務」模塊可以處理「無法識別的服務」的錯誤。

這是我的方法,使用service命令,而不是檢查一個init腳本:

- name: check for apache 
    shell: "service apache2 status" 
    register: _svc_apache 
    failed_when: > 
    _svc_apache.rc != 0 and ("unrecognized service" not in _svc_apache.stderr) 

- name: disable apache 
    service: name=apache2 state=stopped enabled=no 
    when: "_svc_apache.rc == 0" 
  • 檢查的「服務狀態」退出代碼並接受退出代碼0時輸出包含「無法識別的服務」
  • 如果退出代碼爲0,已安裝的服務(停止或運行)