| 1 |
#!/usr/bin/python |
| 2 |
''' |
| 3 |
# (c) 2018-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 |
DOCUMENTATION = ''' |
| 11 |
author: NetApp Ansible Team (@carchi8py) <[email protected]> |
| 12 |
description: |
| 13 |
- Run system-cli commands on ONTAP. |
| 14 |
- Can't be used with cert authentication and domain authentication accounts. |
| 15 |
- Requires ontapi and console permissions. Console is not supported for data vservers. |
| 16 |
- Requires write permissions, even for show commands! ONTAP reports |
| 17 |
"Insufficient privileges" and "user 'xxxxx' does not have write access to this resource" |
| 18 |
for a readonly user. |
| 19 |
extends_documentation_fragment: |
| 20 |
- netapp.ontap.netapp.na_ontap_zapi |
| 21 |
module: na_ontap_command |
| 22 |
short_description: NetApp ONTAP Run any cli command, the username provided needs to have console login permission. |
| 23 |
version_added: 2.7.0 |
| 24 |
options: |
| 25 |
command: |
| 26 |
description: |
| 27 |
- a comma separated list containing the command and arguments. |
| 28 |
required: true |
| 29 |
type: list |
| 30 |
elements: str |
| 31 |
privilege: |
| 32 |
description: |
| 33 |
- privilege level at which to run the command. |
| 34 |
choices: ['admin', 'advanced'] |
| 35 |
default: admin |
| 36 |
type: str |
| 37 |
version_added: 2.8.0 |
| 38 |
return_dict: |
| 39 |
description: |
| 40 |
- Returns a parsesable dictionary instead of raw XML output |
| 41 |
- C(result_value) |
| 42 |
- C(status) > passed, failed. |
| 43 |
- C(stdout) > command output in plaintext. |
| 44 |
- C(stdout_lines) > list of command output lines. |
| 45 |
- C(stdout_lines_filter) > empty list or list of command output lines matching I(include_lines) or I(exclude_lines) parameters. |
| 46 |
- C(xml_dict) > JSON representation of what the CLI returned. |
| 47 |
type: bool |
| 48 |
default: false |
| 49 |
version_added: 2.9.0 |
| 50 |
vserver: |
| 51 |
description: |
| 52 |
- If running as vserver admin, you must give a I(vserver) or module will fail |
| 53 |
version_added: "19.10.0" |
| 54 |
type: str |
| 55 |
include_lines: |
| 56 |
description: |
| 57 |
- applied only when I(return_dict) is true |
| 58 |
- return only lines containing string pattern in C(stdout_lines_filter) |
| 59 |
default: '' |
| 60 |
type: str |
| 61 |
version_added: "19.10.0" |
| 62 |
exclude_lines: |
| 63 |
description: |
| 64 |
- applied only when I(return_dict) is true |
| 65 |
- return only lines containing string pattern in C(stdout_lines_filter) |
| 66 |
default: '' |
| 67 |
type: str |
| 68 |
version_added: "19.10.0" |
| 69 |
''' |
| 70 |
|
| 71 |
EXAMPLES = """ |
| 72 |
- name: Run ONTAP CLI command |
| 73 |
netapp.ontap.na_ontap_command: |
| 74 |
username: "{{ netapp_username }}" |
| 75 |
password: "{{ netapp_password }}" |
| 76 |
hostname: "{{ netapp_hostname }}" |
| 77 |
command: ['version'] |
| 78 |
|
| 79 |
# Same as above, but returns parseable dictonary |
| 80 |
- name: Run ONTAP CLI command |
| 81 |
netapp.ontap.na_ontap_command: |
| 82 |
username: "{{ netapp_username }}" |
| 83 |
password: "{{ netapp_password }}" |
| 84 |
hostname: "{{ netapp_hostname }}" |
| 85 |
command: ['node', 'show', '-fields', 'node,health,uptime,model'] |
| 86 |
privilege: 'admin' |
| 87 |
return_dict: true |
| 88 |
|
| 89 |
# Same as above, but with lines filtering |
| 90 |
- name: Run ONTAP CLI command |
| 91 |
netapp.ontap.na_ontap_command: |
| 92 |
username: "{{ netapp_username }}" |
| 93 |
password: "{{ netapp_password }}" |
| 94 |
hostname: "{{ netapp_hostname }}" |
| 95 |
command: ['node', 'show', '-fields', 'node,health,uptime,model'] |
| 96 |
exclude_lines: 'ode ' # Exclude lines with 'Node ' or 'node ', or anything else containing 'ode '. |
| 97 |
privilege: 'admin' |
| 98 |
return_dict: true |
| 99 |
""" |
| 100 |
|
| 101 |
RETURN = """ |
| 102 |
""" |
| 103 |
|
| 104 |
import traceback |
| 105 |
from ansible.module_utils.basic import AnsibleModule |
| 106 |
from ansible.module_utils._text import to_native |
| 107 |
import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils |
| 108 |
|
| 109 |
|
| 110 |
class NetAppONTAPCommand(): |
| 111 |
''' calls a CLI command ''' |
| 112 |
|
| 113 |
def __init__(self): |
| 114 |
self.argument_spec = netapp_utils.na_ontap_zapi_only_spec() |
| 115 |
self.argument_spec.update(dict( |
| 116 |
command=dict(required=True, type='list', elements='str'), |
| 117 |
privilege=dict(required=False, type='str', choices=['admin', 'advanced'], default='admin'), |
| 118 |
return_dict=dict(required=False, type='bool', default=False), |
| 119 |
vserver=dict(required=False, type='str'), |
| 120 |
include_lines=dict(required=False, type='str', default=''), |
| 121 |
exclude_lines=dict(required=False, type='str', default=''), |
| 122 |
)) |
| 123 |
self.module = AnsibleModule( |
| 124 |
argument_spec=self.argument_spec, |
| 125 |
supports_check_mode=True |
| 126 |
) |
| 127 |
parameters = self.module.params |
| 128 |
# set up state variables |
| 129 |
self.command = parameters['command'] |
| 130 |
self.privilege = parameters['privilege'] |
| 131 |
self.vserver = parameters['vserver'] |
| 132 |
self.return_dict = parameters['return_dict'] |
| 133 |
self.include_lines = parameters['include_lines'] |
| 134 |
self.exclude_lines = parameters['exclude_lines'] |
| 135 |
|
| 136 |
self.result_dict = { |
| 137 |
'status': "", |
| 138 |
'result_value': 0, |
| 139 |
'invoked_command': " ".join(self.command), |
| 140 |
'stdout': "", |
| 141 |
'stdout_lines': [], |
| 142 |
'stdout_lines_filter': [], |
| 143 |
'xml_dict': {}, |
| 144 |
} |
| 145 |
self.module.warn('The module only supports ZAPI; refer to netapp.ontap.na_ontap_rest_cli module for RESTful equivalent.') |
| 146 |
|
| 147 |
if not netapp_utils.has_netapp_lib(): |
| 148 |
self.module.fail_json(msg=netapp_utils.netapp_lib_is_required()) |
| 149 |
self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, wrap_zapi=True) |
| 150 |
|
| 151 |
def run_command(self): |
| 152 |
''' calls the ZAPI ''' |
| 153 |
command_obj = netapp_utils.zapi.NaElement("system-cli") |
| 154 |
|
| 155 |
args_obj = netapp_utils.zapi.NaElement("args") |
| 156 |
if self.return_dict: |
| 157 |
args_obj.add_new_child('arg', 'set') |
| 158 |
args_obj.add_new_child('arg', '-showseparator') |
| 159 |
args_obj.add_new_child('arg', '"###"') |
| 160 |
args_obj.add_new_child('arg', ';') |
| 161 |
for arg in self.command: |
| 162 |
args_obj.add_new_child('arg', arg) |
| 163 |
command_obj.add_child_elem(args_obj) |
| 164 |
command_obj.add_new_child('priv', self.privilege) |
| 165 |
|
| 166 |
try: |
| 167 |
output = self.server.invoke_successfully(command_obj, True) |
| 168 |
if self.return_dict: |
| 169 |
# Parseable dict output |
| 170 |
return self.parse_xml_to_dict(output.to_string()) |
| 171 |
else: |
| 172 |
# Raw XML output |
| 173 |
return output.to_string() |
| 174 |
|
| 175 |
except netapp_utils.zapi.NaApiError as error: |
| 176 |
self.module.fail_json(msg='Error running command %s: %s' % |
| 177 |
(self.command, to_native(error)), |
| 178 |
exception=traceback.format_exc()) |
| 179 |
|
| 180 |
def apply(self): |
| 181 |
''' calls the command and returns raw output ''' |
| 182 |
changed = True |
| 183 |
if self.module.check_mode: |
| 184 |
output = "Would run command: '%s'" % str(self.command) |
| 185 |
else: |
| 186 |
output = self.run_command() |
| 187 |
self.module.exit_json(changed=changed, msg=output) |
| 188 |
|
| 189 |
def parse_xml_to_dict(self, xmldata): |
| 190 |
'''Parse raw XML from system-cli and create an Ansible parseable dictonary''' |
| 191 |
xml_import_ok = True |
| 192 |
xml_parse_ok = True |
| 193 |
importing = 'ast' |
| 194 |
|
| 195 |
try: |
| 196 |
import ast |
| 197 |
importing = 'xml.parsers.expat' |
| 198 |
import xml.parsers.expat |
| 199 |
except ImportError: |
| 200 |
self.result_dict['status'] = "XML parsing failed. Cannot import %s!" % importing |
| 201 |
self.result_dict['stdout'] = str(xmldata) |
| 202 |
self.result_dict['result_value'] = -1 |
| 203 |
xml_import_ok = False |
| 204 |
|
| 205 |
if xml_import_ok: |
| 206 |
xml_str = xmldata.decode('utf-8').replace('\n', '---') |
| 207 |
xml_parser = xml.parsers.expat.ParserCreate() |
| 208 |
xml_parser.StartElementHandler = self._start_element |
| 209 |
xml_parser.CharacterDataHandler = self._char_data |
| 210 |
xml_parser.EndElementHandler = self._end_element |
| 211 |
|
| 212 |
try: |
| 213 |
xml_parser.Parse(xml_str) |
| 214 |
except xml.parsers.expat.ExpatError as errcode: |
| 215 |
self.result_dict['status'] = "XML parsing failed: " + str(errcode) |
| 216 |
self.result_dict['stdout'] = str(xmldata) |
| 217 |
self.result_dict['result_value'] = -1 |
| 218 |
xml_parse_ok = False |
| 219 |
|
| 220 |
if xml_parse_ok: |
| 221 |
self.result_dict['status'] = self.result_dict['xml_dict']['results']['attrs']['status'] |
| 222 |
stdout_string = self._format_escaped_data(self.result_dict['xml_dict']['cli-output']['data']) |
| 223 |
self.result_dict['stdout'] = stdout_string |
| 224 |
# Generate stdout_lines list |
| 225 |
for line in stdout_string.split('\n'): |
| 226 |
stripped_line = line.strip() |
| 227 |
if len(stripped_line) > 1: |
| 228 |
self.result_dict['stdout_lines'].append(stripped_line) |
| 229 |
|
| 230 |
# Generate stdout_lines_filter_list |
| 231 |
if self.exclude_lines: |
| 232 |
if self.include_lines in stripped_line and self.exclude_lines not in stripped_line: |
| 233 |
self.result_dict['stdout_lines_filter'].append(stripped_line) |
| 234 |
elif self.include_lines and self.include_lines in stripped_line: |
| 235 |
self.result_dict['stdout_lines_filter'].append(stripped_line) |
| 236 |
|
| 237 |
self.result_dict['xml_dict']['cli-output']['data'] = stdout_string |
| 238 |
cli_result_value = self.result_dict['xml_dict']['cli-result-value']['data'] |
| 239 |
try: |
| 240 |
# get rid of extra quotes "'1'", but maybe "u'1'" or "b'1'" |
| 241 |
cli_result_value = ast.literal_eval(cli_result_value) |
| 242 |
except (SyntaxError, ValueError): |
| 243 |
pass |
| 244 |
try: |
| 245 |
self.result_dict['result_value'] = int(cli_result_value) |
| 246 |
except ValueError: |
| 247 |
self.result_dict['result_value'] = cli_result_value |
| 248 |
|
| 249 |
return self.result_dict |
| 250 |
|
| 251 |
def _start_element(self, name, attrs): |
| 252 |
''' Start XML element ''' |
| 253 |
self.result_dict['xml_dict'][name] = {} |
| 254 |
self.result_dict['xml_dict'][name]['attrs'] = attrs |
| 255 |
self.result_dict['xml_dict'][name]['data'] = "" |
| 256 |
self.result_dict['xml_dict']['active_element'] = name |
| 257 |
self.result_dict['xml_dict']['last_element'] = "" |
| 258 |
|
| 259 |
def _char_data(self, data): |
| 260 |
''' Dump XML elemet data ''' |
| 261 |
self.result_dict['xml_dict'][str(self.result_dict['xml_dict']['active_element'])]['data'] = repr(data) |
| 262 |
|
| 263 |
def _end_element(self, name): |
| 264 |
self.result_dict['xml_dict']['last_element'] = name |
| 265 |
self.result_dict['xml_dict']['active_element'] = "" |
| 266 |
|
| 267 |
@classmethod |
| 268 |
def _format_escaped_data(cls, datastring): |
| 269 |
''' replace helper escape sequences ''' |
| 270 |
formatted_string = datastring.replace('------', '---').replace('---', '\n').replace("###", " ").strip() |
| 271 |
retval_string = "" |
| 272 |
for line in formatted_string.split('\n'): |
| 273 |
stripped_line = line.strip() |
| 274 |
if len(stripped_line) > 1: |
| 275 |
retval_string += stripped_line + "\n" |
| 276 |
return retval_string |
| 277 |
|
| 278 |
|
| 279 |
def main(): |
| 280 |
""" |
| 281 |
Execute action from playbook |
| 282 |
""" |
| 283 |
command = NetAppONTAPCommand() |
| 284 |
command.apply() |
| 285 |
|
| 286 |
|
| 287 |
if __name__ == '__main__': |
| 288 |
main() |