Example for running a playbook using Python API

`

import ansible.runner
import ansible.playbook
from ansible import callbacks
from ansible import utils

stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)

pb = ansible.playbook.PlayBook(
playbook=“nseries.yml”,
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
check=True
)
for (play_ds, play_basedir) in zip(pb.playbook, pb.play_basedirs):
import ipdb
ipdb.set_trace()

Can play around here to see what’s going on.

pb.run() # This runs the playbook

`

Hi Jazzed,

I used your example as a base for triggering ansible through a python script, however while the output suggest that the connection to the node is made and the playbook is running, individual steps on the various roles fail consistently in contrast to running the playbook using the ansible-playbook command line tool passing the same playbook.

The output suggests no clear reasons for this behavior.

Any ideas on that?

Thanks,
Dimitris

Thanks Jazzed,

Its working fine only if I have my host listed in /etc/ansible/hosts, but I want to pass my custom host file while running a playbook. Can you tell me how to do so?

Lavish,

You can override the default inventory file ( /etc/ansible/hosts ) with the shell environment variable ANSIBLE_HOSTS.

I use the EC2 dynamic inventory script ( http://docs.ansible.com/intro_dynamic_inventory.html#example-aws-ec2-external-inventory-script ) like this:

$ ANSIBLE_HOSTS=/path/to/ec2.py python myscript.py

How to run ansible-playbook on ansible2.0 or later version?
The ansible.playbook has been removed.

在 2014年11月4日星期二 UTC+8上午2:36:35,Jazzed写道: