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, host_user,
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
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
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
54 if not os.path.isfile(playbook_path):
55 raise AnsibleException(
56 'Requested playbook not found - ' + playbook_path)
59 if ssh_priv_key_file_path:
60 pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
62 if not os.path.isfile(pk_file_path):
63 raise AnsibleException('Requested private SSH key not found - ' +
66 if not ssh_priv_key_file_path and not password:
67 raise AnsibleException('Invalid credentials, no priv key or password')
71 passwords = {'conn_pass': password, 'become_pass': password}
73 import ansible.constants
74 ansible.constants.HOST_KEY_CHECKING = False
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)
82 variable_manager.extra_vars = variables
85 if proxy_setting and proxy_setting.ssh_proxy_cmd:
86 ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
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'])
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)
102 logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
104 executor = PlaybookExecutor(
105 playbooks=[playbook_path],
107 variable_manager=variable_manager,
109 options=ansible_opts,
112 logger.debug('Executing Ansible Playbook - ' + playbook_path)
113 return executor.run()
116 def ssh_client(ip, user, private_key_filepath=None, password=None,
117 proxy_settings=None):
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
126 :return: the SSH client if can connect else false
128 logger.debug('Retrieving SSH client')
129 ssh = paramiko.SSHClient()
130 ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
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)
140 if not password and private_key_filepath:
141 pk_abs_path = os.path.expanduser(private_key_filepath)
144 ip, username=user, key_filename=pk_abs_path, password=password,
147 except Exception as e:
148 logger.warning('Unable to connect via SSH with message - ' + str(e))
151 class AnsibleException(Exception):
153 Exception when calls to the Keystone client cannot be served properly