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: Na_ontap_unix_user (#50888)

* Revert "changes to clusteR"

This reverts commit 33ee1b71e4bc8435fb315762a871f8c4cb6c5f80.

* new module na_ontap_unix_user

* update modules

* Update author

* Fix author line

* add na_ontap_unix_user to no-get-exception exception list

* Remove no-get-exception line

* updates

* Revert "updates"

This reverts commit 6771b7fdd78c9f8f7f6fb0fda0858b888c7b753e.

* Revert "Revert "changes to clusteR""

This reverts commit b4b9f9dcc3449deb43d00bf09c4f428559b6ccc0.
This commit is contained in:
Chris Archibald 2019-02-19 06:36:49 -08:00 committed by John R Barker
parent 0c76d8db08
commit c9eb186a94
2 changed files with 535 additions and 0 deletions

View file

@ -0,0 +1,253 @@
#!/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': 'community'}
DOCUMENTATION = '''
module: na_ontap_unix_user
short_description: NetApp ONTAP UNIX users
extends_documentation_fragment:
- netapp.na_ontap
version_added: '2.8'
author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
description:
- Create, delete or modify UNIX users local to ONTAP.
options:
state:
description:
- Whether the specified user should exist or not.
choices: ['present', 'absent']
default: 'present'
name:
description:
- Specifies user's UNIX account name.
- Non-modifiable.
required: true
group_id:
description:
- Specifies the primary group identification number for the UNIX user
- Required for create, modifiable.
vserver:
description:
- Specifies the Vserver for the UNIX user.
- Non-modifiable.
required: true
id:
description:
- Specifies an identification number for the UNIX user.
- Required for create, modifiable.
full_name:
description:
- Specifies the full name of the UNIX user
- Optional for create, modifiable.
'''
EXAMPLES = """
- name: Create UNIX User
na_ontap_unix_user:
state: present
name: SampleUser
vserver: ansibleVServer
group_id: 1
id: 2
full_name: Test User
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
- name: Delete UNIX User
na_ontap_unix_user:
state: absent
name: SampleUser
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 NetAppOntapUnixUser(object):
"""
Common operations to manage users and roles.
"""
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'),
group_id=dict(required=False, type='int'),
id=dict(required=False, type='int'),
full_name=dict(required=False, 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_unix_user(self):
"""
Checks if the UNIX user exists.
:return:
dict() if user found
None if user is not found
"""
get_unix_user = netapp_utils.zapi.NaElement('name-mapping-unix-user-get-iter')
attributes = {
'query': {
'unix-user-info': {
'user-name': self.parameters['name'],
'vserver': self.parameters['vserver'],
}
}
}
get_unix_user.translate_struct(attributes)
try:
result = self.server.invoke_successfully(get_unix_user, enable_tunneling=True)
if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
user_info = result['attributes-list']['unix-user-info']
return {'group_id': int(user_info['group-id']),
'id': int(user_info['user-id']),
'full_name': user_info['full-name']}
return None
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error getting UNIX user %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def create_unix_user(self):
"""
Creates an UNIX user in the specified Vserver
:return: None
"""
if self.parameters.get('group_id') is None or self.parameters.get('id') is None:
self.module.fail_json(msg='Error: Missing one or more required parameters for create: (group_id, id)')
user_create = netapp_utils.zapi.NaElement.create_node_with_children(
'name-mapping-unix-user-create', **{'user-name': self.parameters['name'],
'group-id': str(self.parameters['group_id']),
'user-id': str(self.parameters['id'])})
if self.parameters.get('full_name') is not None:
user_create.add_new_child('full-name', self.parameters['full_name'])
try:
self.server.invoke_successfully(user_create, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error creating UNIX user %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def delete_unix_user(self):
"""
Deletes an UNIX user from a vserver
:return: None
"""
user_delete = netapp_utils.zapi.NaElement.create_node_with_children(
'name-mapping-unix-user-destroy', **{'user-name': self.parameters['name']})
try:
self.server.invoke_successfully(user_delete, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error removing UNIX user %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def modify_unix_user(self, params):
user_modify = netapp_utils.zapi.NaElement.create_node_with_children(
'name-mapping-unix-user-modify', **{'user-name': self.parameters['name']})
for key in params:
if key == 'group_id':
user_modify.add_new_child('group-id', str(params['group_id']))
if key == 'id':
user_modify.add_new_child('user-id', str(params['id']))
if key == 'full_name':
user_modify.add_new_child('full-name', params['full_name'])
try:
self.server.invoke_successfully(user_modify, enable_tunneling=True)
except netapp_utils.zapi.NaApiError as error:
self.module.fail_json(msg='Error modifying UNIX user %s: %s' % (self.parameters['name'], to_native(error)),
exception=traceback.format_exc())
def autosupport_log(self):
"""
Autosupport log for unix_user
:return: None
"""
netapp_utils.ems_log_event("na_ontap_unix_user", self.server)
def apply(self):
"""
Invoke appropriate action based on playbook parameters
:return: None
"""
self.autosupport_log()
current = self.get_unix_user()
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_user()
elif cd_action == 'delete':
self.delete_unix_user()
else:
self.modify_unix_user(modify)
self.module.exit_json(changed=self.na_helper.changed)
def main():
obj = NetAppOntapUnixUser()
obj.apply()
if __name__ == '__main__':
main()

View file

@ -0,0 +1,282 @@
# (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_user \
import NetAppOntapUnixUser as user_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 == 'user':
xml = self.build_user_info(self.params)
elif self.kind == 'user-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_user_info(data):
''' build xml data for vserser-info '''
xml = netapp_utils.zapi.NaElement('xml')
attributes = \
{'attributes-list': {'unix-user-info': {'user-id': data['id'],
'group-id': data['group_id'], 'full-name': data['full_name']}},
'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_user = {
'name': 'test',
'id': '11',
'group_id': '12',
'vserver': 'something',
'full_name': 'Test User'
}
def mock_args(self):
return {
'name': self.mock_user['name'],
'group_id': self.mock_user['group_id'],
'id': self.mock_user['id'],
'vserver': self.mock_user['vserver'],
'full_name': self.mock_user['full_name'],
'hostname': 'test',
'username': 'test_user',
'password': 'test_pass!'
}
def get_user_mock_object(self, kind=None, data=None):
"""
Helper method to return an na_ontap_unix_user object
:param kind: passes this param to MockONTAPConnection()
:return: na_ontap_unix_user object
"""
obj = user_module()
obj.autosupport_log = Mock(return_value=None)
if data is None:
data = self.mock_user
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({})
user_module()
def test_get_nonexistent_user(self):
''' Test if get_unix_user returns None for non-existent user '''
set_module_args(self.mock_args())
result = self.get_user_mock_object().get_unix_user()
assert result is None
def test_get_existing_user(self):
''' Test if get_unix_user returns details for existing user '''
set_module_args(self.mock_args())
result = self.get_user_mock_object('user').get_unix_user()
assert result['full_name'] == self.mock_user['full_name']
def test_get_xml(self):
set_module_args(self.mock_args())
obj = self.get_user_mock_object('user')
result = obj.get_unix_user()
assert obj.server.xml_in['query']
assert obj.server.xml_in['query']['unix-user-info']
user_info = obj.server.xml_in['query']['unix-user-info']
assert user_info['user-name'] == self.mock_user['name']
assert user_info['vserver'] == self.mock_user['vserver']
def test_create_error_missing_params(self):
data = self.mock_args()
del data['group_id']
set_module_args(data)
with pytest.raises(AnsibleFailJson) as exc:
self.get_user_mock_object('user').create_unix_user()
assert 'Error: Missing one or more required parameters for create: (group_id, id)' == exc.value.args[0]['msg']
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.create_unix_user')
def test_create_called(self, create_user):
set_module_args(self.mock_args())
with pytest.raises(AnsibleExitJson) as exc:
self.get_user_mock_object().apply()
assert exc.value.args[0]['changed']
create_user.assert_called_with()
def test_create_xml(self):
'''Test create ZAPI element'''
set_module_args(self.mock_args())
create = self.get_user_mock_object()
with pytest.raises(AnsibleExitJson) as exc:
create.apply()
mock_key = {
'user-name': 'name',
'group-id': 'group_id',
'user-id': 'id',
'full-name': 'full_name'
}
for key in ['user-name', 'user-id', 'group-id', 'full-name']:
assert create.server.xml_in[key] == self.mock_user[mock_key[key]]
def test_create_wihtout_full_name(self):
'''Test create ZAPI element'''
data = self.mock_args()
del data['full_name']
set_module_args(data)
create = self.get_user_mock_object()
with pytest.raises(AnsibleExitJson) as exc:
create.apply()
with pytest.raises(KeyError):
create.server.xml_in['full-name']
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.modify_unix_user')
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.delete_unix_user')
def test_delete_called(self, delete_user, modify_user):
''' Test delete existing user '''
data = self.mock_args()
data['state'] = 'absent'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_user_mock_object('user').apply()
assert exc.value.args[0]['changed']
delete_user.assert_called_with()
assert modify_user.call_count == 0
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.get_unix_user')
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.modify_unix_user')
def test_modify_called(self, modify_user, get_user):
''' Test modify user group_id '''
data = self.mock_args()
data['group_id'] = 20
set_module_args(data)
get_user.return_value = {'group_id': 10}
obj = self.get_user_mock_object('user')
with pytest.raises(AnsibleExitJson) as exc:
obj.apply()
get_user.assert_called_with()
modify_user.assert_called_with({'group_id': 20})
def test_modify_only_id(self):
''' Test modify user id '''
set_module_args(self.mock_args())
modify = self.get_user_mock_object('user')
modify.modify_unix_user({'id': 123})
assert modify.server.xml_in['user-id'] == '123'
with pytest.raises(KeyError):
modify.server.xml_in['group-id']
with pytest.raises(KeyError):
modify.server.xml_in['full-name']
def test_modify_xml(self):
''' Test modify user full_name '''
set_module_args(self.mock_args())
modify = self.get_user_mock_object('user')
modify.modify_unix_user({'full_name': 'New Name',
'group_id': '25'})
assert modify.server.xml_in['user-name'] == self.mock_user['name']
assert modify.server.xml_in['full-name'] == 'New Name'
assert modify.server.xml_in['group-id'] == '25'
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.create_unix_user')
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.delete_unix_user')
@patch('ansible.modules.storage.netapp.na_ontap_unix_user.NetAppOntapUnixUser.modify_unix_user')
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_user_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_user_mock_object('user-fail').get_unix_user()
assert 'Error getting UNIX user' 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_user_mock_object('user-fail').create_unix_user()
assert 'Error creating UNIX user' 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_user_mock_object('user-fail').modify_unix_user({'id': '123'})
assert 'Error modifying UNIX user' 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_user_mock_object('user-fail').delete_unix_user()
assert 'Error removing UNIX user' in exc.value.args[0]['msg']