使用Ansible进行MySQL服务器补丁更新时,委托后台服务器执行任务出现SSH连接异常问题排查
Let's break down the problems in your playbook and fix them step by step:
First, here's the corrected playbook
--- - name: MySQL Server Patch Update with Pre-Tasks hosts: "{{ host }}" gather_facts: no serial: 1 tasks: - name: Stop all running services01 on QA background servers ansible.windows.win_powershell: script: | Stop-Service -DisplayName 'services01*' -Force -ErrorAction SilentlyContinue delegate_to: "{{ item }}" loop: "{{ groups['qa_bg_servers'] }}"
Key Issues & Fixes
Broken Playbook Structure
Your original code had two separate plays (each- name:block counts as a play), and the second play had nohostsdefined. On top of that, you usedbackground_serversas a delegate target—a variable that doesn't exist in your setup. We've moved the stop-service task into the main play'staskssection, and now directly reference your existingqa_bg_servershost group.Wrong Connection Method for Windows Hosts
The error shows Ansible trying to connect to your Windows servers via SSH, which won't work—Windows uses WinRM for Ansible management. You need to update your inventory file for theqa_bg_serversgroup to specify WinRM settings:[qa_bg_servers] 11.111.2.44 ansible_connection=winrm ansible_winrm_transport=ntlm ansible_winrm_server_cert_validation=ignore ansible_user=your_windows_username ansible_password=your_windows_passwordPro tip: Store sensitive credentials in an Ansible vault instead of plaintext for security.
Delegating to a Host Group
To run the task on all 3 servers inqa_bg_servers, we useloop: "{{ groups['qa_bg_servers'] }}"paired withdelegate_to: "{{ item }}". This ensures the stop-service command runs on every server in your target group one by one.Robust PowerShell Script
I added-Forceto ensure stubborn services get stopped, and-ErrorAction SilentlyContinueto avoid failures if someservices01instances aren't running (adjust this if you want to be notified of missing services instead).
Quick Validation Steps
- Test WinRM connectivity first: Run
ansible qa_bg_servers -m win_pingfrom your Ansible controller. If this succeeds, your WinRM setup is correct. - Verify your inventory has the correct IPs for
qa_bg_serversand that the controller can reach those Windows hosts on ports 5985 (HTTP) or 5986 (HTTPS).
内容的提问来源于stack exchange,提问作者shine12

