Invoking Ansible Inside Python Flask

Pasting sample code that can be used as is to run ansible inside python flask app.
This would be a very useful base implementation when devops need to control system over the web or someone tries to control systems over internet without cli

Prerequisites

Install Python3

#PYTHON3 ( Assuming Centos7 or RHEL Flavor). Change accordingly for your env
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum -y install python36u
yum -y install python36u-pip
yum -y install python36u-devel

virtualenv –python=/usr/bin/python3.6 venv

 

from flask import (
    Blueprint
)

import json
import shutil
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
import ansible.constants as C


#Blueprint URL Configuration routes
bp = Blueprint('AnsibleController', __name__, url_prefix='/AnsibleController')


# Ansible Return callback
class ResultCallback(CallbackBase):
    """A sample callback plugin used for performing an action as results come in

    If you want to collect all results into a single object for processing at
    the end of the execution, look into utilizing the ``json`` callback plugin
    or writing your own custom callback plugin
    """
    def __init__(self):
        self.resp = []

    def v2_runner_on_ok(self, result, **kwargs):
        """Print a json representation of the result

        This method could store the result in an instance attribute for retrieval later
        """
        host = result._host
        self.resp.append(json.dumps({host.name: result._result}, indent=4))





#print (json.dumps(out, sort_keys=True, indent=4, separators=(',', ': ')))

@bp.route('/ping', methods=('GET', 'POST'))
def ping():
    # since API is constructed for CLI it expects certain options to always be set, named tuple 'fakes' the args parsing options object
    Options = namedtuple('Options',
                         ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check',
                          'diff'])
    options = Options(connection='local', module_path=['/etc/swiftui/.swiftui/ansible/mymodules'], forks=100, become=None, become_method=None,
                      become_user=None, check=False, diff=False)

    # initialize needed objects
    loader = DataLoader()  # Takes care of finding and reading yaml, json and ini files
    passwords = dict(vault_pass='secret')

    # Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
    results_callback = ResultCallback()

    # create inventory, use path to host config file as source or hosts in a comma separated string
    inventory = InventoryManager(loader=loader, sources='localhost,')

    # variable manager takes care of merging all the different sources to give you a unifed view of variables available in each context
    variable_manager = VariableManager(loader=loader, inventory=inventory)

    # create datastructure that represents our play, including tasks, this is basically what our YAML loader does internally.
    play_source = dict(
        name="Ansible Play",
        hosts='localhost',
        gather_facts='no',
        tasks=[
            dict(action=dict(module='shell', args='ls'), register='shell_out'),
            dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
        ]
    )

    # Create play object, playbook objects use .load instead of init or new methods,
    # this will also automatically create the task objects from the info provided in play_source
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # Run it - instantiate task queue manager, which takes care of forking and setting up
    # all objects to iterate over host list and tasks
    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords,
            stdout_callback=results_callback,
            # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
        )
        result = tqm.run(play)  # most interesting data for a play is actually sent to the callback's methods
    finally:
        # we always need to cleanup child procs and the structres we use to communicate with them
        if tqm is not None:
            tqm.cleanup()

        # Remove ansible tmpdir
        shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    return ''.join(results_callback.resp)

 

Install Virtualbox Extension Commandline

$(vboxmanage -v)

Gives version like this  5.1.4r110228

We need split above version with “r” and use those to generate our required filename

Then get the file from download. virtualbox. org/virtualbox/5.1.4/

Installing is just issuing this command

sudo VBoxManage extpack install <YOUR FILE> –replace

#!/bin/bash
version=$(vboxmanage -v)
echo $version
var1=$(echo $version | cut -d ‘r’ -f 1)
echo $var1
var2=$(echo $version | cut -d ‘r’ -f 2)
echo $var2
file=”Oracle_VM_VirtualBox_Extension_Pack-$var1-$var2.vbox-extpack”
echo $file
wget ***: download. virtualbox. org/virtualbox/$var1/$file -O /tmp/$file
#sudo VBoxManage extpack uninstall “Oracle VM VirtualBox Extension Pack”
sudo VBoxManage extpack install /tmp/$file –replace