ansible_manager_minimal.py 1.84 KB
Newer Older
1
2
3
4
5
6
7
8
import os
import ansible
from ansible.playbook import PlayBook
from ansible import callbacks
from ansible import utils


class Manager:
9
10
11
    def __init__(self, host, group, private_key_path=None):
        if private_key_path is None:
            private_key_path = os.path.expanduser('~/.ssh/id_rsa')
12
13
14
15
16
        if not os.path.exists(private_key_path):
            message = "The private key file was not found in the default location, " \
                      "or the location specified (if any). Please re-run, specifying a " \
                      "valid private key file."
            raise IOError(message)
17
        ansible.constants.HOST_KEY_CHECKING = False
18
        ansible.constants.DEFAULT_TIMEOUT = 30
19
20
21
22

        self.ansible_inventory = ansible.inventory.Inventory(host_list=[host])
        all_group = self.ansible_inventory.get_group('all')
        ansible_host = all_group.get_hosts()[0]
23
        ansible_host.set_variable('ansible_ssh_private_key_file', private_key_path)
24
25
26
27
28
        ansible_group = ansible.inventory.group.Group(name=group)
        ansible_group.add_host(ansible_host)
        self.ansible_inventory.add_group(ansible_group)
        all_group.add_child_group(ansible_group)

29
    def run_playbook(self, playbook_file, only_tags=None, skip_tags=None):
30
31
32
33
34
35
36
37
        """
        Run the playbook_file using created inventory and tags specified
        :return:
        """
        stats = callbacks.AggregateStats()
        playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
        runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
        pb = PlayBook(playbook=playbook_file, inventory=self.ansible_inventory, stats=stats,
38
39
                      callbacks=playbook_cb, runner_callbacks=runner_cb,
                      only_tags=only_tags, skip_tags=skip_tags)
40
41
        playbook_result = pb.run()
        return playbook_result