Search code examples
pythonansibleansible-2.xansible-api

Programmatic ansible: save result into python variable


I am using this code to run ansible programmatically: https://github.com/jtyr/ansible-run_playbook with a simple playbook that just gathers facts from an Ubuntu server and prints them to the screen:

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

But what I really need is to simply save that output into a python variable instead of running it through a template or outputting to the screen (I will actually be using it inside of a Django app). Is there a way to do this?

Thank you for reading.


Solution

  • The output was always going to stdout. The Runner class has no way to change this behavior. I got an idea from Can I redirect the stdout in python into some sort of string buffer? The following change will save the output in mystdout. You can access the output by calling 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()