Updated installation documents and fixed problems found during investigation.
[snaps.git] / snaps / provisioning / ansible_utils.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 import logging
16
17 from collections import namedtuple
18
19 import os
20 import paramiko
21
22 try:
23     from ansible.parsing.dataloader import DataLoader
24     from ansible.vars import VariableManager
25     from ansible.inventory import Inventory
26     from ansible.executor.playbook_executor import PlaybookExecutor
27 except:
28     pass
29
30 __author__ = 'spisarski'
31
32 logger = logging.getLogger('ansible_utils')
33
34
35 def apply_playbook(playbook_path, hosts_inv, host_user, ssh_priv_key_file_path, variables=None, proxy_setting=None):
36     """
37     Executes an Ansible playbook to the given host
38     :param playbook_path: the (relative) path to the Ansible playbook
39     :param hosts_inv: a list of hostnames/ip addresses to which to apply the Ansible playbook
40     :param host_user: A user for the host instances (must be a password-less sudo user if playbook has "sudo: yes"
41     :param ssh_priv_key_file_path: the file location of the ssh key
42     :param variables: a dictionary containing any substitution variables needed by the Jinga 2 templates
43     :param proxy_setting: instance of os_credentials.ProxySettings class
44     :return: the results
45     """
46     if not os.path.isfile(playbook_path):
47         raise Exception('Requested playbook not found - ' + playbook_path)
48     if not os.path.isfile(ssh_priv_key_file_path):
49         raise Exception('Requested private SSH key not found - ' + ssh_priv_key_file_path)
50
51     import ansible.constants
52     ansible.constants.HOST_KEY_CHECKING = False
53
54     variable_manager = VariableManager()
55     if variables:
56         variable_manager.extra_vars = variables
57
58     loader = DataLoader()
59     inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=hosts_inv)
60     variable_manager.set_inventory(inventory)
61
62     ssh_extra_args = None
63     if proxy_setting and proxy_setting.ssh_proxy_cmd:
64         ssh_extra_args = '-o ProxyCommand=\'' + proxy_setting.ssh_proxy_cmd + '\''
65
66     options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', 'connection', 'module_path',
67                                      'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args',
68                                      'become', 'become_method', 'become_user', 'verbosity', 'check'])
69
70     ansible_opts = options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh',
71                            module_path=None, forks=100, remote_user=host_user, private_key_file=ssh_priv_key_file_path,
72                            ssh_common_args=None, ssh_extra_args=ssh_extra_args, become=None, become_method=None,
73                            become_user=None, verbosity=11111, check=False)
74
75     logger.debug('Setting up Ansible Playbook Executor for playbook - ' + playbook_path)
76     executor = PlaybookExecutor(
77         playbooks=[playbook_path],
78         inventory=inventory,
79         variable_manager=variable_manager,
80         loader=loader,
81         options=ansible_opts,
82         passwords=None)
83
84     logger.debug('Executing Ansible Playbook - ' + playbook_path)
85     return executor.run()
86
87
88 def ssh_client(ip, user, private_key_filepath, proxy_settings=None):
89     """
90     Retrieves and attemts an SSH connection
91     :param ip: the IP of the host to connect
92     :param user: the user with which to connect
93     :param private_key_filepath: the path to the private key file
94     :param proxy_settings: instance of os_credentials.ProxySettings class (optional)
95     :return: the SSH client if can connect else false
96     """
97     logger.debug('Retrieving SSH client')
98     ssh = paramiko.SSHClient()
99     ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
100
101     try:
102         proxy_cmd = None
103         if proxy_settings and proxy_settings.ssh_proxy_cmd:
104             proxy_cmd_str = str(proxy_settings.ssh_proxy_cmd.replace('%h', ip))
105             proxy_cmd_str = proxy_cmd_str.replace("%p", '22')
106             proxy_cmd = paramiko.ProxyCommand(proxy_cmd_str)
107
108         ssh.connect(ip, username=user, key_filename=private_key_filepath, sock=proxy_cmd)
109         return ssh
110     except Exception as e:
111         logger.warning('Unable to connect via SSH with message - ' + str(e))