Opened up API to allow for playbook application to localhost
[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     :return: the results
57     """
58     if not os.path.isfile(playbook_path):
59         raise AnsibleException(
60             'Requested playbook not found - ' + playbook_path)
61
62     pk_file_path = None
63     if ssh_priv_key_file_path:
64         pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
65         if not password:
66             if not os.path.isfile(pk_file_path):
67                 raise AnsibleException(
68                     'Requested private SSH key not found - ' + pk_file_path)
69
70     passwords = None
71     if password:
72         passwords = {'conn_pass': password, 'become_pass': password}
73
74     import ansible.constants
75     ansible.constants.HOST_KEY_CHECKING = False
76
77     loader = DataLoader()
78     inventory = InventoryManager(loader=loader)
79     if hosts_inv:
80         for host in hosts_inv:
81             inventory.add_host(host=host, group='ungrouped')
82     else:
83         inventory.remove_restriction()
84
85     variable_manager = VariableManager(loader=loader, inventory=inventory)
86
87     if variables:
88         variable_manager.extra_vars = variables
89
90     ssh_extra_args = None
91     if proxy_setting and proxy_setting.ssh_proxy_cmd:
92         ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
93
94     options = namedtuple(
95         'Options', ['listtags', 'listtasks', 'listhosts', 'syntax',
96                     'connection', 'module_path', 'forks', 'remote_user',
97                     'private_key_file', 'ssh_common_args', 'ssh_extra_args',
98                     'become', 'become_method', 'become_user', 'verbosity',
99                     'check', 'timeout', 'diff'])
100
101     ansible_opts = options(
102         listtags=False, listtasks=False, listhosts=False, syntax=False,
103         connection='ssh', module_path=None, forks=100, remote_user=host_user,
104         private_key_file=pk_file_path, ssh_common_args=None,
105         ssh_extra_args=ssh_extra_args, become=None, become_method=None,
106         become_user=None, verbosity=11111, check=False, timeout=30, diff=None)
107
108     logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
109                  playbook_path)
110     executor = PlaybookExecutor(
111         playbooks=[playbook_path],
112         inventory=inventory,
113         variable_manager=variable_manager,
114         loader=loader,
115         options=ansible_opts,
116         passwords=passwords)
117
118     logger.debug('Executing Ansible Playbook - ' + playbook_path)
119     return executor.run()
120
121
122 def ssh_client(ip, user, private_key_filepath=None, password=None,
123                proxy_settings=None):
124     """
125     Retrieves and attemts an SSH connection
126     :param ip: the IP of the host to connect
127     :param user: the user with which to connect
128     :param private_key_filepath: when None, password is required
129     :param password: when None, private_key_filepath is required
130     :param proxy_settings: instance of os_credentials.ProxySettings class
131                            (optional)
132     :return: the SSH client if can connect else false
133     """
134     logger.debug('Retrieving SSH client')
135     ssh = paramiko.SSHClient()
136     ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
137
138     try:
139         proxy_cmd = None
140         if proxy_settings and proxy_settings.ssh_proxy_cmd:
141             proxy_cmd_str = str(proxy_settings.ssh_proxy_cmd.replace('%h', ip))
142             proxy_cmd_str = proxy_cmd_str.replace("%p", '22')
143             proxy_cmd = paramiko.ProxyCommand(proxy_cmd_str)
144
145         pk_abs_path = None
146         if not password and private_key_filepath:
147             pk_abs_path = os.path.expanduser(private_key_filepath)
148
149         ssh.connect(
150             ip, username=user, key_filename=pk_abs_path, password=password,
151             sock=proxy_cmd)
152         return ssh
153     except Exception as e:
154         logger.warning('Unable to connect via SSH with message - ' + str(e))
155
156
157 class AnsibleException(Exception):
158     """
159     Exception when calls to the Keystone client cannot be served properly
160     """