mirror of https://github.com/ansible/ansible.git
parent
d17e7a91b1
commit
8bf069114f
@ -0,0 +1,178 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# (c) 2018-2019, NetApp Inc.
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'certified'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
module: na_ontap_vscan
|
||||
short_description: NetApp ONTAP Vscan enable/disable.
|
||||
extends_documentation_fragment:
|
||||
- netapp.na_ontap
|
||||
version_added: '2.9'
|
||||
author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
|
||||
notes:
|
||||
- on demand task, on_access_policy and scanner_pools must be set up before running this module
|
||||
description:
|
||||
- Enable and Disable Vscan
|
||||
options:
|
||||
enable:
|
||||
description:
|
||||
- Whether to enable to disable a Vscan
|
||||
type: bool
|
||||
default: True
|
||||
|
||||
vserver:
|
||||
description:
|
||||
- the name of the data vserver to use.
|
||||
required: true
|
||||
type: str
|
||||
'''
|
||||
|
||||
EXAMPLES = """
|
||||
- name: Enable Vscan
|
||||
na_ontap_vscan:
|
||||
enable: True
|
||||
username: '{{ netapp_username }}'
|
||||
password: '{{ netapp_password }}'
|
||||
hostname: '{{ netapp_hostname }}'
|
||||
vserver: trident_svm
|
||||
|
||||
- name: Disable Vscan
|
||||
na_ontap_vscan:
|
||||
enable: False
|
||||
username: '{{ netapp_username }}'
|
||||
password: '{{ netapp_password }}'
|
||||
hostname: '{{ netapp_hostname }}'
|
||||
vserver: trident_svm
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
|
||||
"""
|
||||
|
||||
import traceback
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils._text import to_native
|
||||
import ansible.module_utils.netapp as netapp_utils
|
||||
from ansible.module_utils.netapp import OntapRestAPI
|
||||
from ansible.module_utils.netapp_module import NetAppModule
|
||||
|
||||
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
|
||||
|
||||
|
||||
class NetAppOntapVscan(object):
|
||||
def __init__(self):
|
||||
self.use_rest = False
|
||||
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
|
||||
self.argument_spec.update(dict(
|
||||
enable=dict(type='bool', default=True),
|
||||
vserver=dict(required=True, type='str'),
|
||||
))
|
||||
self.module = AnsibleModule(
|
||||
argument_spec=self.argument_spec,
|
||||
supports_check_mode=True
|
||||
)
|
||||
self.na_helper = NetAppModule()
|
||||
self.parameters = self.na_helper.set_parameters(self.module.params)
|
||||
|
||||
# API should be used for ONTAP 9.6 or higher, Zapi for lower version
|
||||
self.restApi = OntapRestAPI(self.module)
|
||||
if self.restApi.is_rest():
|
||||
self.use_rest = True
|
||||
else:
|
||||
if HAS_NETAPP_LIB is False:
|
||||
self.module.fail_json(msg="the python NetApp-Lib module is required")
|
||||
else:
|
||||
self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
|
||||
|
||||
def get_vscan(self):
|
||||
if self.use_rest:
|
||||
params = {'fields': 'svm,enabled',
|
||||
"svm.name": self.parameters['vserver']}
|
||||
api = "protocols/vscan"
|
||||
message, error = self.restApi.get(api, params)
|
||||
if error:
|
||||
self.module.fail_json(msg=error)
|
||||
return message['records'][0]
|
||||
else:
|
||||
vscan_status_iter = netapp_utils.zapi.NaElement('vscan-status-get-iter')
|
||||
vscan_status_info = netapp_utils.zapi.NaElement('vscan-status-info')
|
||||
vscan_status_info.add_new_child('vserver', self.parameters['vserver'])
|
||||
query = netapp_utils.zapi.NaElement('query')
|
||||
query.add_child_elem(vscan_status_info)
|
||||
vscan_status_iter.add_child_elem(query)
|
||||
try:
|
||||
result = self.server.invoke_successfully(vscan_status_iter, True)
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg='Error getting Vscan info for Vserver %s: %s' %
|
||||
(self.parameters['vserver'], to_native(error)),
|
||||
exception=traceback.format_exc())
|
||||
if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
|
||||
return result.get_child_by_name('attributes-list').get_child_by_name('vscan-status-info')
|
||||
|
||||
def enable_vscan(self, uuid=None):
|
||||
if self.use_rest:
|
||||
params = {"svm.name": self.parameters['vserver']}
|
||||
data = {"enabled": self.parameters['enable']}
|
||||
api = "protocols/vscan/" + uuid
|
||||
message, error = self.restApi.patch(api, data, params)
|
||||
if error is not None:
|
||||
self.module.fail_json(msg=error)
|
||||
# self.module.fail_json(msg=repr(self.restApi.errors), log=repr(self.restApi.debug_logs))
|
||||
else:
|
||||
vscan_status_obj = netapp_utils.zapi.NaElement("vscan-status-modify")
|
||||
vscan_status_obj.add_new_child('is-vscan-enabled', str(self.parameters['enable']))
|
||||
try:
|
||||
self.server.invoke_successfully(vscan_status_obj, True)
|
||||
except netapp_utils.zapi.NaApiError as error:
|
||||
self.module.fail_json(msg="Error Enable/Disabling Vscan: %s" % to_native(error), exception=traceback.format_exc())
|
||||
|
||||
def asup_log(self):
|
||||
if self.use_rest:
|
||||
# TODO: logging for Rest
|
||||
return
|
||||
else:
|
||||
# Either we are using ZAPI, or REST failed when it should not
|
||||
try:
|
||||
netapp_utils.ems_log_event("na_ontap_vscan", self.server)
|
||||
except Exception:
|
||||
# TODO: we may fail to connect to REST or ZAPI, the line below shows REST issues only
|
||||
# self.module.fail_json(msg=repr(self.restApi.errors), log=repr(self.restApi.debug_logs))
|
||||
pass
|
||||
|
||||
def apply(self):
|
||||
changed = False
|
||||
self.asup_log()
|
||||
current = self.get_vscan()
|
||||
if self.use_rest:
|
||||
if current['enabled'] != self.parameters['enable']:
|
||||
if not self.module.check_mode:
|
||||
self.enable_vscan(current['svm']['uuid'])
|
||||
changed = True
|
||||
else:
|
||||
if current.get_child_content('is-vscan-enabled') != str(self.parameters['enable']).lower():
|
||||
if not self.module.check_mode:
|
||||
self.enable_vscan()
|
||||
changed = True
|
||||
self.module.exit_json(changed=changed)
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Execute action from playbook
|
||||
"""
|
||||
command = NetAppOntapVscan()
|
||||
command.apply()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -0,0 +1,231 @@
|
||||
# (c) 2018, NetApp, Inc
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
''' unit tests for Ansible module: na_ontap_vscan'''
|
||||
|
||||
from __future__ import print_function
|
||||
import json
|
||||
import pytest
|
||||
|
||||
from units.compat import unittest
|
||||
from units.compat.mock import patch, Mock
|
||||
from ansible.module_utils import basic
|
||||
from ansible.module_utils._text import to_bytes
|
||||
import ansible.module_utils.netapp as netapp_utils
|
||||
|
||||
from ansible.modules.storage.netapp.na_ontap_vscan \
|
||||
import NetAppOntapVscan as vscan_module # module under test
|
||||
|
||||
if not netapp_utils.has_netapp_lib():
|
||||
pytestmark = pytest.mark.skip('skipping as missing required netapp_lib')
|
||||
HAS_NETAPP_ZAPI_MSG = "pip install netapp_lib is required"
|
||||
|
||||
|
||||
# REST API canned responses when mocking send_request
|
||||
SRR = {
|
||||
# common responses
|
||||
'is_rest': (200, None),
|
||||
'is_zapi': (400, "Unreachable"),
|
||||
'empty_good': ({}, None),
|
||||
'end_of_sequence': (None, "Ooops, the UT needs one more SRR response"),
|
||||
'generic_error': (None, "Expected error"),
|
||||
# module specific responses
|
||||
'enabled': ({'records': [{'enabled': True, 'svm': {'uuid': 'testuuid'}}]}, None),
|
||||
'disabled': ({'records': [{'enabled': False, 'svm': {'uuid': 'testuuid'}}]}, None),
|
||||
}
|
||||
|
||||
|
||||
def set_module_args(args):
|
||||
"""prepare arguments so that they will be picked up during module creation"""
|
||||
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
|
||||
basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access
|
||||
|
||||
|
||||
class AnsibleExitJson(Exception):
|
||||
"""Exception class to be raised by module.exit_json and caught by the test case"""
|
||||
pass
|
||||
|
||||
|
||||
class AnsibleFailJson(Exception):
|
||||
"""Exception class to be raised by module.fail_json and caught by the test case"""
|
||||
pass
|
||||
|
||||
|
||||
def exit_json(*args, **kwargs): # pylint: disable=unused-argument
|
||||
"""function to patch over exit_json; package return data into an exception"""
|
||||
if 'changed' not in kwargs:
|
||||
kwargs['changed'] = False
|
||||
raise AnsibleExitJson(kwargs)
|
||||
|
||||
|
||||
def fail_json(*args, **kwargs): # pylint: disable=unused-argument
|
||||
"""function to patch over fail_json; package return data into an exception"""
|
||||
kwargs['failed'] = True
|
||||
raise AnsibleFailJson(kwargs)
|
||||
|
||||
|
||||
class MockONTAPConnection(object):
|
||||
''' mock server connection to ONTAP host '''
|
||||
|
||||
def __init__(self, kind=None, data=None):
|
||||
''' save arguments '''
|
||||
self.kind = kind
|
||||
self.params = data
|
||||
self.xml_in = None
|
||||
self.xml_out = None
|
||||
|
||||
def invoke_successfully(self, xml, enable_tunneling): # pylint: disable=unused-argument
|
||||
''' mock invoke_successfully returning xml data '''
|
||||
self.xml_in = xml
|
||||
if self.kind == 'enable':
|
||||
xml = self.build_vscan_status_info(self.params)
|
||||
self.xml_out = xml
|
||||
return xml
|
||||
|
||||
@staticmethod
|
||||
def build_vscan_status_info(status):
|
||||
xml = netapp_utils.zapi.NaElement('xml')
|
||||
attributes = {'num-records': 1,
|
||||
'attributes-list': {'vscan-status-info': {'is-vscan-enabled': status}}}
|
||||
xml.translate_struct(attributes)
|
||||
return xml
|
||||
|
||||
|
||||
class TestMyModule(unittest.TestCase):
|
||||
''' Unit tests for na_ontap_job_schedule '''
|
||||
|
||||
def setUp(self):
|
||||
self.mock_module_helper = patch.multiple(basic.AnsibleModule,
|
||||
exit_json=exit_json,
|
||||
fail_json=fail_json)
|
||||
self.mock_module_helper.start()
|
||||
self.addCleanup(self.mock_module_helper.stop)
|
||||
|
||||
def mock_args(self):
|
||||
return {
|
||||
'enable': False,
|
||||
'vserver': 'vserver',
|
||||
'hostname': 'test',
|
||||
'username': 'test_user',
|
||||
'password': 'test_pass!'
|
||||
}
|
||||
|
||||
def get_vscan_mock_object(self, type='zapi', kind=None, status=None):
|
||||
vscan_obj = vscan_module()
|
||||
if type == 'zapi':
|
||||
if kind is None:
|
||||
vscan_obj.server = MockONTAPConnection()
|
||||
else:
|
||||
vscan_obj.server = MockONTAPConnection(kind=kind, data=status)
|
||||
# For rest, mocking is achieved through side_effect
|
||||
return vscan_obj
|
||||
|
||||
def test_module_fail_when_required_args_missing(self):
|
||||
''' required arguments are reported as errors '''
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
set_module_args({})
|
||||
vscan_module()
|
||||
print('Info: %s' % exc.value.args[0]['msg'])
|
||||
|
||||
def test_successfully_enable(self):
|
||||
data = self.mock_args()
|
||||
data['enable'] = True
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object('zapi', 'enable', 'false').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
|
||||
def test_idempotently_enable(self):
|
||||
data = self.mock_args()
|
||||
data['enable'] = True
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object('zapi', 'enable', 'true').apply()
|
||||
assert not exc.value.args[0]['changed']
|
||||
|
||||
def test_successfully_disable(self):
|
||||
data = self.mock_args()
|
||||
data['enable'] = False
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object('zapi', 'enable', 'true').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
|
||||
def test_idempotently_disable(self):
|
||||
data = self.mock_args()
|
||||
data['enable'] = False
|
||||
set_module_args(data)
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object('zapi', 'enable', 'false').apply()
|
||||
assert not exc.value.args[0]['changed']
|
||||
|
||||
@patch('ansible.module_utils.netapp.OntapRestAPI.send_request')
|
||||
def test_rest_error(self, mock_request):
|
||||
data = self.mock_args()
|
||||
set_module_args(data)
|
||||
mock_request.side_effect = [
|
||||
SRR['is_rest'],
|
||||
SRR['generic_error'],
|
||||
SRR['end_of_sequence']
|
||||
]
|
||||
with pytest.raises(AnsibleFailJson) as exc:
|
||||
self.get_vscan_mock_object(type='rest').apply()
|
||||
assert exc.value.args[0]['msg'] == SRR['generic_error'][1]
|
||||
|
||||
@patch('ansible.module_utils.netapp.OntapRestAPI.send_request')
|
||||
def test_rest_successly_enable(self, mock_request):
|
||||
data = self.mock_args()
|
||||
data['enable'] = True
|
||||
set_module_args(data)
|
||||
mock_request.side_effect = [
|
||||
SRR['is_rest'],
|
||||
SRR['disabled'],
|
||||
SRR['empty_good'],
|
||||
SRR['end_of_sequence']
|
||||
]
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object(type='rest').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
|
||||
@patch('ansible.module_utils.netapp.OntapRestAPI.send_request')
|
||||
def test_rest_idempotently_enable(self, mock_request):
|
||||
data = self.mock_args()
|
||||
data['enable'] = True
|
||||
set_module_args(data)
|
||||
mock_request.side_effect = [
|
||||
SRR['is_rest'],
|
||||
SRR['enabled'],
|
||||
SRR['end_of_sequence']
|
||||
]
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object(type='rest').apply()
|
||||
assert not exc.value.args[0]['changed']
|
||||
|
||||
@patch('ansible.module_utils.netapp.OntapRestAPI.send_request')
|
||||
def test_rest_successly_disable(self, mock_request):
|
||||
data = self.mock_args()
|
||||
data['enable'] = False
|
||||
set_module_args(data)
|
||||
mock_request.side_effect = [
|
||||
SRR['is_rest'],
|
||||
SRR['enabled'],
|
||||
SRR['empty_good'],
|
||||
SRR['end_of_sequence']
|
||||
]
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object(type='rest').apply()
|
||||
assert exc.value.args[0]['changed']
|
||||
|
||||
@patch('ansible.module_utils.netapp.OntapRestAPI.send_request')
|
||||
def test_rest_idempotently_disable(self, mock_request):
|
||||
data = self.mock_args()
|
||||
data['enable'] = False
|
||||
set_module_args(data)
|
||||
mock_request.side_effect = [
|
||||
SRR['is_rest'],
|
||||
SRR['disabled'],
|
||||
SRR['end_of_sequence']
|
||||
]
|
||||
with pytest.raises(AnsibleExitJson) as exc:
|
||||
self.get_vscan_mock_object(type='rest').apply()
|
||||
assert not exc.value.args[0]['changed']
|
Loading…
Reference in New Issue