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: