| 1 |
#!/usr/bin/python |
| 2 |
''' |
| 3 |
# (c) 2020-2025, NetApp, Inc |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
''' |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
ANSIBLE_METADATA = {'metadata_version': '1.1', |
| 11 |
'status': ['preview'], |
| 12 |
'supported_by': 'certified'} |
| 13 |
|
| 14 |
DOCUMENTATION = ''' |
| 15 |
author: NetApp Ansible Team (@carchi8py) <[email protected]> |
| 16 |
description: |
| 17 |
- Run cli commands on ONTAP over SSH using paramiko. |
| 18 |
- Output is returned in C(stdout) and C(stderr), and also as C(stdout_lines), C(stdout_lines_filtered), C(stderr_lines). |
| 19 |
- Note that the module can succeed even though the command failed. You need to analyze stdout and check the results. |
| 20 |
- If the SSH host key is unknown and accepted, C(warnings) is updated. |
| 21 |
- Options related to ZAPI or REST APIs are ignored. |
| 22 |
extends_documentation_fragment: |
| 23 |
- netapp.ontap.netapp.na_ontap |
| 24 |
module: na_ontap_ssh_command |
| 25 |
short_description: NetApp ONTAP Run any cli command over plain SSH using paramiko. |
| 26 |
version_added: 20.8.0 |
| 27 |
options: |
| 28 |
command: |
| 29 |
description: |
| 30 |
- a string containing the command and arguments. |
| 31 |
required: true |
| 32 |
type: str |
| 33 |
privilege: |
| 34 |
description: |
| 35 |
- privilege level at which to run the command, eg admin, advanced. |
| 36 |
- if set, the command is prefixed with C(set -privilege <privilege>;). |
| 37 |
type: str |
| 38 |
accept_unknown_host_keys: |
| 39 |
description: |
| 40 |
- When false, reject the connection if the host key is not in known_hosts file. |
| 41 |
- When true, if the host key is unknown, accept it, but report a warning. |
| 42 |
- Note that the key is not added to the file. You could add the key by manually using SSH. |
| 43 |
type: bool |
| 44 |
default: false |
| 45 |
include_lines: |
| 46 |
description: |
| 47 |
- return only lines containing string pattern in C(stdout_lines_filtered) |
| 48 |
default: '' |
| 49 |
type: str |
| 50 |
exclude_lines: |
| 51 |
description: |
| 52 |
- return only lines containing string pattern in C(stdout_lines_filtered) |
| 53 |
default: '' |
| 54 |
type: str |
| 55 |
service_processor: |
| 56 |
description: |
| 57 |
- whether the target system is ONTAP or the service processor (SP) |
| 58 |
- only menaningful when privilege is set |
| 59 |
aliases: [sp] |
| 60 |
default: false |
| 61 |
type: bool |
| 62 |
''' |
| 63 |
|
| 64 |
EXAMPLES = """ |
| 65 |
- name: run ontap cli command using SSH |
| 66 |
netapp.ontap.na_ontap_ssh_command: |
| 67 |
hostname: "{{ netapp_hostname }}" |
| 68 |
username: "{{ netapp_username }}" |
| 69 |
password: "{{ netapp_password }}" |
| 70 |
command: version |
| 71 |
|
| 72 |
# Same as above, with parameters |
| 73 |
- name: run ontap cli command |
| 74 |
netapp.ontap.na_ontap_ssh_command: |
| 75 |
hostname: "{{ netapp_hostname }}" |
| 76 |
username: "{{ netapp_username }}" |
| 77 |
password: "{{ netapp_password }}" |
| 78 |
command: node show -fields node,health,uptime,model |
| 79 |
privilege: admin |
| 80 |
|
| 81 |
# Same as above, but with lines filtering |
| 82 |
- name: run ontap cli command |
| 83 |
netapp.ontap.na_ontap_ssh_command: |
| 84 |
hostname: "{{ netapp_hostname }}" |
| 85 |
username: "{{ netapp_username }}" |
| 86 |
password: "{{ netapp_password }}" |
| 87 |
command: node show -fields node,health,uptime,model |
| 88 |
exclude_lines: 'ode ' # Exclude lines with 'Node ' or 'node' |
| 89 |
# use with caution! |
| 90 |
accept_unknown_host_keys: true |
| 91 |
privilege: admin |
| 92 |
|
| 93 |
- name: run ontap SSH command on SP |
| 94 |
netapp.ontap.na_ontap_ssh_command: |
| 95 |
# <<: *sp_login |
| 96 |
command: sp switch-version |
| 97 |
privilege: diag |
| 98 |
sp: true |
| 99 |
register: result |
| 100 |
""" |
| 101 |
|
| 102 |
RETURN = """ |
| 103 |
stdout_lines_filtered: |
| 104 |
description: |
| 105 |
- In addition to stdout and stdout_lines, a list of non-white lines, excluding last and failed login information. |
| 106 |
- The list can be further refined using the include_lines and exclude_lines filters. |
| 107 |
returned: always |
| 108 |
type: list |
| 109 |
""" |
| 110 |
|
| 111 |
import traceback |
| 112 |
import warnings |
| 113 |
from ansible.module_utils.basic import AnsibleModule |
| 114 |
from ansible.module_utils._text import to_native |
| 115 |
import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils |
| 116 |
|
| 117 |
try: |
| 118 |
import paramiko |
| 119 |
HAS_PARAMIKO = True |
| 120 |
except ImportError: |
| 121 |
HAS_PARAMIKO = False |
| 122 |
|
| 123 |
|
| 124 |
class NetAppONTAPSSHCommand(object): |
| 125 |
''' calls a CLI command using SSH''' |
| 126 |
|
| 127 |
def __init__(self): |
| 128 |
self.argument_spec = netapp_utils.na_ontap_host_argument_spec() |
| 129 |
self.argument_spec.update(dict( |
| 130 |
command=dict(required=True, type='str'), |
| 131 |
privilege=dict(required=False, type='str'), |
| 132 |
accept_unknown_host_keys=dict(required=False, type='bool', default=False), |
| 133 |
include_lines=dict(required=False, type='str', default=''), |
| 134 |
exclude_lines=dict(required=False, type='str', default=''), |
| 135 |
service_processor=dict(required=False, type='bool', default=False, aliases=['sp']), |
| 136 |
)) |
| 137 |
self.module = AnsibleModule( |
| 138 |
argument_spec=self.argument_spec, |
| 139 |
supports_check_mode=True |
| 140 |
) |
| 141 |
parameters = self.module.params |
| 142 |
# set up state variables |
| 143 |
self.command = parameters['command'] |
| 144 |
self.privilege = parameters['privilege'] |
| 145 |
self.include_lines = parameters['include_lines'] |
| 146 |
self.exclude_lines = parameters['exclude_lines'] |
| 147 |
self.accept_unknown_host_keys = parameters['accept_unknown_host_keys'] |
| 148 |
self.service_processor = parameters['service_processor'] |
| 149 |
self.warnings = list() |
| 150 |
self.failed = False |
| 151 |
|
| 152 |
if not HAS_PARAMIKO: |
| 153 |
self.module.fail_json(msg="the python paramiko module is required") |
| 154 |
|
| 155 |
client = paramiko.SSHClient() |
| 156 |
client.load_system_host_keys() # load ~/.ssh/known_hosts if it exists |
| 157 |
if self.accept_unknown_host_keys: |
| 158 |
# accept unknown key, but raise a python warning |
| 159 |
client.set_missing_host_key_policy(paramiko.WarningPolicy()) |
| 160 |
|
| 161 |
with warnings.catch_warnings(record=True) as wngs: |
| 162 |
try: |
| 163 |
client.connect(hostname=parameters['hostname'], username=parameters['username'], password=parameters['password']) |
| 164 |
if len(wngs) > 0: |
| 165 |
self.warnings.extend([str(warning.message) for warning in wngs]) |
| 166 |
except paramiko.SSHException as exc: |
| 167 |
self.module.fail_json(msg="SSH connection failed: %s" % repr(exc)) |
| 168 |
|
| 169 |
self.client = client |
| 170 |
|
| 171 |
def parse_output(self, out): |
| 172 |
out_string = out.read() |
| 173 |
# ONTAP makes copious use of \r |
| 174 |
out_string = out_string.replace(b'\r\r\n', b'\n') |
| 175 |
out_string = out_string.replace(b'\r\n', b'\n') |
| 176 |
return out_string |
| 177 |
|
| 178 |
def run_ssh_command(self, command): |
| 179 |
''' calls SSH ''' |
| 180 |
try: |
| 181 |
stdin, stdout, stderr = self.client.exec_command(command) |
| 182 |
except paramiko.SSHException as exc: |
| 183 |
self.module.fail_json(msg='Error running command %s: %s' % |
| 184 |
(command, to_native(exc)), |
| 185 |
exception=traceback.format_exc()) |
| 186 |
stdin.close() # if we don't close, we may see a TypeError |
| 187 |
return stdout, stderr |
| 188 |
|
| 189 |
def filter_output(self, output): |
| 190 |
''' Generate stdout_lines_filtered list |
| 191 |
Remove login information if found in the first non white lines |
| 192 |
''' |
| 193 |
result = list() |
| 194 |
find_banner = True |
| 195 |
for line in output.splitlines(): |
| 196 |
try: |
| 197 |
stripped_line = line.strip().decode() |
| 198 |
except Exception as exc: |
| 199 |
self.warnings.append("Unable to decode ONTAP output. Skipping filtering. Error: %s" % repr(exc)) |
| 200 |
result.append('ERROR: truncated, cannot decode: %s' % line) |
| 201 |
self.failed = False |
| 202 |
return result |
| 203 |
|
| 204 |
if not stripped_line: |
| 205 |
continue |
| 206 |
if find_banner and stripped_line.startswith(('Last login time:', 'Unsuccessful login attempts since last login:')): |
| 207 |
continue |
| 208 |
find_banner = False |
| 209 |
if self.exclude_lines: |
| 210 |
if self.include_lines in stripped_line and self.exclude_lines not in stripped_line: |
| 211 |
result.append(stripped_line) |
| 212 |
elif self.include_lines: |
| 213 |
if self.include_lines in stripped_line: |
| 214 |
result.append(stripped_line) |
| 215 |
else: |
| 216 |
result.append(stripped_line) |
| 217 |
|
| 218 |
return result |
| 219 |
|
| 220 |
def run_command(self): |
| 221 |
''' calls SSH ''' |
| 222 |
command = self.command |
| 223 |
if self.privilege is not None: |
| 224 |
if self.service_processor: |
| 225 |
command = "priv set %s;%s" % (self.privilege, command) |
| 226 |
else: |
| 227 |
command = "set -privilege %s;%s" % (self.privilege, command) |
| 228 |
stdout, stderr = self.run_ssh_command(command) |
| 229 |
stdout_string = self.parse_output(stdout) |
| 230 |
stdout_filtered = self.filter_output(stdout_string) |
| 231 |
return stdout_string, stdout_filtered, self.parse_output(stderr) |
| 232 |
|
| 233 |
def apply(self): |
| 234 |
''' calls the command and returns raw output ''' |
| 235 |
changed = True |
| 236 |
stdout, filtered, stderr = '', '', '' |
| 237 |
if not self.module.check_mode: |
| 238 |
stdout, filtered, stderr = self.run_command() |
| 239 |
if stderr: |
| 240 |
self.failed = True |
| 241 |
self.module.exit_json(changed=changed, failed=self.failed, stdout=stdout, stdout_lines_filtered=filtered, stderr=stderr, warnings=self.warnings) |
| 242 |
|
| 243 |
|
| 244 |
def main(): |
| 245 |
""" |
| 246 |
Execute action from playbook |
| 247 |
""" |
| 248 |
command = NetAppONTAPSSHCommand() |
| 249 |
command.apply() |
| 250 |
|
| 251 |
|
| 252 |
if __name__ == '__main__': |
| 253 |
main() |