Ansible - 从机器变量启动到循环中的命令的返回代码



我现在对我的 Ansible 任务有一些严重的挣扎,我想我需要一点帮助......

背景 : 我的 Ansible 清单中有多个服务器,我希望能够启动一个 playbook 来检查服务器上运行的服务的状态,而无需为每个服务执行特定任务。 我已经将机器变量配置为如下所示(例如(:

services:
apache-custom:
cmd: ps aux | grep /bin/custom-httpd | ps -efl | grep custom-owner | grep -v grep
return_code: 0
restart: echo restart
mysqld:
cmd: 0

目前剧本如下:

- hosts: all
tasks:
- name: Check native services status
service:
name: "{{ item.key }}"
state: started
with_dict: "{{ services }}"
when: item.value.cmd == 0
- name: Check others services
shell: "{{ item.value.cmd }}"
register: result
with_dict: "{{ services }}"
failed_when: result.rc != item.value.return_code
when: item.value.cmd != 0 and item.value.cmd != ''
ignore_errors: yes

对于使用"cmd: 0"定义的服务,第一个任务将检查服务的状态,如果未启动,则启动它。 但是对于某些自定义服务,"服务"模块无法帮助我,因此我需要启动命令才能知道服务是否已启动。 在这种情况下,第二个任务可以工作,但我无法获取该任务的返回代码以启动将要启动服务的任务。

我尝试添加此任务:

- name: test
debug:
msg: ({{ item.item.key }}) failed
when: item.rc != 0
with_items: "{{ result.results }}"

但是Ansible抱怨"dict"值没有任何返回代码。

我尝试调试,但我不明白发生了什么。 例如,当我想查看任务的全局结果的内容时,我添加以下内容:

- name: test2
debug:
msg: "{{ item }}"
with_items: "{{ result.results }}"

它给了我以下输出(包含我正在寻找的返回代码(:

[...]
"failed_when_result": false,
"invocation": {
"module_args": {
"_raw_params": "ps aux | grep /bin/custom-httpd | ps -efl | grep custom_owner | grep -v grep",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"warn": true
}
},
"item": {
"key": "apache-custom",
"value": {
"cmd": "ps aux | grep /bin/custom_httpd | ps -efl | grep custom-owner | grep -v grep",
"restart": "echo restart",
"return_code": 0
}
},
"rc": 0, <====== here is the return code
"start": "2018-07-09 15:44:24.859555",
"stderr": "",
"stderr_lines": [],
[...]

但是我无法到达它...

知道怎么做吗? 还是我做错了什么?

谢谢

"为了能够启动检查服务器上运行的服务状态的剧本",您可能需要考虑模块service_facts

- name: 'Test service_facts'
hosts: localhost
connection: local
tasks:
- name: populate service facts
service_facts:
- debug:
var: ansible_facts.services

最新更新