- Authors
- Name
Overview
I wanted to use dynamic inventories and dynamic variables in Django, which runs as Python code, and fortunately I found a module called ansible-runner. Ansible Runner is a Python module that enables running Ansible from Python. Upon trying it, I found it also has features that guarantee consistent execution results regardless of the ansible version being used, and it was convenient for registering event callbacks to output results in real-time. Detailed documentation is available on the official website.
How to Run
As shown below, after importing ansible_runner, you can execute an ansible playbook by calling run with private_data_dir, playbook, and inventory as arguments. Of course, ansible must be installed on the server running ansible-runner. I installed it using pip as follows: pip install ansible
import ansible_runner
def event_callback(event_data):
# do something every event
print(event_data)
def finished_callback(runner):
#do something after finishing
print runner
return
r = ansible_runner.run(
private_data_dir=os.path.join(
settings.BASE_DIR,"private_directory"
),
playbook=os.path.join(
settings.BASE_DIR,"playbook_directory",
"setup.yml"
),
event_handler=event_callback,
finished_callback=finished_callback,
quiet=True,
)
Any playbook that can be executed in ansible can also be executed through ansible_runner.