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

如何将Ansible输出传递给Python脚本?实现script2获取script1输出

如何在Ansible中将script1的输出传递给script2?

你可以通过以下几种常见方式实现:

1. 命令行参数传递

直接将script1的输出作为命令行参数传给script2,Ansible中通过register变量的stdout字段捕获脚本输出:

- name: "执行script1并捕获输出"
  command: /home/test/script1.py
  register: script1_output

- name: "传递script1输出给script2"
  command: /home/test/script2.py "{{ script1_output.stdout | quote }}"

在script2.py中,可通过sys.argv[1]读取该参数(需导入sys模块)。使用quote过滤器能避免输出中的空格、特殊字符导致命令解析错误。

2. 环境变量传递

利用Ansible的environment参数为script2设置环境变量,将script1的输出存入环境变量:

- name: "执行script1并捕获输出"
  command: /home/test/script1.py
  register: script1_output

- name: "通过环境变量传递输出给script2"
  command: /home/test/script2.py
  environment:
    SCRIPT1_RESULT: "{{ script1_output.stdout }}"

在script2.py中,通过os.environ['SCRIPT1_RESULT']读取环境变量内容(需导入os模块)。这种方式适合输出内容较长或包含特殊字符的场景。

3. 临时文件传递

将script1的输出写入临时文件,让script2读取该文件内容:

- name: "执行script1并捕获输出"
  command: /home/test/script1.py
  register: script1_output

- name: "将script1输出写入临时文件"
  copy:
    content: "{{ script1_output.stdout }}"
    dest: /tmp/script1_result.txt
    mode: '0644'

- name: "让script2读取临时文件"
  command: /home/test/script2.py /tmp/script1_result.txt

在script2.py中,通过打开并读取指定路径的文件来获取内容。这种方式适合输出非常大的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:05:33