You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Ansible将Windows主机脚本结果保存至控制节点文件?

将Windows设备信息保存到Ansible控制节点文件的方法

你已经通过win_powershell模块获取了Windows设备的信息并注册到result变量,只需在playbook中添加一个控制节点本地执行的任务,就能把结果保存到控制节点的文件中。

修改后的完整Playbook

- name: firsttest
  hosts: win
  tasks:
   - name: Ping my Windows vm
     win_ping:

   - name: Run basic PowerShell script
     ansible.windows.win_powershell:
       script: |
         $hostname = hostname
         $domain = Get-NetFirewallProfile -Name Domain | Select-Object -ExpandProperty Enabled | Out-String
         $private = Get-NetFirewallProfile -Name Private | Select-Object -ExpandProperty Enabled | Out-String
         $public = Get-NetFirewallProfile -Name Public | Select-Object -ExpandProperty Enabled | Out-String
         $ipaddress = Get-NetIPAddress -AddressFamily IPv4 | Select-Object -ExpandProperty IPAddress | Out-String

         $myObject = [PSCustomObject]@{
          "Hostname" = $hostname
          "IPAdress" = $ipaddress
          "Domain" = $domain
          "Private" = $private
          "Public" = $public
         }
         $Ansible.Result = $myObject
     register: result

   - name: Show PS_output
     debug:
       var: result

   # 新增:将结果保存到控制节点的JSON文件
   - name: 保存设备信息到控制节点JSON文件
     local_action:
       module: copy
       content: "{{ result.output | to_nice_json }}"
       dest: "./windows_device_info_{{ inventory_hostname }}.json"

   # 可选:保存为格式化的文本文件(更易读)
   - name: 保存设备信息到控制节点文本文件
     local_action:
       module: copy
       content: |
         主机名: {{ result.output.Hostname }}
         IP地址: {{ result.output.IPAdress | trim }}
         Domain防火墙状态: {{ result.output.Domain | trim }}
         Private防火墙状态: {{ result.output.Private | trim }}
         Public防火墙状态: {{ result.output.Public | trim }}
       dest: "./windows_device_info_{{ inventory_hostname }}.txt"

关键说明

  1. local_action:指定任务在控制节点本地执行,而非目标Windows节点,文件会直接生成在控制节点上。
  2. result.output:对应你在PowerShell脚本中存入$Ansible.Result的自定义对象,是任务返回的核心数据。
  3. to_nice_json过滤器:将对象格式化为缩进清晰的JSON格式,方便后续解析或查看;偏好YAML格式可替换为to_nice_yaml。
  4. inventory_hostname变量:自动使用目标主机的inventory名称作为文件名后缀,避免多主机执行时文件被覆盖。
  5. trim过滤器:去除PowerShell中Out-String生成的多余换行和空白字符,让文本内容更整洁。

执行playbook后,控制节点当前目录下会生成对应主机的.json和.txt文件,包含你需要的设备信息。

内容的提问来源于stack exchange,提问作者Onyx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:51:53