我有一个Ansible手册,用于将Java应用程序部署为init.d守护程序。
作为Ansible和Linux的初学者,我很难根据主机的状态有条件地在主机上执行任务。
即我有一些主机已经提供服务,并且在我做任何其他事情之前我想要停止它。然后可能会有新主机,但尚未提供服务。所以我不能简单地使用service: name={{service_name}} state=stopped
,因为这会在新主机上失败。
我如何才能实现这一目标?这是我到目前为止所做的:
- 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
答案 0 :(得分:28)
当然我也可以检查/etc/init.d中是否存在包装脚本。所以这就是我最终的结果:
- 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
答案 1 :(得分:14)
请参阅service_facts
模块,这是Ansible 2.5的新功能。
- name: Populate service facts
service_facts:
- debug:
msg: Docker installed!
when: "'docker' in services"
答案 2 :(得分:7)
如果"服务"那将是很好的。模块可以处理"无法识别的服务"错误。
这是我的方法,使用service
命令而不是检查init脚本:
- name: check for apache
shell: "service apache2 status"
register: _svc_apache
failed_when: >
_svc_apache.rc != 0 and ("unrecognized service" not in _svc_apache.stderr)
- name: disable apache
service: name=apache2 state=stopped enabled=no
when: "_svc_apache.rc == 0"
答案 3 :(得分:6)
我修改@ Florian的答案只使用service
命令的返回码(这适用于Mint 18.2)
- name: Check if Logstash service exist
shell: service logstash status
register: logstash_status
failed_when: not(logstash_status.rc == 3 or logstash_status.rc == 0)
- name: Check if Logstash service exist
service:
name: logstash
state: stopped
when: logstash_status.rc == 0
答案 4 :(得分:1)
systemd(from Jakuje)的另一种方法:
- name: Check if cups-browsed service exists
command: systemctl cat cups-browsed
check_mode: no
register: cups_browsed_exists
changed_when: False
failed_when: cups_browsed_exists.rc not in [0, 1]
- name: Stop cups-browsed service
systemd:
name: cups-browsed
state: stopped
when: cups_browsed_exists.rc == 0
答案 5 :(得分:0)
我的几分钱。与上述相同,但适用于kubernetes
检查kublete服务是否正在运行
- name: "Obtain state of kublet service"
command: systemctl status kubelet.service
register: kubelet_status
failed_when: kubelet_status.rc > 3
如果kublet服务未运行,则显示调试消息
- debug:
msg: "{{ kubelet_status.stdout }}"
when: "'running' not in kubelet_status.stdout"
答案 6 :(得分:0)
这种仅使用服务模块的方式对我们有用:
- name: Disable *service_name*
service:
name: *service_name*
enabled: no
state: stopped
register: service_command_output
failed_when: >
service_command_output|failed
and 'unrecognized service' not in service_command_output.msg
and 'Could not find the requested service' not in service_command_output.msg