Running ansible-playbook using Python API

Question:

How can I run a playbook in python script? What is the equivalent of the following using ansible module in python:

I was looking at their documenation in http://docs.ansible.com/developing_api.html but they have very limited examples.

Answer:

This covered in the Ansible documentation under “Python API.”

For example, ansible -i hosts dbservers -m setup is implemented via:

There are a bunch of non-documented parameters in the __init__ method of Runner (from ansible.runner). There’s too many to list inline, but I’ve included some of the parameters in this post as a guess to what you’re specifically looking for.

For instance, the above command that specifies a sudo user and pass would be:

For playbooks, look into playbook.PlayBook, which takes a similar set of initializers:

and can be executed with the .run() method. e.g.:

more robust usage can be found in the ansible-playbook file.

As far as I know, translating playbooks to Python modules is a bit more involved, but the documentation listed above should get you covered and you can reuse the YAML parser built into Ansible to convert playbooks to variables.

Leave a Reply