1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

New Module: Ontap Igroup initiator (#52281)

* Revert "changes to clusteR"

This reverts commit 33ee1b71e4bc8435fb315762a871f8c4cb6c5f80.

* Add igroup initiator

* fix author

* Revert "Revert "changes to clusteR""

This reverts commit 2c517792115179665d43d74780dc356ca41b9abe.
This commit is contained in:
Chris Archibald 2019-02-21 08:02:32 -08:00 committed by John R Barker
parent fde2e2d195
commit fdc3f16bba
2 changed files with 385 additions and 0 deletions

View file

@ -0,0 +1,181 @@
#!/usr/bin/python
''' This is an Ansible module for ONTAP, to manage initiators in an Igroup
(c) 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': 'community'
}
DOCUMENTATION = '''
module: na_ontap_igroup_initiator
short_description: NetApp ONTAP igroup initiator configuration
extends_documentation_fragment:
- netapp.na_ontap
version_added: '2.8'
author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
description:
- Add/Remove initiators from an igroup
options:
state:
description:
- Whether the specified initiator should exist or not in an igroup.
choices: ['present', 'absent']
default: present
names:
description:
- List of initiators to manage.
required: true
aliases:
- name
initiator_group:
description:
- Name of the initiator group to which the initiator belongs.
required: true
vserver:
description:
- The name of the vserver to use.
required: true
'''
EXAMPLES = '''
- name: Add initiators to an igroup
na_ontap_igroup_initiator:
names: abc.test:def.com, def.test:efg.com
initiator_group: test_group
vserver: ansibleVServer
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
- name: Remove an initiator from an igroup
na_ontap_igroup_initiator:
state: absent
name: abc.test:def.com
initiator_group: test_group
vserver: ansibleVServer
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
'''
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_module import NetAppModule
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
class NetAppOntapIgroupInitiator(object):
def __init__(self):
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
self.argument_spec.update(dict(
state=dict(required=False, choices=['present', 'absent'], default='present'),
names=dict(required=True, type='list', aliases=['name']),
initiator_group=dict(required=True, type='str'),
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)
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_initiators(self):
"""
Get the existing list of initiators from an igroup
:rtype: list() or None
"""
igroup_info = netapp_utils.zapi.NaElement('igroup-get-iter')
attributes = dict(query={'initiator-group-info': {'initiator-group-name': self.parameters['initiator_group']}})
igroup_info.translate_struct(attributes)
result, current = None, []
try:
result = self.server.invoke_successfully(igroup_info, True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error fetching igroup info %s: %s' % (self.parameters['initiator_group'],
to_native(error)),
exception=traceback.format_exc())
if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
igroup_info = result.get_child_by_name('attributes-list').get_child_by_name('initiator-group-info')
if igroup_info.get_child_by_name('initiators') is not None:
current = [initiator['initiator-name'] for initiator in igroup_info['initiators'].get_children()]
return current
def modify_initiator(self, initiator_name, zapi):
"""
Add or remove an initiator to/from an igroup
"""
options = {'initiator-group-name': self.parameters['initiator_group'],
'initiator': initiator_name}
initiator_modify = netapp_utils.zapi.NaElement.create_node_with_children(zapi, **options)
try:
self.server.invoke_successfully(initiator_modify, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error modifying igroup initiator %s: %s' % (initiator_name,
to_native(error)),
exception=traceback.format_exc())
def autosupport_log(self):
netapp_utils.ems_log_event("na_ontap_igroup_initiator", self.server)
def apply(self):
self.autosupport_log()
initiators, present = self.get_initiators(), None
for initiator in self.parameters['names']:
if initiator in initiators:
present = True
cd_action = self.na_helper.get_cd_action(present, self.parameters)
if self.na_helper.changed:
if self.module.check_mode:
pass
else:
if cd_action == 'create':
self.modify_initiator(initiator, 'igroup-add')
elif cd_action == 'delete':
self.modify_initiator(initiator, 'igroup-remove')
self.module.exit_json(changed=self.na_helper.changed)
def main():
obj = NetAppOntapIgroupInitiator()
obj.apply()
if __name__ == '__main__':
main()

View file

@ -0,0 +1,204 @@
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
''' unit test template for ONTAP Ansible module '''
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_igroup_initiator \
import NetAppOntapIgroupInitiator as initiator # module under test
if not netapp_utils.has_netapp_lib():
pytestmark = pytest.mark.skip('skipping as missing required netapp_lib')
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.data = 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 == 'initiator':
xml = self.build_igroup_initiator()
self.xml_out = xml
return xml
@staticmethod
def build_igroup_initiator():
''' build xml data for initiator '''
xml = netapp_utils.zapi.NaElement('xml')
attributes = {
'num-records': 1,
'attributes-list': {
'initiator-group-info': {
'initiators': [
{'initiator-info': {
'initiator-name': 'init1'
}},
{'initiator-info': {
'initiator-name': 'init2'
}}
]
}
}
}
xml.translate_struct(attributes)
return xml
class TestMyModule(unittest.TestCase):
''' a group of related Unit Tests '''
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)
self.server = MockONTAPConnection()
def mock_args(self):
return {
'vserver': 'vserver',
'name': 'init1',
'initiator_group': 'test',
'hostname': 'hostname',
'username': 'username',
'password': 'password'
}
def get_initiator_mock_object(self, kind=None):
"""
Helper method to return an na_ontap_initiator object
:param kind: passes this param to MockONTAPConnection()
:return: na_ontap_initiator object
"""
obj = initiator()
obj.autosupport_log = Mock(return_value=None)
if kind is None:
obj.server = MockONTAPConnection()
else:
obj.server = MockONTAPConnection(kind=kind)
return 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({})
initiator()
def test_get_nonexistent_initiator(self):
''' Test if get_initiators returns None for non-existent initiator '''
data = self.mock_args()
data['name'] = 'idontexist'
set_module_args(data)
result = self.get_initiator_mock_object('initiator').get_initiators()
assert data['name'] not in result
def test_get_nonexistent_igroup(self):
''' Test if get_initiators returns None for non-existent igroup '''
data = self.mock_args()
data['name'] = 'idontexist'
set_module_args(data)
result = self.get_initiator_mock_object().get_initiators()
assert result == []
def test_get_existing_initiator(self):
''' Test if get_initiator returns None for existing initiator '''
data = self.mock_args()
set_module_args(data)
result = self.get_initiator_mock_object(kind='initiator').get_initiators()
assert data['name'] in result
assert result == ['init1', 'init2'] # from build_igroup_initiators()
def test_successful_add(self):
''' Test successful add'''
data = self.mock_args()
data['name'] = 'iamnew'
set_module_args(data)
obj = self.get_initiator_mock_object('initiator')
with pytest.raises(AnsibleExitJson) as exc:
current = obj.get_initiators()
obj.apply()
assert data['name'] not in current
assert exc.value.args[0]['changed']
def test_successful_add_idempotency(self):
''' Test successful add idempotency '''
data = self.mock_args()
set_module_args(data)
obj = self.get_initiator_mock_object('initiator')
with pytest.raises(AnsibleExitJson) as exc:
current_list = obj.get_initiators()
obj.apply()
assert data['name'] in current_list
assert not exc.value.args[0]['changed']
def test_successful_remove(self):
''' Test successful remove '''
data = self.mock_args()
data['state'] = 'absent'
set_module_args(data)
obj = self.get_initiator_mock_object('initiator')
with pytest.raises(AnsibleExitJson) as exc:
current_list = obj.get_initiators()
obj.apply()
assert data['name'] in current_list
assert exc.value.args[0]['changed']
def test_successful_remove_idempotency(self):
''' Test successful remove idempotency'''
data = self.mock_args()
data['state'] = 'absent'
data['name'] = 'alreadyremoved'
set_module_args(data)
obj = self.get_initiator_mock_object('initiator')
with pytest.raises(AnsibleExitJson) as exc:
current_list = obj.get_initiators()
obj.apply()
assert data['name'] not in current_list
assert not exc.value.args[0]['changed']