使用Ansible将多台Windows主机的主机名和序列号写入本地文件遇错求助
问题分析
错误核心是执行local_action时,Ansible错误地将localhost当作Windows主机处理,尝试运行PowerShell命令(而主控节点是Linux系统,不存在PowerShell),导致命令未找到(退出码127),进而无法创建临时目录。同时原Playbook使用copy模块会覆盖文件,多台主机执行后只会保留最后一台的信息。
解决方案
1. 修正本地执行的连接逻辑
改用delegate_to: localhost明确指定在本地执行,并确保localhost使用Linux兼容的连接方式,避免复用Windows的连接插件。
2. 改用追加模式写入文件
替换copy模块为lineinfile模块,实现多台主机信息的追加写入,而非覆盖。
3. 优化序列号收集命令
原命令返回带属性结构的冗余输出,改用-ExpandProperty参数直接提取序列号字符串,保证输出格式简洁。
修正后的Playbook
--- - name: Gather hostname and serial number hosts: Test gather_facts: no tasks: - name: Get hostname win_command: hostname register: hostname_output - name: Get serial number win_command: powershell.exe -Command "Get-WmiObject win32_bios | Select-Object -ExpandProperty Serialnumber" register: serial_number_output - name: Append output to local file delegate_to: localhost lineinfile: path: /opt/ansible/hosts.txt line: "{{ hostname_output.stdout }},{{ serial_number_output.stdout }}" create: yes # 文件不存在时自动创建
额外配置说明
如果你的Ansible inventory中localhost被错误配置为使用winrm连接,需要在inventory文件中明确指定localhost的连接方式:
[localhost] localhost ansible_connection=local
同时确保主控节点对/opt/ansible/目录有写入权限,可执行以下命令调整:
sudo chown -R $USER /opt/ansible
内容的提问来源于stack exchange,提问作者max
相关产品推荐
相关产品推荐

