程序式ansible: 保存结果到Python变量

2024-10-01 13:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用这段代码以编程方式运行ansible:https://github.com/jtyr/ansible-run_playbook和一个简单的剧本,它只是从Ubuntu服务器收集事实并将它们打印到屏幕上:

- name: Test play
  hosts: all
  tasks:
    - name: Debug task
      debug:
        msg: "{{hostvars[inventory_hostname]}}"
      tags:
        - debug

但我真正需要的是简单地将输出保存到python变量中,而不是通过模板运行输出到屏幕上(我将在Django应用程序中使用它)。有办法吗?在

谢谢你的阅读。在


Tags: run代码namehttpsdebuggithubcom屏幕
1条回答
网友
1楼 · 发布于 2024-10-01 13:29:58

输出总是去stdout。Runner类无法更改此行为。我从Can I redirect the stdout in python into some sort of string buffer?得到了一个想法,下面的更改将把输出保存在mystdout中。您可以通过调用mystdout.getvalue()来访问输出

from cStringIO import StringIO

def main():
    runner = Runner(
    ...
        # vault_pass='vault_password',
    )

    old_stdout = sys.stdout
    sys.stdout = mystdout = StringIO()

    stats = runner.run()

    sys.stdout = old_stdout
    print mystdout.getvalue()

相关问题 更多 >