【发布时间】:2020-11-27 03:04:05
【问题描述】:
如果 systemd 服务正在远程主机上运行和/或启用,我正在尝试停止和/或禁用它。
tasks/main.yml的内容:
---
- name: Populate service facts
service_facts:
- name: Display selected service
debug:
var: ansible_facts.services[serviceToDisplay]
loop: "{{ disable_services }}"
loop_control:
loop_var: serviceToDisplay
vars:
disable_services:
- cups.service
- cups
- name: Stop and Disable service if it is running or enabled
systemd:
name: cups.service
enabled: false
state: stopped
when:
- "serviceToDisable is defined"
- "serviceToDisable.status == 'enabled'"
loop: "{{ disable_services }}"
loop_control:
loop_var: serviceToDisable
vars:
disable_services:
- cups.service
- cups
become: true
...
结果:
PLAY [configServerGroup] *************************************************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************************************
ok: [radicale.jlhimpel.net]
TASK [example : Populate service facts] **********************************************************************************************************************
ok: [radicale.jlhimpel.net]
TASK [example : Display selected service] ********************************************************************************************************************
ok: [radicale.jlhimpel.net] => (item=cups.service) => {
"ansible_facts.services[serviceToDisplay]": {
"name": "cups.service",
"source": "systemd",
"state": "running",
"status": "enabled"
},
"ansible_loop_var": "serviceToDisplay",
"serviceToDisplay": "cups.service"
}
ok: [radicale.jlhimpel.net] => (item=cups) => {
"ansible_facts.services[serviceToDisplay]": {
"name": "cups",
"source": "sysv",
"state": "running"
},
"ansible_loop_var": "serviceToDisplay",
"serviceToDisplay": "cups"
}
TASK [example : Stop and Disable service if it is running or enabled] ****************************************************************************************
fatal: [radicale.jlhimpel.net]: FAILED! => {"msg": "The conditional check 'serviceToDisable.status == 'enabled'' failed. The error was: error while evaluating conditional (serviceToDisable.status == 'enabled'): 'str object' has no attribute 'status'\n\nThe error appears to be in '/home/jwhimpel/ansible/roles/example/tasks/main.yml': line 16, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Stop and Disable service if it is running or enabled\n ^ here\n"}
PLAY RECAP ***************************************************************************************************************************************************
radicale.jlhimpel.net : ok=3 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
Ansible 版本:Fedora 上的 2.9.14-1.fc32
我应该如何检查状态 == 启用或状态 == 运行?
注意:服务可能不存在于 ansible_facts.service 中。它也可以选择不运行和/或不启用。我正在尝试使任务具有幂等性。
谢谢
【问题讨论】:
标签: ansible ansible-facts