Ansible - Looping and Debug/Register

时间:2018-12-03 13:04:39

标签: ansible

I have the following task. However, it doesn't output the output for each ping that is produced, and I only get a 1 x output. When there should be x 5.

Task

  tasks:
    - name: "Check Connectivity (ping)"
      nxos_ping:
        provider: "{{ nxos_ssh }}"
        source: "{{ hostvars[inventory_hostname]['lo0_ipaddr'] }}"
        vrf: default
        dest: "192.168.1.{{item}}"
      with_sequence: start=1 end=5
      register: out

    - debug:
        msg:
         - "command: {{ out['results'][0]['commands'][0] }}"

Example

TASK [Check Connectivity (ping)] ***************************************************************************************************
ok: [spine-nxos-1] => (item=1)
ok: [spine-nxos-2] => (item=1)
ok: [spine-nxos-2] => (item=2)
ok: [spine-nxos-1] => (item=2)
ok: [spine-nxos-1] => (item=3)
ok: [spine-nxos-2] => (item=3)
ok: [spine-nxos-1] => (item=4)
ok: [spine-nxos-2] => (item=4)
ok: [spine-nxos-1] => (item=5)
ok: [spine-nxos-2] => (item=5)

TASK [debug] ***********************************************************************************************************************
ok: [spine-nxos-1] => {
    "msg": [
        "command: ping 192.168.1.1 count 5 source 192.168.1.1 vrf default"
    ]
}
ok: [spine-nxos-2] => {
    "msg": [
        "command: ping 192.168.1.1 count 5 source 192.168.1.2 vrf default"
    ]
}

1 个答案:

答案 0 :(得分:2)

您的代码工作正常,因为您仅打印出注册输出的第一个元素。如果要查看所有命令,则应将剧本的最后一行替换为:

- "command {{ out | json_query('results[*].commands[*]') }}"

或遍历与序列相对应的输出:

debug:
  msg:
    - "command {{ out.results[item|int].commands[0]}}"
with_sequence: start=0 end=2