首页 > 解决方案 > 将 ansible stdout_lines 导入 python 文件

问题描述

我正在尝试将ansible output.stdout_lines 数组复制到 python 文件

- name: Fetch routing info
  hosts: Windows
  tasks:
    - win_command: route print
      register: output
    - debug: msg={{ output.stdout_lines }}
    - command: python rInfoPython.py {{ output.stdout_lines }}
      delegate_to: localhost

样本输出

"stdout_lines": [
            "", 
            "Windows IP Configuration", 
            "", 
            "   Host Name . . . . . . . . . . . . : test-win", 
            "   Primary Dns Suffix  . . . . . . . : ", 
            "   Node Type . . . . . . . . . . . . : local",
            "", 
            "Ethernet adapter Ethernet 3:", 
            "", 
            "   Connection-specific DNS Suffix  . : ", 
            "   Description . . . . . . . . . . . : Xr Device #0", 
            "   Physical Address. . . . . . . . . : 01-KJ-00-33-22-B0", 
            "   DHCP Enabled. . . . . . . . . . . : No", 
            "   Autoconfiguration Enabled . . . . : Yes", 
            "   IPv4 Address. . . . . . . . . . . : XX.XXX.X.XX(Preferred) ", 
            "   Subnet Mask . . . . . . . . . . . : 255.255.255.XX", 
            "   Default Gateway . . . . . . . . . : ", 
            "   DNS Servers . . . . . . . . . . . : XX.X.XX.XX", 
            "                                       XX.X.XX.XX", 
            "   NetBIOS over Tcpip. . . . . . . . : Enabled", 
            "", 
        ]

我想复制和打印 stdout_lines,因为它与 python 文件对齐格式以对其进行迭代

import sys
print(str(sys.argv))

请帮我解决它

标签: pythonlistansible

解决方案


出于该特定目的,您可能更乐意使用环境变量,或者(当然)将它们写入临时文件

    - command: python rInfoPython.py
      delegate_to: localhost
      environment:
        the_output: '{{ output.stdout }}'

然后您的脚本会将文本拉入为

import os
print(os.getenv("the_output"))

如果您坚持尝试通过这样的字符串传递丰富的结构,那么 JSON 编码将保留格式而不需要一堆 shell 巫术

    - command: python rInfoPython.py {{ output.stdout_lines | to_json | quote }}
      delegate_to: localhost
import json
import sys
text = sys.argv[1]
lines = json.loads(text)
print(f"received {len(lines)} lines")

推荐阅读