2017-10-09 31 views
0

我想檢查終端主機中存在的服務。如何檢查Ansible存在的任何服務?

所以,我只是做了如下的劇本。

--- 

- hosts: '{{ host }}' 
    become: yes 
    vars: 
    servicename: 
    tasks: 

    - name: Check if Service Exists 
    stat: 'path=/etc/init.d/{{ servicename }}' 
    register: servicestatus 
    with_items: '{{ servicename }}' 

    - name: Show service service status 
    debug: 
     msg: '{{ servicename }} is exists.' 
    with_items: '{{ servicename }}' 
    when: servicestatus.stat.exists 

於是,我試圖執行這個劇本到我的主機正在運行的Nginx已經如下。

ansible-playbook cheknginxservice.yml -i /etc/ansible/hosts -e 'host=hostname' -e 'servicename=nginx' 

我得到了這樣的錯誤。

FAILED! => {"failed": true, "msg": "The conditional check 'servicestatus.stat.exists' failed. The error was: error while evaluating conditional (servicestatus.stat.exists): 'dict object' has no attribute 'stat'\n\nThe error appears to have been in '/home/centos/cheknginxservice.yml': line 13, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n with_items: '{{ servicename }}'\n - name: Show service servicestatus\n ^here\n"} 
     to retry, use: --limit @/home/centos/cheknginxservice.retry 

所以,我認爲問題是關於使用條件涉及的stat模塊。

回答

2

爲什麼使用with_items?您計劃通過多項服務?這很重要,因爲如果您使用with_items,結果將成爲列表。只要刪除with_items,它會工作。如果您想通過多項服務,則必須通過with_items循環並使用item而不是servicename

- name: Check if Service Exists 
    stat: 'path=/etc/init.d/{{ servicename }}' 
    register: servicestatus 

    - name: Show service service status 
    debug: 
     msg: '{{ servicename }} is exists.' 
    when: servicestatus.stat.exists 

Ansible中沒有本地方式來檢查服務的狀態。您可以使用shell模塊。通知我使用了sudo。你的情況可能會有所不同。

- name: check for service status 
    shell: sudo service {{ servicename }} status 
    ignore_errors: true 
    register: servicestatus 

    - name: Show service service status 
    debug: 
     msg: '{{ servicename }} exists.' 
    when: servicestatus.rc | int == 0 
+0

謝謝你,先生。我只是不知道「with_items」究竟意味着什麼。所以,我在以前的工作中多次使用它。 –

+0

我只是嘗試通過在主機終端中使用命令「apt-get remove nginx」來刪除nginx服務。但是/etc/init.d中的文件「nginx」仍然存在。所以,我的任務仍然有輸出存在。是否有另一種方式通過Ansible來檢查服務是否存在?謝謝。 –

+0

@TutchaponSirisaeng看到我的更新回答。 – helloV

相關問題