Is it possible to run an Ansible Playbook in python script?

0 votes
Is it possible to run an Ansible Playbook in python script?
Jan 17 in Ansible by Cerci

1 answer to this question.

0 votes

Hey @Cerci, Of course its possible. You can do it the following way:

import os
import sys
from collections import namedtuple

from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_executor import PlaybookExecutor

variable_manager = VariableManager()
loader = DataLoader()

inventory = Inventory(loader=loader, variable_manager=variable_manager,  host_list='/home/slotlocker/hosts2')
playbook_path = '/home/slotlocker/ls.yml'

if not os.path.exists(playbook_path):
    print '[INFO] No playbook'

Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', 'connection','module_path', 'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])
options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='slotlocker', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method=None, become_user='root', verbosity=None, check=False)

variable_manager.extra_vars = {'hosts': 'mywebserver'} 
passwords = {}

pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)

results =
answered Jan 17 by Nicolas

Related Questions In Ansible

0 votes
1 answer

Is it possible to run commands on ansible host?

If you just trying to run a ...READ MORE

answered Jan 9 in Ansible by Vijay
0 votes
1 answer

Is it possible to run a playbook with a crontab?

Ofcourse you can run ansible playbook with ...READ MORE

answered Jan 17 in Ansible by Yesha
+1 vote
1 answer



answered Jul 30, 2018 in Ansible by Atul
• 10,240 points
0 votes
2 answers
+13 votes
2 answers



answered Mar 26, 2018 in DevOps & Agile by DragonLord999
• 8,380 points
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Role of subelement module in an Ansible playbook


answered Jan 16 in Ansible by Emily