使用Ansible检查服务是否存在 [英] Check if service exists with Ansible
问题描述
我有一本Ansible手册,用于将Java应用程序部署为init.d守护程序.
I have an Ansible playbook for deploying a Java app as an init.d daemon.
作为Ansible和Linux的初学者,我无法根据主机的状态有条件地在主机上执行任务.
Being a beginner in both Ansible and Linux I'm having trouble to conditionally execute tasks on a host based on the host's status.
也就是说,我有一些主机已经存在该服务并且正在运行该服务器,然后再执行其他操作.然后可能会有新的主机,但还没有该服务.所以我不能简单地使用service: name={{service_name}} state=stopped
,因为这将在新主机上失败.
Namely I have some hosts having the service already present and running where I want to stop it before doing anything else. And then there might be new hosts, which don't have the service yet. So I can't simply use service: name={{service_name}} state=stopped
, because this will fail on new hosts.
我该如何实现?这是我到目前为止的内容:
How I can I achieve this? Here's what I have so far:
- 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
推荐答案
当然,我也可以只检查包装脚本在/etc/init.d中是否存在.所以这就是我最终得到的:
Of course I could also just check if the wrapper script exists in /etc/init.d. So this is what I ended up with:
- 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
这篇关于使用Ansible检查服务是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!