Split View: Ansible-Runner (Python 에서 ansible 실행)
Ansible-Runner (Python 에서 ansible 실행)
Overview
Python코드로 실행하는 Django에서 동적 인벤토리, 동적 변수를 사용하고 싶었는데, 다행히 ansiblerunner 라는 module을 찾게되었다.Ansible Runner는 Python 에서 Ansible 을 실행할 수 있도록 도와주는 파이썬 모듈이다. 사용해보니 실행되는 ansible version에 상관없이 같은 실행결과를 보장하는 기능도 있고, event callback을 등록해 실시간으로 output을 출력할 때도 편리했다.공식홈페이지에 자세한 설명이 나와있다.
실행방법
아래와 같이 ansible_runner를 import한 뒤, run을 호출하면서, 인자로 private_data_dir, playbook, inventory 를 넣어주면 ansible playbook을 실행가능하다.
물론 ansible-runner를 실행하는 서버에 ansible이 설치되어 있어야한다. 나는 다음과 같은 pip를 사용해 설치하였다. 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,
)
ansible에서 실행가능한 play-book이라면 ansible_runner 에서도 실행이 가능하다.
Ansible-Runner (Running Ansible from Python)
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.
Quiz
Q1: What is the main topic covered in "Ansible-Runner (Running Ansible from Python)"?
Learn about the Ansible Runner module that enables running Ansible from Python.
Q2: 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.