New Modules: na_ontap_unix_group (#51390)

* changes to clusteR

* Revert "changes to clusteR"

This reverts commit 33ee1b71e4bc8435fb315762a871f8c4cb6c5f80.

* add new module ontap_unix_groups
This commit is contained in:
Chris Archibald 2019-02-12 07:06:28 -08:00 committed by John R Barker
parent af710bd048
commit ce092ed939
2 changed files with 529 additions and 0 deletions

View file

@ -0,0 +1,267 @@
#!/usr/bin/python
"""
create Autosupport module to enable, disable or modify
"""
# (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 = """
author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
description:
- "Create/Delete Unix user group"
extends_documentation_fragment:
- netapp.na_ontap
module: na_ontap_unix_group
options:
state:
description:
- Whether the specified group should exist or not.
choices: ['present', 'absent']
default: 'present'
name:
description:
- Specifies UNIX group's name, unique for each group.
- Non-modifiable.
required: true
id:
description:
- Specifies an identification number for the UNIX group.
- Group ID is unique for each UNIX group.
- Required for create, modifiable.
vserver:
description:
- Specifies the Vserver for the UNIX group.
- Non-modifiable.
required: true
skip_name_validation:
description:
- Specifies if group name validation is skipped.
type: bool
short_description: NetApp ONTAP UNIX Group
version_added: "2.8"
"""
EXAMPLES = """
- name: Create UNIX group
na_ontap_unix_group:
state: present
name: SampleGroup
vserver: ansibleVServer
id: 2
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
- name: Delete UNIX group
na_ontap_unix_group:
state: absent
name: SampleGroup
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 NetAppOntapUnixGroup(object):
"""
Common operations to manage UNIX groups
"""
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'),
name=dict(required=True, type='str'),
id=dict(required=False, type='int'),
skip_name_validation=dict(required=False, type='bool'),
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)
self.set_playbook_zapi_key_map()
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 set_playbook_zapi_key_map(self):
self.na_helper.zapi_string_keys = {
'name': 'group-name'
}
self.na_helper.zapi_int_keys = {
'id': 'group-id'
}
self.na_helper.zapi_bool_keys = {
'skip_name_validation': 'skip-name-validation'
}
def get_unix_group(self):
"""
Checks if the UNIX group exists.
:return:
dict() if group found
None if group is not found
"""
get_unix_group = netapp_utils.zapi.NaElement('name-mapping-unix-group-get-iter')
attributes = {
'query': {
'unix-group-info': {
'group-name': self.parameters['name'],
'vserver': self.parameters['vserver'],
}
}
}
get_unix_group.translate_struct(attributes)
try:
result = self.server.invoke_successfully(get_unix_group, enable_tunneling=True)
if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
group_info = result['attributes-list']['unix-group-info']
group_details = dict()
else:
return None
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error getting UNIX group %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
for item_key, zapi_key in self.na_helper.zapi_string_keys.items():
group_details[item_key] = group_info[zapi_key]
for item_key, zapi_key in self.na_helper.zapi_int_keys.items():
group_details[item_key] = self.na_helper.get_value_for_int(from_zapi=True,
value=group_info[zapi_key])
return group_details
def create_unix_group(self):
"""
Creates an UNIX group in the specified Vserver
:return: None
"""
if self.parameters.get('id') is None:
self.module.fail_json(msg='Error: Missing a required parameter for create: (id)')
group_create = netapp_utils.zapi.NaElement('name-mapping-unix-group-create')
group_details = {}
for item in self.parameters:
if item in self.na_helper.zapi_string_keys:
zapi_key = self.na_helper.zapi_string_keys.get(item)
group_details[zapi_key] = self.parameters[item]
elif item in self.na_helper.zapi_bool_keys:
zapi_key = self.na_helper.zapi_bool_keys.get(item)
group_details[zapi_key] = self.na_helper.get_value_for_bool(from_zapi=False,
value=self.parameters[item])
elif item in self.na_helper.zapi_int_keys:
zapi_key = self.na_helper.zapi_int_keys.get(item)
group_details[zapi_key] = self.na_helper.get_value_for_int(from_zapi=True,
value=self.parameters[item])
group_create.translate_struct(group_details)
try:
self.server.invoke_successfully(group_create, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error creating UNIX group %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def delete_unix_group(self):
"""
Deletes an UNIX group from a vserver
:return: None
"""
group_delete = netapp_utils.zapi.NaElement.create_node_with_children(
'name-mapping-unix-group-destroy', **{'group-name': self.parameters['name']})
try:
self.server.invoke_successfully(group_delete, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error removing UNIX group %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def modify_unix_group(self, params):
group_modify = netapp_utils.zapi.NaElement('name-mapping-unix-group-modify')
group_details = {'group-name': self.parameters['name']}
for key in params:
if key in self.na_helper.zapi_int_keys:
zapi_key = self.na_helper.zapi_int_keys.get(key)
group_details[zapi_key] = self.na_helper.get_value_for_int(from_zapi=True,
value=params[key])
group_modify.translate_struct(group_details)
try:
self.server.invoke_successfully(group_modify, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error modifying UNIX group %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def autosupport_log(self):
"""
Autosupport log for unix_group
:return: None
"""
netapp_utils.ems_log_event("na_ontap_unix_group", self.server)
def apply(self):
"""
Invoke appropriate action based on playbook parameters
:return: None
"""
self.autosupport_log()
current = self.get_unix_group()
cd_action = self.na_helper.get_cd_action(current, self.parameters)
if self.parameters['state'] == 'present' and cd_action is None:
modify = self.na_helper.get_modified_attributes(current, self.parameters)
if self.na_helper.changed:
if self.module.check_mode:
pass
else:
if cd_action == 'create':
self.create_unix_group()
elif cd_action == 'delete':
self.delete_unix_group()
else:
self.modify_unix_group(modify)
self.module.exit_json(changed=self.na_helper.changed)
def main():
obj = NetAppOntapUnixGroup()
obj.apply()
if __name__ == '__main__':
main()

View file

@ -0,0 +1,262 @@
# (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_unix_group \
import NetAppOntapUnixGroup as group_module # 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.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 == 'group':
xml = self.build_group_info(self.params)
elif self.kind == 'group-fail':
raise netapp_utils.zapi.NaApiError(code='TEST', message="This exception is from the unit test")
self.xml_out = xml
return xml
@staticmethod
def build_group_info(data):
''' build xml data for vserser-info '''
xml = netapp_utils.zapi.NaElement('xml')
attributes = \
{'attributes-list': {'unix-group-info': {'group-name': data['name'],
'group-id': data['id']}},
'num-records': 1}
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()
self.mock_group = {
'name': 'test',
'id': '11',
'vserver': 'something',
}
def mock_args(self):
return {
'name': self.mock_group['name'],
'id': self.mock_group['id'],
'vserver': self.mock_group['vserver'],
'hostname': 'test',
'username': 'test_user',
'password': 'test_pass!'
}
def get_group_mock_object(self, kind=None, data=None):
"""
Helper method to return an na_ontap_unix_group object
:param kind: passes this param to MockONTAPConnection()
:return: na_ontap_unix_group object
"""
obj = group_module()
obj.autosupport_log = Mock(return_value=None)
if data is None:
data = self.mock_group
obj.server = MockONTAPConnection(kind=kind, data=data)
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({})
group_module()
def test_get_nonexistent_group(self):
''' Test if get_unix_group returns None for non-existent group '''
set_module_args(self.mock_args())
result = self.get_group_mock_object().get_unix_group()
assert result is None
def test_get_existing_group(self):
''' Test if get_unix_group returns details for existing group '''
set_module_args(self.mock_args())
result = self.get_group_mock_object('group').get_unix_group()
assert result['name'] == self.mock_group['name']
def test_get_xml(self):
set_module_args(self.mock_args())
obj = self.get_group_mock_object('group')
result = obj.get_unix_group()
assert obj.server.xml_in['query']
assert obj.server.xml_in['query']['unix-group-info']
group_info = obj.server.xml_in['query']['unix-group-info']
assert group_info['group-name'] == self.mock_group['name']
assert group_info['vserver'] == self.mock_group['vserver']
def test_create_error_missing_params(self):
data = self.mock_args()
del data['id']
set_module_args(data)
with pytest.raises(AnsibleFailJson) as exc:
self.get_group_mock_object('group').create_unix_group()
assert 'Error: Missing a required parameter for create: (id)' == exc.value.args[0]['msg']
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.create_unix_group')
def test_create_called(self, create_group):
set_module_args(self.mock_args())
with pytest.raises(AnsibleExitJson) as exc:
self.get_group_mock_object().apply()
assert exc.value.args[0]['changed']
create_group.assert_called_with()
def test_create_xml(self):
'''Test create ZAPI element'''
set_module_args(self.mock_args())
create = self.get_group_mock_object()
with pytest.raises(AnsibleExitJson) as exc:
create.apply()
mock_key = {
'group-name': 'name',
'group-id': 'id',
}
for key in ['group-name', 'group-id']:
assert create.server.xml_in[key] == self.mock_group[mock_key[key]]
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.modify_unix_group')
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.delete_unix_group')
def test_delete_called(self, delete_group, modify_group):
''' Test delete existing group '''
data = self.mock_args()
data['state'] = 'absent'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_group_mock_object('group').apply()
assert exc.value.args[0]['changed']
delete_group.assert_called_with()
assert modify_group.call_count == 0
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.get_unix_group')
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.modify_unix_group')
def test_modify_called(self, modify_group, get_group):
''' Test modify group group_id '''
data = self.mock_args()
data['id'] = 20
set_module_args(data)
get_group.return_value = {'id': 10}
obj = self.get_group_mock_object('group')
with pytest.raises(AnsibleExitJson) as exc:
obj.apply()
get_group.assert_called_with()
modify_group.assert_called_with({'id': 20})
def test_modify_only_id(self):
''' Test modify group id '''
set_module_args(self.mock_args())
modify = self.get_group_mock_object('group')
modify.modify_unix_group({'id': 123})
print(modify.server.xml_in.to_string())
assert modify.server.xml_in['group-id'] == '123'
with pytest.raises(KeyError):
modify.server.xml_in['id']
def test_modify_xml(self):
''' Test modify group full_name '''
set_module_args(self.mock_args())
modify = self.get_group_mock_object('group')
modify.modify_unix_group({'id': 25})
assert modify.server.xml_in['group-name'] == self.mock_group['name']
assert modify.server.xml_in['group-id'] == '25'
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.create_unix_group')
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.delete_unix_group')
@patch('ansible.modules.storage.netapp.na_ontap_unix_group.NetAppOntapUnixGroup.modify_unix_group')
def test_do_nothing(self, modify, delete, create):
''' changed is False and none of the opetaion methods are called'''
data = self.mock_args()
data['state'] = 'absent'
set_module_args(data)
obj = self.get_group_mock_object()
with pytest.raises(AnsibleExitJson) as exc:
obj.apply()
create.assert_not_called()
delete.assert_not_called()
modify.assert_not_called()
def test_get_exception(self):
set_module_args(self.mock_args())
with pytest.raises(AnsibleFailJson) as exc:
self.get_group_mock_object('group-fail').get_unix_group()
assert 'Error getting UNIX group' in exc.value.args[0]['msg']
def test_create_exception(self):
set_module_args(self.mock_args())
with pytest.raises(AnsibleFailJson) as exc:
self.get_group_mock_object('group-fail').create_unix_group()
assert 'Error creating UNIX group' in exc.value.args[0]['msg']
def test_modify_exception(self):
set_module_args(self.mock_args())
with pytest.raises(AnsibleFailJson) as exc:
self.get_group_mock_object('group-fail').modify_unix_group({'id': '123'})
assert 'Error modifying UNIX group' in exc.value.args[0]['msg']
def test_delete_exception(self):
set_module_args(self.mock_args())
with pytest.raises(AnsibleFailJson) as exc:
self.get_group_mock_object('group-fail').delete_unix_group()
assert 'Error removing UNIX group' in exc.value.args[0]['msg']