我想检查终端主机中是否存在服务。
所以,我刚刚做了如下的剧本。
---
- 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
然后,我尝试将此playbook执行到我的主机,该主机已经运行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模块。
答案 0 :(得分:3)
您为什么使用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