2017-10-09 29 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

相关问题