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