Merge "Created new class AnsibleException."
[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,
36                    variables=None, proxy_setting=None):
37     """
38     Executes an Ansible playbook to the given host
39     :param playbook_path: the (relative) path to the Ansible playbook
40     :param hosts_inv: a list of hostnames/ip addresses to which to apply the
41                       Ansible playbook
42     :param host_user: A user for the host instances (must be a password-less
43                       sudo user if playbook has "sudo: yes"
44     :param ssh_priv_key_file_path: the file location of the ssh key
45     :param variables: a dictionary containing any substitution variables needed
46                       by the Jinga 2 templates
47     :param proxy_setting: instance of os_credentials.ProxySettings class
48     :return: the results
49     """
50     if not os.path.isfile(playbook_path):
51         raise AnsibleException('Requested playbook not found - ' + playbook_path)
52
53     pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
54     if not os.path.isfile(pk_file_path):
55         raise AnsibleException('Requested private SSH key not found - ' +
56                         pk_file_path)
57
58     import ansible.constants
59     ansible.constants.HOST_KEY_CHECKING = False
60
61     variable_manager = VariableManager()
62     if variables:
63         variable_manager.extra_vars = variables
64
65     loader = DataLoader()
66     inventory = Inventory(loader=loader, variable_manager=variable_manager,
67                           host_list=hosts_inv)
68     variable_manager.set_inventory(inventory)
69
70     ssh_extra_args = None
71     if proxy_setting and proxy_setting.ssh_proxy_cmd:
72         ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
73
74     options = namedtuple(
75         'Options', ['listtags', 'listtasks', 'listhosts', 'syntax',
76                     'connection', 'module_path', 'forks', 'remote_user',
77                     'private_key_file', 'ssh_common_args', 'ssh_extra_args',
78                     'become', 'become_method', 'become_user', 'verbosity',
79                     'check'])
80
81     ansible_opts = options(
82         listtags=False, listtasks=False, listhosts=False, syntax=False,
83         connection='ssh', module_path=None, forks=100, remote_user=host_user,
84         private_key_file=pk_file_path, ssh_common_args=None,
85         ssh_extra_args=ssh_extra_args, become=None, become_method=None,
86         become_user=None, verbosity=11111, check=False)
87
88     logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
89                  playbook_path)
90     executor = PlaybookExecutor(
91         playbooks=[playbook_path],
92         inventory=inventory,
93         variable_manager=variable_manager,
94         loader=loader,
95         options=ansible_opts,
96         passwords=None)
97
98     logger.debug('Executing Ansible Playbook - ' + playbook_path)
99     return executor.run()
100
101
102 def ssh_client(ip, user, private_key_filepath, proxy_settings=None):
103     """
104     Retrieves and attemts an SSH connection
105     :param ip: the IP of the host to connect
106     :param user: the user with which to connect
107     :param private_key_filepath: the path to the private key file
108     :param proxy_settings: instance of os_credentials.ProxySettings class
109                            (optional)
110     :return: the SSH client if can connect else false
111     """
112     logger.debug('Retrieving SSH client')
113     ssh = paramiko.SSHClient()
114     ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
115
116     try:
117         proxy_cmd = None
118         if proxy_settings and proxy_settings.ssh_proxy_cmd:
119             proxy_cmd_str = str(proxy_settings.ssh_proxy_cmd.replace('%h', ip))
120             proxy_cmd_str = proxy_cmd_str.replace("%p", '22')
121             proxy_cmd = paramiko.ProxyCommand(proxy_cmd_str)
122
123         pk_abs_path = os.path.expanduser(private_key_filepath)
124         ssh.connect(ip, username=user, key_filename=pk_abs_path,
125                     sock=proxy_cmd)
126         return ssh
127     except Exception as e:
128         logger.warning('Unable to connect via SSH with message - ' + str(e))
129
130
131 class AnsibleException(Exception):
132     """
133     Exception when calls to the Keystone client cannot be served properly
134     """