3

I want to use Ansible to collect information from a number of servers. The information should be postprocessed locally, so it should be presented in a certain format. Other than grep and sed and awk and other sysadmin's best friends, how do I get from Ansible what is relevant to the task and nothing else?

There must be a way either to run Ansible from Python, exporting variables to the wrapping script, or to run Python from Ansible to customize the output.

minaev
  • 1,549
  • 12
  • 13

1 Answers1

4

Ansible is indeed directly callable from your own python script. The Ansible API is fully documented. I have not used it myself but you should be able to write your own python script to leverage Ansible and do what you want. According to their documentation is as simple as this:

import ansible.runner

runner = ansible.runner.Runner(
   module_name='ping',
   module_args='',
   pattern='web*',
   forks=10
)
datastructure = runner.run()

There's a more thorough example in the documentation that I linked to.

Bruce P
  • 2,163
  • 3
  • 16
  • 21
  • 1
    Yes! Thanks. I wouldn't say, though, that that page qualifies as 'fully documented' :) But it redirects the reader to a better source of information, the sources of ansible and ansible-playbook. These sources use `callback.display` to output data, which took me to http://blog.cliffano.com/2014/04/06/human-readable-ansible-playbook-log-output-using-callback-plugin/ It seems to be the solution of the problem :) – minaev Oct 16 '14 at 05:26
  • 1
    Beware the documentation clearly stipulates: This API is intended for internal Ansible use. Ansible may make changes to this API at any time that could break backward compatibility with older versions of the API. Because of this, external use is not supported by Ansible". Indeed, the *runner* module does not exist anymore. – pedroapero Oct 19 '18 at 12:29