b4c86f2ae4dda6d6d20b75af70874ad4705d9f2e
[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.manager import VariableManager
25     from ansible.inventory.manager import InventoryManager
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=None, host_user=None,
36                    ssh_priv_key_file_path=None, password=None, variables=None,
37                    proxy_setting=None):
38     """
39     Executes an Ansible playbook to the given host
40     :param playbook_path: the (relative) path to the Ansible playbook
41     :param hosts_inv: a list of hostnames/ip addresses to which to apply the
42                       Ansible playbook (not required when PB is configured for
43                       localhost)
44     :param host_user: A user for the host instances (must be a password-less
45                       sudo user if playbook has "sudo: yes") (not required when
46                       PB is configured for localhost)
47     :param ssh_priv_key_file_path: the file location of the ssh key. Required
48                                    if password is None (not required when PB is
49                                    configured for localhost)
50     :param password: the file location of the ssh key. Required if
51                      ssh_priv_key_file_path is None (not required when PB is
52                      configured for localhost)
53     :param variables: a dictionary containing any substitution variables needed
54                       by the Jinga 2 templates
55     :param proxy_setting: instance of os_credentials.ProxySettings class
56     :raises AnsibleException when the return code from the Ansible library is
57             not 0
58     :return: the return code from the Ansible library only when 0.
59              Implementation now raises an exception otherwise
60     """
61     if not os.path.isfile(playbook_path):
62         raise AnsibleException(
63             'Requested playbook not found - ' + playbook_path)
64
65     pk_file_path = None
66     if ssh_priv_key_file_path:
67         pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
68         if not password:
69             if not os.path.isfile(pk_file_path):
70                 raise AnsibleException(
71                     'Requested private SSH key not found - ' + pk_file_path)
72
73     passwords = None
74     if password:
75         passwords = {'conn_pass': password, 'become_pass': password}
76
77     import ansible.constants
78     ansible.constants.HOST_KEY_CHECKING = False
79
80     loader = DataLoader()
81     inventory = InventoryManager(loader=loader)
82     if hosts_inv:
83         for host in hosts_inv:
84             inventory.add_host(host=host, group='ungrouped')
85         connection = 'ssh'
86     else:
87         connection = 'local'
88
89     variable_manager = VariableManager(loader=loader, inventory=inventory)
90
91     if variables:
92         variable_manager.extra_vars = variables
93
94     ssh_extra_args = None
95     if proxy_setting and proxy_setting.ssh_proxy_cmd:
96         ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
97
98     options = namedtuple(
99         'Options', ['listtags', 'listtasks', 'listhosts', 'syntax',
100                     'connection', 'module_path', 'forks', 'remote_user',
101                     'private_key_file', 'ssh_common_args', 'ssh_extra_args',
102                     'become', 'become_method', 'become_user', 'verbosity',
103                     'check', 'timeout', 'diff'])
104
105     ansible_opts = options(
106         listtags=False, listtasks=False, listhosts=False, syntax=False,
107         connection=connection, module_path=None, forks=100,
108         remote_user=host_user, private_key_file=pk_file_path,
109         ssh_common_args=None, ssh_extra_args=ssh_extra_args, become=None,
110         become_method=None, become_user=None, verbosity=11111, check=False,
111         timeout=30, diff=None)
112
113     logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
114                  playbook_path)
115     executor = PlaybookExecutor(
116         playbooks=[playbook_path],
117         inventory=inventory,
118         variable_manager=variable_manager,
119         loader=loader,
120         options=ansible_opts,
121         passwords=passwords)
122
123     logger.debug('Executing Ansible Playbook - ' + playbook_path)
124     ret_val = executor.run()
125
126     if ret_val != 0:
127         raise AnsibleException(
128             'Error applying playbook [{}] with value [{}] using the connection'
129             ' type of [{}]'.format(
130                 playbook_path, ret_val, connection))
131
132     return ret_val
133
134
135 def ssh_client(ip, user, private_key_filepath=None, password=None,
136                proxy_settings=None):
137     """
138     Retrieves and attemts an SSH connection
139     :param ip: the IP of the host to connect
140     :param user: the user with which to connect
141     :param private_key_filepath: when None, password is required
142     :param password: when None, private_key_filepath is required
143     :param proxy_settings: instance of os_credentials.ProxySettings class
144                            (optional)
145     :return: the SSH client if can connect else false
146     """
147     logger.debug('Retrieving SSH client')
148     ssh = paramiko.SSHClient()
149     ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
150
151     try:
152         proxy_cmd = None
153         if proxy_settings and proxy_settings.ssh_proxy_cmd:
154             proxy_cmd_str = str(proxy_settings.ssh_proxy_cmd.replace('%h', ip))
155             proxy_cmd_str = proxy_cmd_str.replace("%p", '22')
156             proxy_cmd = paramiko.ProxyCommand(proxy_cmd_str)
157
158         pk_abs_path = None
159         if not password and private_key_filepath:
160             pk_abs_path = os.path.expanduser(private_key_filepath)
161
162         ssh.connect(
163             ip, username=user, key_filename=pk_abs_path, password=password,
164             sock=proxy_cmd)
165         logger.info('Obtained SSH connection to %s', ip)
166         return ssh
167     except Exception as e:
168         logger.debug('Unable to connect via SSH with message - ' + str(e))
169
170
171 class AnsibleException(Exception):
172     """
173     Exception when calls to the Keystone client cannot be served properly
174     """