问题描述
我的文件包含 Ip 地址,我使用以下方法为我的任务制作此清单
I am having file consists of Ip address I using below method to to make this inventory for my tasks
ips.text
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
main.yml
- name: Add Instance IP Addresses to temporary inventory groups
shell: cat ~/ips.text
register: serverlist
- debug: msg={{ serverlist.stdout_lines }}
- name: Add Instance IP Addresses to temporary inventory groups
add_host
groups: working_hosts
hostname: "{{item}}"
with_items: "{{ serverlist.stdout_lines }}"
- hosts: working_hosts
become: yes
现在我想让它像如果 192.168.0.1 是可访问的,那么它应该跳过该文件中的其余 ips,如果 192.168.0.1 是不可访问的,那么只有转到下一个 192.168.0.2.
Now I want to make it like if 192.168.0.1 is reachable then it should skip rest of the ips from that file and if 192.168.0.1 is unreachable then only goes to next 192.168.0.2.
我们如何才能做到这一点?
How can we achieve this?
推荐答案
A:让我们wait_for_connection
在 block
并将连接状态存储在变量 reachable
中.然后使用变量 reachable
创建可到达主机组 reachable
并使用组 groups.reachable.0
中的第一个主机运行新游戏.例如
A: Let's wait_for_connection
on all hosts in the block
and store the connection status in the variable reachable
. Then use the variable reachable
to create the group of reachable hosts reachable
and run new play with the first host from the group groups.reachable.0
. For example
- name: Test reachable hosts
hosts: working_hosts
gather_facts: false
vars:
connection_timeout: "10"
tasks:
- block:
- wait_for_connection:
timeout: "{{ connection_timeout }}"
rescue:
- set_fact:
reachable: false
- meta: clear_host_errors
- meta: end_host
- set_fact:
reachable: true
- add_host:
name: '{{ item }}'
groups: 'reachable'
loop: "{{ hostvars|dict2items|json_query('[?value.reachable].key') }}"
run_once: true
- hosts: "{{ groups.reachable.0 }}"
tasks:
- debug:
msg: "{{ inventory_hostname }}"
这篇关于如果在 Ansible 中可以访问第一个主机,则跳过其他主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!