Ansible启停ssh服务异常:执行停止后sshd仍运行
Let's break down why your SSH service isn't actually stopping when you run that playbook, and fix it step by step.
First: Verify the Correct Service Name
Different Linux distros use different names for the SSH service:
- Debian/Ubuntu:
ssh - RHEL/CentOS/Fedora:
sshd
Run this command on your localhost to confirm the exact name:
systemctl list-unit-files | grep ssh
If it shows sshd.service instead of ssh.service, that's your first fix—update the name field in your Ansible task.
Why Your Original Playbook Fails
Using with_items to run stop then start back-to-back is the main culprit here. Ansible sends the stop command and immediately sends the start command without waiting for the service to fully shut down. The system might still be processing the stop request when the start command hits, so it looks like the service never stopped.
Fixed Playbook: Separate Tasks with Validation
Instead of looping, split the tasks and add a check to ensure the service is actually stopped before starting it again. Here's a reliable version:
- hosts: localhost become: yes tasks: - name: Stop SSH service service: name: ssh # Replace with sshd if needed state: stopped - name: Wait for SSH service to fully stop command: service ssh status register: ssh_stop_status failed_when: "'active (running)' in ssh_stop_status.stdout" retries: 3 delay: 2 until: ssh_stop_status is succeeded - name: Start SSH service service: name: ssh # Match the name above state: started
Alternative: Use the systemd Module (More Reliable for Modern Systems)
For systems using systemd (most modern distros), the systemd module offers better control and feedback than the generic service module. Try this:
- hosts: localhost become: yes tasks: - name: Stop SSH service systemd: name: ssh # Or sshd state: stopped daemon_reload: yes # Optional, but useful if configs changed - name: Verify SSH service is stopped systemd: name: ssh state: stopped register: ssh_systemd_status retries: 3 delay: 2 until: ssh_systemd_status.status.ActiveState == "inactive" - name: Start SSH service systemd: name: ssh state: started
Edge Case: Check if SSH is Configured to Auto-Restart
In some cases, the SSH service might be set to automatically restart if it stops. Check this with:
systemctl show ssh.service | grep Restart
If you see Restart=always, you'll need to temporarily override this or edit the service file before stopping it. But this is rare for default SSH configurations.
内容的提问来源于stack exchange,提问作者VIVEK GAUR

