python - python - Run Ansible playbook programmatically? - answerstu - answerstu

python - Run Ansible playbook programmatically?

I have a python application that calls the code below with the plan to run an Ansible playbook programmatically via the Ansible API versus using something like subprocess.

The code below runs but nothing actually seems to get executed. Grabbing the output of results just gives me a dictionary that looks like:

[{'plays': [localhost], 'playbook': 'playbooks/asg_elb_example.yml'}]

I am not sure where I am going wrong or what I am missing. Here is the code I am running.

import os
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(SCRIPT_DIR)

import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from import Play
from ansible.executor.playbook_executor import PlaybookExecutor

def ansible_part():
    playbook_path = "playbooks/asg_elb_example.yml"
    inventory_path = "hosts"

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff', 'listhosts', 'listtasks', 'listtags', 'syntax'])
    loader = DataLoader()
    options = Options(connection='local', module_path='%s/' % (ROOT_DIR), forks=100, become=None, become_method=None, become_user=None, check=False,
                    diff=False, listhosts=True, listtasks=False, listtags=False, syntax=False)
    passwords = dict(vault_pass='secret')

    inventory = InventoryManager(loader=loader, sources=[inventory_path])
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    executor = PlaybookExecutor(  
                playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader,  
                options=options, passwords=passwords)  
    results =  
    print results

def main():


1 Answer

  1. Quentin- Reply


    You tell Ansible to list hosts with listhosts=True and it is doing its job properly.

    To execute the playbook change to listhosts=False.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>