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 import VariableManager
25 from ansible.inventory import Inventory
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, ssh_priv_key_file_path,
36 variables=None, proxy_setting=None):
38 Executes an Ansible playbook to the given host
39 :param playbook_path: the (relative) path to the Ansible playbook
40 :param hosts_inv: a list of hostnames/ip addresses to which to apply the
42 :param host_user: A user for the host instances (must be a password-less
43 sudo user if playbook has "sudo: yes"
44 :param ssh_priv_key_file_path: the file location of the ssh key
45 :param variables: a dictionary containing any substitution variables needed
46 by the Jinga 2 templates
47 :param proxy_setting: instance of os_credentials.ProxySettings class
50 if not os.path.isfile(playbook_path):
51 raise AnsibleException('Requested playbook not found - ' + playbook_path)
53 pk_file_path = os.path.expanduser(ssh_priv_key_file_path)
54 if not os.path.isfile(pk_file_path):
55 raise AnsibleException('Requested private SSH key not found - ' +
58 import ansible.constants
59 ansible.constants.HOST_KEY_CHECKING = False
61 variable_manager = VariableManager()
63 variable_manager.extra_vars = variables
66 inventory = Inventory(loader=loader, variable_manager=variable_manager,
68 variable_manager.set_inventory(inventory)
71 if proxy_setting and proxy_setting.ssh_proxy_cmd:
72 ssh_extra_args = '-o ProxyCommand=\'%s\'' % proxy_setting.ssh_proxy_cmd
75 'Options', ['listtags', 'listtasks', 'listhosts', 'syntax',
76 'connection', 'module_path', 'forks', 'remote_user',
77 'private_key_file', 'ssh_common_args', 'ssh_extra_args',
78 'become', 'become_method', 'become_user', 'verbosity',
81 ansible_opts = options(
82 listtags=False, listtasks=False, listhosts=False, syntax=False,
83 connection='ssh', module_path=None, forks=100, remote_user=host_user,
84 private_key_file=pk_file_path, ssh_common_args=None,
85 ssh_extra_args=ssh_extra_args, become=None, become_method=None,
86 become_user=None, verbosity=11111, check=False)
88 logger.debug('Setting up Ansible Playbook Executor for playbook - ' +
90 executor = PlaybookExecutor(
91 playbooks=[playbook_path],
93 variable_manager=variable_manager,
98 logger.debug('Executing Ansible Playbook - ' + playbook_path)
102 def ssh_client(ip, user, private_key_filepath, proxy_settings=None):
104 Retrieves and attemts an SSH connection
105 :param ip: the IP of the host to connect
106 :param user: the user with which to connect
107 :param private_key_filepath: the path to the private key file
108 :param proxy_settings: instance of os_credentials.ProxySettings class
110 :return: the SSH client if can connect else false
112 logger.debug('Retrieving SSH client')
113 ssh = paramiko.SSHClient()
114 ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
118 if proxy_settings and proxy_settings.ssh_proxy_cmd:
119 proxy_cmd_str = str(proxy_settings.ssh_proxy_cmd.replace('%h', ip))
120 proxy_cmd_str = proxy_cmd_str.replace("%p", '22')
121 proxy_cmd = paramiko.ProxyCommand(proxy_cmd_str)
123 pk_abs_path = os.path.expanduser(private_key_filepath)
124 ssh.connect(ip, username=user, key_filename=pk_abs_path,
127 except Exception as e:
128 logger.warning('Unable to connect via SSH with message - ' + str(e))
131 class AnsibleException(Exception):
133 Exception when calls to the Keystone client cannot be served properly