Ansible-命令返回码从机器变量启动进入循环

时间:2018-07-09 14:04:37

标签: ansible

我现在在完成Ansible任务时有些挣扎,我认为我需要一点帮助...

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

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": [],
    [...]

但是我无法达到...

任何想法该怎么做? 还是我做错了什么?

谢谢

1 个答案:

答案 0 :(得分:0)

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

logger.log(ioHelper.printTest())