1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 # and others. All rights reserved.
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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 from collections import namedtuple
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
30 __author__ = 'spisarski'
32 from warnings import warn
33 warn('This utility will be removed in a subsequent release',
36 logger = logging.getLogger('ansible_utils')
39 def apply_playbook(playbook_path, hosts_inv=None, host_user=None,
40 ssh_priv_key_file_path=None, password=None, variables=None,
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
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
62 :return: the return code from the Ansible library only when 0.
63 Implementation now raises an exception otherwise
65 if not os.path.isfile(playbook_path):
66 raise AnsibleException(
67 'Requested playbook not found - ' + playbook_path)
70 if ssh_priv_key_file_path:
71 pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
73 if not os.path.isfile(pk_file_path):
74 raise AnsibleException(
75 'Requested private SSH key not found - ' + pk_file_path)
79 passwords = {'conn_pass': password, 'become_pass': password}
81 import ansible.constants
82 ansible.constants.HOST_KEY_CHECKING = False
85 inventory = InventoryManager(loader=loader)
87 for host in hosts_inv:
88 inventory.add_host(host=host, group='ungrouped')
93 variable_manager = VariableManager(loader=loader, inventory=inventory)
96 variable_manager.extra_vars = variables
99 if proxy_setting and proxy_setting.ssh_proxy_cmd:
100 ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
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'])
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)
117 logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
119 executor = PlaybookExecutor(
120 playbooks=[playbook_path],
122 variable_manager=variable_manager,
124 options=ansible_opts,
127 logger.debug('Executing Ansible Playbook - ' + playbook_path)
128 ret_val = executor.run()
131 raise AnsibleException(
132 'Error applying playbook [{}] with value [{}] using the connection'
133 ' type of [{}]'.format(
134 playbook_path, ret_val, connection))
139 def ssh_client(ip, user, private_key_filepath=None, password=None,
140 proxy_settings=None):
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
149 :return: the SSH client if can connect else false
151 logger.debug('Retrieving SSH client')
152 ssh = paramiko.SSHClient()
153 ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
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)
163 if not password and private_key_filepath:
164 pk_abs_path = os.path.expanduser(private_key_filepath)
167 ip, username=user, key_filename=pk_abs_path, password=password,
169 logger.info('Obtained SSH connection to %s', ip)
171 except Exception as e:
172 logger.debug('Unable to connect via SSH with message - ' + str(e))
175 class AnsibleException(Exception):
177 Exception when calls to the Keystone client cannot be served properly