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 logger = logging.getLogger('ansible_utils')
35 def apply_playbook(playbook_path, hosts_inv=None, host_user=None,
36 ssh_priv_key_file_path=None, password=None, variables=None,
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
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
58 if not os.path.isfile(playbook_path):
59 raise AnsibleException(
60 'Requested playbook not found - ' + playbook_path)
63 if ssh_priv_key_file_path:
64 pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
66 if not os.path.isfile(pk_file_path):
67 raise AnsibleException(
68 'Requested private SSH key not found - ' + pk_file_path)
72 passwords = {'conn_pass': password, 'become_pass': password}
74 import ansible.constants
75 ansible.constants.HOST_KEY_CHECKING = False
78 inventory = InventoryManager(loader=loader)
80 for host in hosts_inv:
81 inventory.add_host(host=host, group='ungrouped')
83 inventory.remove_restriction()
85 variable_manager = VariableManager(loader=loader, inventory=inventory)
88 variable_manager.extra_vars = variables
91 if proxy_setting and proxy_setting.ssh_proxy_cmd:
92 ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
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'])
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)
108 logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
110 executor = PlaybookExecutor(
111 playbooks=[playbook_path],
113 variable_manager=variable_manager,
115 options=ansible_opts,
118 logger.debug('Executing Ansible Playbook - ' + playbook_path)
119 return executor.run()
122 def ssh_client(ip, user, private_key_filepath=None, password=None,
123 proxy_settings=None):
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
132 :return: the SSH client if can connect else false
134 logger.debug('Retrieving SSH client')
135 ssh = paramiko.SSHClient()
136 ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
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)
146 if not password and private_key_filepath:
147 pk_abs_path = os.path.expanduser(private_key_filepath)
150 ip, username=user, key_filename=pk_abs_path, password=password,
153 except Exception as e:
154 logger.warning('Unable to connect via SSH with message - ' + str(e))
157 class AnsibleException(Exception):
159 Exception when calls to the Keystone client cannot be served properly