How can I run a playbook in python script? What is the equivalent of the following using ansible module in python:
ansible -i hosts dbservers -m setup
ansible-playbook -i hosts -vvvv -k site.yml
I was looking at their documenation in http://docs.ansible.com/developing_api.html but they have very limited examples.
Deprecation Notice: This post doesn't work as of Ansible 2. The API was changed.
This is covered in the Ansible documentation under "Python API."
For example,
ansible -i hosts dbservers -m setupis implemented via:There are a bunch of non-documented parameters in the
__init__method of Runner (fromansible.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-playbookfile.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.