1

Using Ansible how to wait or recover when SSH service restarted? I have an ansible playbook that does a few changes to SSH configuration, but of course Ansible loses the SSH connection when ssh is restarted. I am using the built in ansible module to do the service restart.

I can trigger a reboot and wait, but that seems over kill when I just need ansible to wait a bit for the service to complete its restart, anyone have a way to solve this?

1 Answer 1

0

Just add a new task of wait_for module after ssh service restart task. Here is the reference from the official Ansible documentation.

# Do not assume the inventory_hostname is resolvable and delay 10 seconds at start
- name: Wait 300 seconds for port 22 to become open and contain "OpenSSH"
  ansible.builtin.wait_for:
    port: 22
    host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
    search_regex: OpenSSH
    delay: 10
  connection: local

In the default Ansible example, delay is 10s, but I've also added timeout to 300s in my example (below) so it will retry at every 10s, and it will fail after 300s if it is not able to connect to port 22 on your inventory hosts. Feel free to modify it according to your need.

Here is a sample play for your task. I've tested this before providing you the solution. It consists of three tasks. The first one is restart ssh daemon. Second task will wait for 300s with retry at every 10s. And if the connection is success, it will continue with next task, which I've tested with ping module.

---
- name: Reload service ssh, in all cases
  hosts: yourinventoryname
  become: true
  tasks:
    - name: Reload SSH service
      ansible.builtin.systemd:
        name: sshd
        state: restarted

- name: Wait for SSH service to be available
  hosts: all
  gather_facts: false
  tasks:
    - name: Wait for port 22 to become open and contain "OpenSSH"
      ansible.builtin.wait_for:
        port: 22
        host: '{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}'
        search_regex: OpenSSH
        delay: 10
        timeout: 300
      connection: local

- name: Test SSH connection
  gather_facts: false
  hosts: yourinventoryname
  tasks:
    - name: Ping hosts
      ansible.builtin.ping:
1
  • Thank you... testing now. I believe this should work, just crossing Ts and dotting I's. Commented Mar 20 at 15:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .