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