如何通过Ansible检查是否存在任何服务?
我想检查终端主机中是否存在该服务 所以,我只是做了下面的剧本如何通过Ansible检查是否存在任何服务?,ansible,conditional,ansible-2.x,Ansible,Conditional,Ansible 2.x,我想检查终端主机中是否存在该服务 所以,我只是做了下面的剧本 --- - hosts: '{{ host }}' become: yes vars: servicename: tasks: - name: Check if Service Exists stat: 'path=/etc/init.d/{{ servicename }}' register: servicestatus with_items: '{{ servicename }}
---
- 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
ansible-playbook cheknginxservice.yml -i /etc/ansible/hosts -e 'host=hostname' -e 'servicename=nginx'
然后,我尝试对运行Nginx的主机执行这个剧本,如下所示
---
- 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
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模块。为什么要对项目使用
?你打算通过多项服务吗?这很重要,因为如果将与\u项一起使用,结果将是一个列表。只需删除带有\u项的,它就会工作。如果您想传递多个服务,那么您必须使用_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
非常感谢,先生。我只是不知道“带物品”到底是什么意思。因此,我在以前的工作中多次使用它,我只是尝试在主机终端中使用命令“apt get remove nginx”删除nginx服务。但是/etc/init.d中的文件“nginx”仍然存在。因此,我的任务仍然得到了现有的输出。是否有其他方法通过Ansible检查服务是否存在?谢谢