data-structures - Ansible在dict中的列表中显示正确的结果和条件
问题描述
我如何在 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
推荐阅读
- c - 为什么在这种情况下linux系统调用“capset”失败?
- .net - 找不到工具包参考(System.Windows.Controls.Input.Toolkit & System.Windows.Controls.Toolkit)
- reactjs - webpack dev不断抱怨组件无效
- angular - 为 Angular5 添加组件时出错
- pandas - 每次遇到值时切片数据帧
- bash - jq解析中如何使用环境变量参数
- python - 通过给定的折扣策略获取折扣列表并续订月份
- ruby - 如何根据编码字符串Ruby返回解码字符串
- android - 无法在 Android 的 Twitter 上发布图片
- ios - iOS IAP 沙盒 - 是否可以在不同的捆绑包 ID 上进行测试