如果在Ansible中可以访问第一个主机,则跳过其他主机

时间:2020-03-02 07:56:45

标签: ansible ansible-inventory

我拥有的文件包含我使用以下方法制作的库存的IP地址

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

我们如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

Q:“如果192.168.0.1可以访问,则应跳过其余IP。”

A:让我们wait_for_connectionblock中的所有主机上,并将连接状态存储在变量reachable中。然后,使用变量reachable创建可访问主机组reachable,并使用组groups.reachable.0中的第一台主机进行新的播放。例如

- 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 }}"

答案 1 :(得分:0)

好吧,在清单中根据需要订购主机,设置gather_facts: yesrun_once: yes的任务,一切顺利:

---
- hosts: all
  gather_facts: yes
  tasks:
  - debug:
      var: ansible_hostname
    run_once: yes

在一组主机上运行此剧本,并且列表中的前几台电源关闭,您将看到任务仅在响应的第一台主机上运行。

另一个选项类似于弗拉基米尔(Vladimir)建议的选项,但是使用了gather_facts的(缺乏)结果:

---
- hosts: all
  gather_facts: yes
  tasks:
  - set_fact:
      first_good_host: "{{ ansible_play_hosts | map('extract', hostvars) | list | json_query(query) | first }}"
    run_once: yes
    delegate_to: localhost
    vars:
      query: "[?ansible_facts!=''].inventory_hostname"

  - debug:
      var: first_good_host
    delegate_to: localhost

  - add_host:
      name: '{{ first_good_host }}'
      groups: 'reachable'
    run_once: yes

- hosts: reachable
  gather_facts: yes
  tasks:
  - debug:
      msg: "{{ inventory_hostname }}"

祝你好运!

相关问题