打印调试中来自stdout的已注册变量的Ansible循环

时间:2019-10-25 17:54:40

标签: ansible ansible-2.x ansible-facts

enter image description here团队

我的任务是从json_query输出stdoud_lines中提取主机。

然后,我遍历每个主机名,并在每个主机上执行ssh连接以及shell命令。

最后,要列出每个主机的输出,我正在调试每个主机的结果。[i]。有没有一种方法可以循环显示结果[i],其中i =具有主机条目的动态变量?我想循环调试。有任何提示吗?

任务:“ ssh并运行shell命令并手动列出每个主机结果”

      - name: "RAID mount check for fscache on GPU Nodes"
        shell: ssh -F {{ ssh_cfg_path.stdout }} {{ item.node_name }}.{{ ssh_host }} "df -kh /raid/"
        ignore_errors: no
        register: raid_info
        failed_when: raid_info.rc != 0
        with_items: "{{ gpu_nodes }}"

      - name: raid_info result
        debug:
          var: raid_info

      - name: raid_info results0_stdout_lines
        debug:
          var: raid_info.results[0].stdout_lines
      - name: raid_info results1_stdout_lines
        debug:
          var: raid_info.results[1].stdout_lines

输出:


    TASK [team-services-pre-install-checks : raid_info results0_stdout_lines] ****
    Friday 25 October 2019  17:03:07 +0000 (0:00:00.041)       0:00:25.292 ******** 
    ok: [localhost] => {
        "raid_info.results[0].stdout_lines": [
            "Filesystem      Size  Used Avail Use% Mounted on", 
            "/dev/sdb1       7.0T  175G  6.5T   3% /raid"
        ]
    }

    TASK [team-services-pre-install-checks : raid_info results1_stdout_lines] ****
    Friday 25 October 2019  17:03:07 +0000 (0:00:00.040)       0:00:25.333 ******** 
    ok: [localhost] => {
        "raid_info.results[1].stdout_lines": [
            "Filesystem      Size  Used Avail Use% Mounted on", 
            "/dev/sdb1       7.0T  176G  6.5T   3% /raid"
        ]
    }

以下方法无效或未列出任何输出。


      - name: raid_info results loop over all hosts output/result
        debug:
          var: raid_info.results[{{ item }}].stdout_lines
        with_items: "{{ raid_info }}"

我认为我需要使用hostvars,但我是新手,不确定如何设置。

1 个答案:

答案 0 :(得分:1)

您似乎已经很接近了,只需要在这里稍微调整一下逻辑即可。 with_items将遍历提供的所有内容的列表,因此,如果您将更多的变量结构移入with_items列表中,如下所示:

- name: raid_info results loop over all hosts output/result
  debug:
    msg: "{{ item.stdout }}"
  with_items: "{{ raid_info.results }}"
  loop_control: 
    label: "{{ item.item.node_name }}"

这将遍历索引列表,该列表是上一个任务的with_items创建的结果。