使用 Ansible 检查服务是否存在 [英] Check if service exists with Ansible
问题描述
我有一个 Ansible playbook,用于将 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屋!