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

8

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

        self.inventory = {}
13
14
15
16
17
18
19
20
21
        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']
22

23
24
25
        with tempfile.NamedTemporaryFile(mode='w', delete=False) as kf:
            kf.write(provisioner_response['pk'])
            self.temp_file = kf.name
26
            # print self.temp_file
27
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'])
        # ansible.constants.DEFAULT_PRIVATE_KEY_FILE = self.temp_file
30
        ansible.constants.HOST_KEY_CHECKING = False
31
        # ansible.constants.DEFAULT_GATHERING = 'explicit'
32

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

39
        all_hosts = []
40

41
42
43
44
45
46
47
48
49
50
        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)
51
        all_group.set_variable('local_net', self.cidr)
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
52

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

        slaves_group = ansible.inventory.group.Group(name='slaves')
64
65
        slaves_group.set_variable('proxy_env',
                                  {'http_proxy': 'http://' + self.inventory['master']['name'] + '.local:3128'})
66
67
68
        # 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]
69
            ansible_host.set_variable('internal_ip', host['ip'])
70
            ansible_host.set_variable('id', host_id)
71
72
73
            slaves_group.add_host(ansible_host)
        self.ansible_inventory.add_group(slaves_group)
        all_group.add_child_group(slaves_group)
74

75
        # print self.ansible_inventory.groups_list()
76

77
        return self.ansible_inventory
78

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

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

95

96
if __name__ == "__main__":
Ioannis Tsafaras's avatar
Ioannis Tsafaras committed
97
98
99
100
101
102
103
104
    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'}}
105

106
107
    manager = Manager(response)
    manager.create_inventory()
108
109
110
111
112
    # manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/testinventory.yml", tags=['hosts'])
    # manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/testproxy.yml", tags=['install'])

    manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/wait_for_ssh.yml")
    manager.run_playbook(playbook_file=script_path + "/../../ansible/playbooks/cluster/cluster-install.yml")
113

114
    manager.cleanup()