python - 将 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))
请帮我解决它
解决方案
出于该特定目的,您可能更乐意使用环境变量,或者(当然)将它们写入临时文件
- 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")
推荐阅读
- python - 在matplotlib中处理按键事件时如何保留默认键盘快捷键
- vba - 我需要我的程序复制 3 个单元格并将其作为图片粘贴到下一张纸上。我需要它对列表中的每一行重复此操作
- excel - 有没有办法将(excel屏幕剪辑按钮程序)分配给用户窗体命令按钮?
- jinja2 - DBT 宏忽略前导 if 块
- ssh - Mobaxterm:通过 SSH 网关连接(跳转主机)给出错误为“远程端意外关闭网络连接”
- kotlin - Kotlin 内部类无法解析外部类中声明的扩展函数
- iot - 谷歌主页。关于配置锁定设备的问题
- typescript - 如果字段未设置值,prisma postgresql 无法设置未定义
- json - 反对在客户端创建 JWT 的论据
- javascript -
在我的 Nuxt js 应用程序中毁掉我的 CSS