下面是一个使用Ansible停止和禁用服务的代码示例:
- name: Stop and disable service if it exists
hosts: all
vars:
service_name: myservice
tasks:
- name: Check if service is running
command: systemctl is-active {{ service_name }}
register: service_status
ignore_errors: true
- name: Stop and disable service if it is running
systemd:
name: "{{ service_name }}"
state: stopped
enabled: false
when: service_status.stdout == "active"
以上代码使用systemd模块来停止和禁用服务。首先,使用command
模块来检查服务是否正在运行,并将结果存储在service_status
变量中。然后,使用systemd
模块来停止和禁用服务,仅当服务状态为"active"时才执行此操作。
请注意,这个示例假设你的目标主机使用systemd作为服务管理器。如果你的系统使用其他服务管理器(如init.d),你需要相应地修改代码。