ansible_manager.py 5.15 KB
Newer Older
1
import inspect
2
import os
3
import tempfile
4 5 6 7 8
import ansible
from ansible.playbook import PlayBook
from ansible import callbacks
from ansible import utils

9

10
class Manager:
11
    def __init__(self, provisioner_response):
12 13

        self.inventory = {}
14 15 16 17 18 19 20 21 22
        self.inventory['master'] = {
            'name': 'snf-' + str(provisioner_response['nodes']['master']['id']),
            'ip': provisioner_response['nodes']['master']['internal_ip']}
        self.inventory['slaves'] = []
        for response in provisioner_response['nodes']['slaves']:
            self.inventory['slaves'].append(
                {'name': 'snf-' + str(response['id']),
                 'ip': response['internal_ip']})
        self.cidr = provisioner_response['subnet']['cidr']
23

24 25 26
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as kf:
            kf.write(provisioner_response['pk'])
            self.temp_file = kf.name
27
            # print self.temp_file
28 29
        ansible.constants.ANSIBLE_SSH_ARGS = '-o "ProxyCommand ssh -i %s -o StrictHostKeyChecking=no -W %%h:%%p root@%s.vm.okeanos.grnet.gr"' \
                                             % (self.temp_file, self.inventory['master']['name'])
30
        ansible.constants.DEFAULT_TIMEOUT = 30
31
        # ansible.constants.DEFAULT_PRIVATE_KEY_FILE = self.temp_file
32
        ansible.constants.HOST_KEY_CHECKING = False
33
        # ansible.constants.DEFAULT_GATHERING = 'explicit'
34

35
    def create_inventory(self):
36 37 38 39
        """
        Create the inventory using the ansible library objects
        :return:
        """
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
40

41
        all_hosts = []
42

43 44 45 46 47 48 49 50 51 52
        host = self.inventory['master']
        all_hosts.append(host['name'] + '.vm.okeanos.grnet.gr')
        ansible_host = ansible.inventory.host.Host(name=all_hosts[-1])
        for host in self.inventory['slaves']:
            all_hosts.append(host['name'] + '.local')
            ansible_host = ansible.inventory.host.Host(name=all_hosts[-1])
        self.ansible_inventory = ansible.inventory.Inventory(host_list=all_hosts)

        all_group = self.ansible_inventory.get_group('all')
        all_group.set_variable('ansible_ssh_private_key_file', self.temp_file)
53
        all_group.set_variable('local_net', self.cidr)
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
54

55
        all_ansible_hosts = all_group.get_hosts()
56
        master_group = ansible.inventory.group.Group(name='master')
57
        master_group.set_variable('proxy_env', {})
58
        ansible_host = all_ansible_hosts[0]
59
        ansible_host.set_variable('internal_ip', self.inventory['master']['ip'])
60
        ansible_host.set_variable('id', 0)
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
61
        master_group.add_host(ansible_host)
62 63 64 65
        self.ansible_inventory.add_group(master_group)
        all_group.add_child_group(master_group)

        slaves_group = ansible.inventory.group.Group(name='slaves')
66 67
        slaves_group.set_variable('proxy_env',
                                  {'http_proxy': 'http://' + self.inventory['master']['name'] + '.local:3128'})
68 69 70
        # slaves_group.set_variable('http_proxy', 'http://' + self.inventory['master']['name'] + '.local:3128')
        for host_id, host in enumerate(self.inventory['slaves'], start=1):
            ansible_host = all_ansible_hosts[host_id]
71
            ansible_host.set_variable('internal_ip', host['ip'])
72
            ansible_host.set_variable('id', host_id)
73 74 75
            slaves_group.add_host(ansible_host)
        self.ansible_inventory.add_group(slaves_group)
        all_group.add_child_group(slaves_group)
76

77
        # print self.ansible_inventory.groups_list()
78
        return self.ansible_inventory
79

Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
80
    def run_playbook(self, playbook_file, tags=None):
81 82 83 84
        """
        Run the playbook_file using created inventory and tags specified
        :return:
        """
85 86 87
        stats = callbacks.AggregateStats()
        playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
        runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
88
        pb = PlayBook(playbook=playbook_file, inventory=self.ansible_inventory, stats=stats,
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
89
                      callbacks=playbook_cb,
90 91 92
                      runner_callbacks=runner_cb, only_tags=tags)
        pb.run()

93 94
    def cleanup(self):
        os.remove(self.temp_file)
95

96

97
if __name__ == "__main__":
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
98 99 100 101 102 103 104 105
    response = {
        u'ips': [{u'floating_network_id': u'2186', u'floating_ip_address': u'83.212.116.49', u'id': u'688160'}],
        u'nodes': {
            u'master': {'internal_ip': u'192.168.0.2', u'adminPass': u'0igc3vbnSx', u'id': 666976, u'name': u'test_vm'},
            u'slaves': [{'internal_ip': u'192.168.0.3', u'id': 666977, u'name': u'lambda-node1'}]},
        u'vpn': {u'type': u'MAC_FILTERED', u'id': u'143713'},
        'pk': 'Dummy pk',
        u'subnet': {u'cidr': u'192.168.0.0/24', u'gateway_ip': u'192.168.0.1', u'id': u'142761'}}
106

107
    script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
108 109
    manager = Manager(response)
    manager.create_inventory()
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
110 111
    # manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/test/testinventory.yml", tags=['hosts'])
    # manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/test/testproxy.yml", tags=['install'])
112

Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
113
    manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/cluster-install.yml")
114

115
    manager.cleanup()