微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ansible 在来自 dict 中的列表时使用 conditionnal 显示正确的结果

如何解决Ansible 在来自 dict 中的列表时使用 conditionnal 显示正确的结果

我如何从 with_items 中的 ping 中选择正确的“IP”

Ansible main.yml 代码

IP_server:
  - north:
      192.168.1.1
      192.168.1.2

- name: Ping command
  shell:
    cmd: "ping -c -w 2 {{ item }}"
  register: "server_ok"
  ignore_errors: yes
  with_items:
    - "{{ IP_server.north }}"
  loop_control:
   loop_var: "correct_server"

- name: "Selected IP"
  debug:
    msg: "{{ IP_server.north.msg }}"
  when: IP_server.north.msg.0.rc == 0

结果:始终显示一个 IP:192.168.1.1


期望结果:“when”中的条件“....rc==0”选择的正确IP。


非常感谢!

解决方法

例如

- hosts: localhost
  vars:
    IP_server:
      - 10.1.0.61
      - 10.1.0.62
      - 10.1.0.99
  tasks:
    - command: "ping -c 1 {{ item }}"
      register: server_ok
      ignore_errors: yes
      loop: "{{ IP_server }}"
    - debug:
        msg: "{{ server_ok.results|
                 selectattr('rc','eq',0)|
                 map(attribute='item')|
                 list }}"

给予

PLAY [localhost] ****************************************************************

TASK [command] ******************************************************************
changed: [localhost] => (item=10.1.0.61)
changed: [localhost] => (item=10.1.0.62)
failed: [localhost] (item=10.1.0.99) => changed=true 
  ansible_loop_var: item
  cmd:
  - ping
  - -c
  - '1'
  - 10.1.0.99
  delta: '0:00:03.078826'
  end: '2021-02-25 10:50:17.192211'
  item: 10.1.0.99
  msg: non-zero return code
  rc: 1
  start: '2021-02-25 10:50:14.113385'
  stderr: ''
  stderr_lines: <omitted>
  stdout: |-
    PING 10.1.0.99 (10.1.0.99) 56(84) bytes of data.
    From 10.1.0.27 icmp_seq=1 Destination Host Unreachable
  
    --- 10.1.0.99 ping statistics ---
    1 packets transmitted,0 received,+1 errors,100% packet loss,time 0ms
  stdout_lines: <omitted>
...ignoring

TASK [debug] ********************************************************************
ok: [localhost] => 
  msg:
  - 10.1.0.61
  - 10.1.0.62

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。