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

如何查看Ansible启动脚本的输出及Playbook中脚本的$output变量

Ansible脚本输出及变量查看方案

1. 查看通过Ansible启动的脚本的输出

有两种常用方式可以查看脚本输出:

方式一:直接查看Playbook运行输出

运行Playbook时,ansible.windows.win_powershell模块默认会把脚本内的输出(比如echo/Write-Output的内容)返回至终端。直接执行命令:

ansible-playbook playbook.yaml

在终端日志里就能看到脚本的输出内容。

方式二:捕获输出并显式打印

如果需要更清晰地展示输出,或者后续要用到输出内容,可以用register关键字捕获任务结果,再通过debug模块打印:
修改你的Playbook如下:

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

   - name: Run basic PowerShell script
     ansible.windows.win_powershell:
       script: |
         $output = "Hello World"
         echo $output
     register: script_run_result

   - name: 打印脚本输出
     ansible.builtin.debug:
       var: script_run_result.output

运行Playbook后,debug任务会在Shell中清晰展示脚本的输出列表。

2. 在Shell中显示脚本里的$output变量

要让PowerShell脚本内的$output变量值在Shell中显示,核心是让Ansible捕获到这个变量的值,再通过debug模块输出:

方法一:脚本内输出变量,Ansible捕获后打印

修改Playbook,让脚本输出$output,再用register捕获并打印:

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

   - name: Run PowerShell script and capture $output
     ansible.windows.win_powershell:
       script: |
         $output = "Hello World"
         Write-Output $output  # 输出变量,让模块捕获
     register: output_result

   - name: 在Shell中显示$output的值
     ansible.builtin.debug:
       msg: "脚本中的$output变量值为: {{ output_result.output[0] }}"

运行Playbook后,Shell中会显示类似ok: [win] => { "msg": "脚本中的$output变量值为: Hello World" }的内容。

方法二:利用PowerShell默认输出特性

PowerShell会把脚本最后一行的表达式结果自动输出,因此可以直接把$output放在脚本最后一行,无需额外的Write-Output:

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

   - name: Run script and get $output
     ansible.windows.win_powershell:
       script: |
         $output = "Hello World"
         $output  # 最后一行自动输出变量
     register: var_result

   - name: 显示$output变量值
     ansible.builtin.debug:
       var: var_result.output[0]

这种方式同样能在Shell中打印出$output的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:25:33