Reputation: 95
A tried to write a simulation of ansible-playbook running in Python3. Found an old docs from Ansible how to make it: https://docs.ansible.com/ansible/3/dev_guide/developing_api.html
I thought every paramteres has added to code, but the 'builtin' modules is still missing. I read answer another stackoverflow question (https://stackoverflow.com/a/73225346/4208035) this module cannot install via ansible-galaxy. How can I reach them via API ?
Here is my code:
from ansible import context
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.inventory.manager import InventoryManager
from ansible.module_utils.common.collections import ImmutableDict
from ansible.parsing.dataloader import DataLoader
from ansible.playbook import Play
from ansible.vars.manager import VariableManager
def main():
host_list = ['127.0.0.1']
context.CLIARGS = ImmutableDict(connection='local', become=None, become_method=None, become_user=None, check=False, diff=False)
sources = ','.join(host_list)
if len(host_list) == 1:
sources += ','
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources=sources)
variable_manager = VariableManager(loader=loader, inventory=inventory)
passwords = dict(vault_pass='secret')
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords
)
play_source = dict(
name="Ansible Play",
hosts=host_list,
gather_facts='no',
connection = 'local',
tasks=[
dict(action=dict(module='shell', args='ls'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}'))),
dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime'))),
]
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
try:
result = tqm.run(play)
finally:
tqm.cleanup()
if loader:
loader.cleanup_all_tmp_files()
if __name__ == '__main__':
main()
Result:
TASK [shell] *******************************************************************
fatal: [127.0.0.1]: FAILED! => {"msg": "error processing module_util ansible.module_utils._text.to_bytes loading redirected collection ansible.builtin: unable to locate collection ansible.builtin"}
Must be running in locally without extra (inventory, passwords, variable_manager).
Thanks for the inswer.
Upvotes: 0
Views: 24