【问题标题】:Get Python Ansible_Runner module STDOUT Key Value获取 Python Ansible_Runner 模块 STDOUT 键值
【发布时间】:2022-06-16 20:51:24
【问题描述】:

我正在使用ansbile_runner Python 模块,如下所示:

import ansible_runner
r = ansible_runner.run(private_data_dir='/tmp/demo', playbook='test.yml')

当我执行上面的代码时,它将显示输出而不用 Python 打印。我想要的是将标准输出内容保存到 Python 变量中以进行进一步的文本处理。

【问题讨论】:

    标签: python ansible


    【解决方案1】:

    您是否阅读了https://ansible-runner.readthedocs.io/en/stable/python_interface/ 下的手册?有一个示例,您可以添加另一个参数,称为output_fd,它可以是文件处理程序而不是sys.stdout

    遗憾的是,这是run_command 函数的参数,文档不是很好。查看https://github.com/ansible/ansible-runner/blob/devel/ansible_runner/interface.py 的源代码可能会对您有所帮助。

    根据https://github.com/ansible/ansible-runner/blob/devel/ansible_runner/runner.py 中的实现细节,run() 函数总是打印到标准输出。

    根据接口,run(json_mode=TRUE) 中有一个布尔标志,它将响应存储在 JSON 中(我希望在 r 而不是标准输出中),还有另一个布尔标志 quiet

    我玩了一会儿。目前 -whyever - 无法避免输出到标准输出。 Ansible_Runner 或 Ansible 将始终打印到标准输出。但是 Ansible_Runner 捕获输出并将其写入工件目录中的文件。如https://ansible-runner.readthedocs.io/en/stable/intro/#runner-artifacts-directory-hierarchy 中所述,每个 run() 命令都会生成该目录。所以有一个文件叫stdout。它包含详细信息。但返回的对象也包含该数据 - 这只是噪声输出(我无法避免)。这是我的例子

    playbook = 'playbook.yml'
    private_data_dir = 'data/' # existing folder with inventory etc
    work_dir = 'playbooks/' # contains playbook and roles
    
    try:
      logging.debug('Running ansible playbook {} with private data dir {} in project dir {}'.format(playbook, private_data_dir, work_dir))
      runner = ansible_runner.run(
        private_data_dir=private_data_dir, 
        project_dir=work_dir, 
        playbook=playbook,
        suppress_output_file=True,
        suppress_ansible_output=True,
        json_mode=True
      )
    
      processed = runner.stats.get('processed')
      failed = runner.stats.get('failures')
      
      # TODO inform backend
      for host in processed:
        if host in failed:
          logging.error('Host {} failed'.format(host))
        else:
          logging.debug('Host {} backupd'.format(host))
    
      logging.error('Playbook runs into status {} on inventory {}'.format(runner.status, inventory.get('name')))
    
      if runner.rc != 0:
        # we have an overall failure
      else:
        # success message
    except BaseException as err:
      logging.error('Could not process ansible playbook {}\n{}'.format(inventory.get('name'),err))
    

    【讨论】:

    • 是的,我读过那本手册。我需要将 stdout 的内容保存到运行命令中的变量中。
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2020-07-13
    • 2014-06-11
    • 1970-01-01
    相关资源
    最近更新 更多