Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible how to ignore unreachable hosts before ansible 2.7.x

Tags:

ssh

ansible

I'm using ansible to run a command against multiple servers at once. I want to ignore any hosts that fail because of the '"SSH Error: data could not be sent to remote host \"1.2.3.4\". Make sure this host can be reached over ssh"' error because some of the hosts in the list will be offline. How can I do this? Is there a default option in ansible to ignore offline hosts without failing the playbook? Is there an option to do this in a single ansible cli argument outside of a playbook?

Update: I am aware that the ignore_unreachable: true works for ansible 2.7 or greater, but I am working in an ansible 2.6.1 environment.

like image 551
Alex Cohen Avatar asked Mar 15 '19 18:03

Alex Cohen


2 Answers

I found a good solution here. You ping each host locally to see if you can connect and then run commands against the hosts that passed:

---
- 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
like image 136
Alex Cohen Avatar answered Sep 21 '22 02:09

Alex Cohen


With current version on Ansible (2.8) something like this is possible:

- 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"
like image 34
sorin Avatar answered Sep 23 '22 02:09

sorin