Ansible如何忽略无法访问的主机Ansible 2.6.1

时间:2019-03-15 18:43:52

标签: ssh ansible

我正在使用ansible一次对多个服务器运行命令。我想忽略由于“ "SSH Error: data could not be sent to remote host \"1.2.3.4\". Make sure this host can be reached over ssh"”错误而失败的所有主机,因为列表中的某些主机将脱机。我怎样才能做到这一点?难道有一个默认选项可以忽略离线主机而不使剧本失败吗?可以在剧本之外的单个ansible cli参数中执行此操作吗?

更新:我知道ignore_unreachable: true适用于ansible 2.7或更高版本,但是我正在ansible 2.6.1环境中工作。

2 个答案:

答案 0 :(得分:3)

我找到了一个很好的解决方案here。您在本地ping每个主机以查看是否可以连接,然后对通过的主机运行命令:

---
- hosts: all
  connection: local
  gather_facts: no
  tasks:
    - block:
        - name: determine hosts that are up
          wait_for_connection:
            timeout: 5
          vars:
            ansible_connection: ssh
        - name: add devices with connectivity to the "running_hosts" group
          group_by:
            key: "running_hosts"
      rescue:
        - debug: msg="cannot connect to {{inventory_hostname}}"

- hosts: running_hosts
  gather_facts: no
  tasks:
  - command: date

答案 1 :(得分:1)

使用Ansible(2.8)的当前版本,可能会发生以下情况:

- name: identify reachable hosts
  hosts: all
  gather_facts: false
  ignore_errors: true
  ignore_unreachable: true
  tasks:
    - block:
        - name: this does nothing
          shell: exit 1
          register: result
      always:
        - add_host:
            name: "{{ inventory_hostname }}"
            group: reachable

- name: Converge
  hosts: reachable
  gather_facts: false
  tasks:
    - debug: msg="{{ inventory_hostname }} is reachable"