问题描述
我如何从 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
期望结果:“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