From becca36c5e3bfc8f9318807ce13eea14db863ca0 Mon Sep 17 00:00:00 2001 From: Wojciech Wypior Date: Fri, 21 Jun 2019 14:45:30 +0100 Subject: [PATCH] Added new module for remote user management (#58171) --- .../modules/network/f5/bigip_remote_user.py | 391 ++++++++++++++++++ .../fixtures/load_remote_user_settings.json | 10 + .../network/f5/test_bigip_remote_user.py | 128 ++++++ 3 files changed, 529 insertions(+) create mode 100644 lib/ansible/modules/network/f5/bigip_remote_user.py create mode 100644 test/units/modules/network/f5/fixtures/load_remote_user_settings.json create mode 100644 test/units/modules/network/f5/test_bigip_remote_user.py diff --git a/lib/ansible/modules/network/f5/bigip_remote_user.py b/lib/ansible/modules/network/f5/bigip_remote_user.py new file mode 100644 index 00000000000..beaab5db0f2 --- /dev/null +++ b/lib/ansible/modules/network/f5/bigip_remote_user.py @@ -0,0 +1,391 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2019, F5 Networks 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 = r''' +--- +module: bigip_remote_user +short_description: Manages default settings for remote user accounts on a BIG-IP +description: + - Manages default settings for remote user accounts on a BIG-IP. +version_added: 2.9 +options: + default_role: + description: + - Specifies the default role for all remote user accounts. + - The default system value is C(no-access). + type: str + choices: + - acceleration-policy-editor + - admin + - application-editor + - auditor + - certificate-manager + - firewall-manager + - fraud-protection-manager + - guest + - irule-manager + - manager + - no-access + - operator + - resource-admin + - user-manager + - web-application-security-administrator + - web-application-security-editor + default_partition: + description: + - Specifies the default partition for all remote user accounts. + - The default system value is C(all) for all partitions. + type: str + console_access: + description: + - Enables or disables the default console access for all remote user accounts. + - The default system value is C(disabled). + type: bool + description: + description: + - User defined description. + type: str +extends_documentation_fragment: f5 +author: + - Wojciech Wypior (@wojtek0806) +''' + +EXAMPLES = r''' +- name: Modify default partition and console access + bigip_remote_user: + default_partition: Common + console_access: yes + provider: + password: secret + server: lb.mydomain.com + user: admin + delegate_to: localhost + +- name: Modify default role, partition and console access + bigip_remote_user: + default_partition: Common + default_role: manager + console_access: yes + description: "Changed new settings" + provider: + password: secret + server: lb.mydomain.com + user: admin + delegate_to: localhost + +- name: Revert to default settings + bigip_remote_user: + default_partition: all + default_role: "no-access" + console_access: no + description: "" + provider: + password: secret + server: lb.mydomain.com + user: admin + delegate_to: localhost +''' + +RETURN = r''' +default_role: + description: The default role for all remote user accounts. + returned: changed + type: str + sample: auditor +default_partition: + description: The default partition for all remote user accounts. + returned: changed + type: str + sample: Common +console_access: + description: The default console access for all remote user accounts + returned: changed + type: bool + sample: no +description: + description: The user defined description. + returned: changed + type: str + sample: Foo is bar +''' + +from ansible.module_utils.basic import AnsibleModule + +try: + from library.module_utils.network.f5.bigip import F5RestClient + from library.module_utils.network.f5.common import F5ModuleError + from library.module_utils.network.f5.common import AnsibleF5Parameters + from library.module_utils.network.f5.common import f5_argument_spec + from library.module_utils.network.f5.common import flatten_boolean + from library.module_utils.network.f5.compare import cmp_str_with_none +except ImportError: + from ansible.module_utils.network.f5.bigip import F5RestClient + from ansible.module_utils.network.f5.common import F5ModuleError + from ansible.module_utils.network.f5.common import AnsibleF5Parameters + from ansible.module_utils.network.f5.common import f5_argument_spec + from ansible.module_utils.network.f5.common import flatten_boolean + from ansible.module_utils.network.f5.compare import cmp_str_with_none + + +class Parameters(AnsibleF5Parameters): + api_map = { + 'defaultPartition': 'default_partition', + 'defaultRole': 'default_role', + 'remoteConsoleAccess': 'console_access', + } + + api_attributes = [ + 'defaultPartition', + 'defaultRole', + 'description', + 'remoteConsoleAccess', + + ] + + returnables = [ + 'default_partition', + 'default_role', + 'console_access', + 'description', + ] + + updatables = [ + 'default_partition', + 'default_role', + 'console_access', + 'description', + ] + + +class ApiParameters(Parameters): + pass + + +class ModuleParameters(Parameters): + @property + def console_access(self): + result = flatten_boolean(self._values['console_access']) + if result == 'yes': + return 'tmsh' + if result == 'no': + return 'disabled' + + +class Changes(Parameters): + def to_return(self): + result = {} + try: + for returnable in self.returnables: + result[returnable] = getattr(self, returnable) + result = self._filter_params(result) + except Exception: + pass + return result + + +class UsableChanges(Changes): + pass + + +class ReportableChanges(Changes): + @property + def console_access(self): + if self._values['console_access'] is None: + return None + if self._values['console_access'] == 'tmsh': + return 'yes' + if self._values['console_access'] == 'disabled': + return 'no' + + +class Difference(object): + def __init__(self, want, have=None): + self.want = want + self.have = have + + def compare(self, param): + try: + result = getattr(self, param) + return result + except AttributeError: + return self.__default(param) + + def __default(self, param): + attr1 = getattr(self.want, param) + try: + attr2 = getattr(self.have, param) + if attr1 != attr2: + return attr1 + except AttributeError: + return attr1 + + @property + def description(self): + result = cmp_str_with_none(self.want.description, self.have.description) + return result + + +class ModuleManager(object): + def __init__(self, *args, **kwargs): + self.module = kwargs.get('module', None) + self.client = F5RestClient(**self.module.params) + self.want = ModuleParameters(params=self.module.params) + self.have = ApiParameters() + self.changes = UsableChanges() + + def _update_changed_options(self): + diff = Difference(self.want, self.have) + updatables = Parameters.updatables + changed = dict() + for k in updatables: + change = diff.compare(k) + if change is None: + continue + else: + if isinstance(change, dict): + changed.update(change) + else: + changed[k] = change + if changed: + self.changes = UsableChanges(params=changed) + return True + return False + + def _announce_deprecations(self, result): + warnings = result.pop('__warnings', []) + for warning in warnings: + self.client.module.deprecate( + msg=warning['msg'], + version=warning['version'] + ) + + def exec_module(self): + result = dict() + + changed = self.update() + + reportable = ReportableChanges(params=self.changes.to_return()) + changes = reportable.to_return() + result.update(**changes) + result.update(dict(changed=changed)) + self._announce_deprecations(result) + return result + + def should_update(self): + result = self._update_changed_options() + if result: + return True + return False + + def update(self): + self.have = self.read_current_from_device() + if not self.should_update(): + return False + if self.module.check_mode: + return True + self.update_on_device() + return True + + def update_on_device(self): + params = self.changes.api_params() + uri = "https://{0}:{1}/mgmt/tm/auth/remote-user/".format( + self.client.provider['server'], + self.client.provider['server_port'], + ) + resp = self.client.api.patch(uri, json=params) + try: + response = resp.json() + except ValueError as ex: + raise F5ModuleError(str(ex)) + + if 'code' in response and response['code'] == 400: + if 'message' in response: + raise F5ModuleError(response['message']) + else: + raise F5ModuleError(resp.content) + + def read_current_from_device(self): + uri = "https://{0}:{1}/mgmt/tm/auth/remote-user/".format( + self.client.provider['server'], + self.client.provider['server_port'], + ) + resp = self.client.api.get(uri) + try: + response = resp.json() + except ValueError as ex: + raise F5ModuleError(str(ex)) + + if 'code' in response and response['code'] == 400: + if 'message' in response: + raise F5ModuleError(response['message']) + else: + raise F5ModuleError(resp.content) + return ApiParameters(params=response) + + +class ArgumentSpec(object): + def __init__(self): + self.supports_check_mode = True + self.choices = [ + 'acceleration-policy-editor', + 'admin', + 'application-editor', + 'auditor', + 'certificate-manager', + 'firewall-manager', + 'fraud-protection-manager', + 'guest', + 'irule-manager', + 'manager', + 'no-access', + 'operator', + 'resource-admin', + 'user-manager', + 'web-application-security-administrator', + 'web-application-security-editor' + ] + argument_spec = dict( + default_role=dict( + choices=self.choices + ), + default_partition=dict(), + console_access=dict(type='bool'), + description=dict() + ) + self.argument_spec = {} + self.argument_spec.update(f5_argument_spec) + self.argument_spec.update(argument_spec) + self.required_one_of = [ + ['default_role', 'default_partition'] + ] + + +def main(): + spec = ArgumentSpec() + + module = AnsibleModule( + argument_spec=spec.argument_spec, + supports_check_mode=spec.supports_check_mode, + ) + + try: + mm = ModuleManager(module=module) + results = mm.exec_module() + module.exit_json(**results) + except F5ModuleError as ex: + module.fail_json(msg=str(ex)) + + +if __name__ == '__main__': + main() diff --git a/test/units/modules/network/f5/fixtures/load_remote_user_settings.json b/test/units/modules/network/f5/fixtures/load_remote_user_settings.json new file mode 100644 index 00000000000..296f462f97d --- /dev/null +++ b/test/units/modules/network/f5/fixtures/load_remote_user_settings.json @@ -0,0 +1,10 @@ +{ + "kind": "tm:auth:remote-user:remote-userstate", + "selfLink": "https://localhost/mgmt/tm/auth/remote-user?ver=12.1.4", + "defaultPartition": "all", + "defaultPartitionReference": { + "link": "https://localhost/mgmt/tm/auth/partition/all?ver=12.1.4" + }, + "defaultRole": "no-access", + "remoteConsoleAccess": "disabled" +} diff --git a/test/units/modules/network/f5/test_bigip_remote_user.py b/test/units/modules/network/f5/test_bigip_remote_user.py new file mode 100644 index 00000000000..a31d696f22d --- /dev/null +++ b/test/units/modules/network/f5/test_bigip_remote_user.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2019, F5 Networks 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 + +import os +import json +import pytest +import sys + +if sys.version_info < (2, 7): + pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") + +from ansible.module_utils.basic import AnsibleModule + +try: + from library.modules.bigip_remote_user import ApiParameters + from library.modules.bigip_remote_user import ModuleParameters + from library.modules.bigip_remote_user import ModuleManager + from library.modules.bigip_remote_user import ArgumentSpec + + # In Ansible 2.8, Ansible changed import paths. + from test.units.compat import unittest + from test.units.compat.mock import Mock + from test.units.compat.mock import patch + + from test.units.modules.utils import set_module_args +except ImportError: + from ansible.modules.network.f5.bigip_remote_user import ApiParameters + from ansible.modules.network.f5.bigip_remote_user import ModuleParameters + from ansible.modules.network.f5.bigip_remote_user import ModuleManager + from ansible.modules.network.f5.bigip_remote_user import ArgumentSpec + + # Ansible 2.8 imports + from units.compat import unittest + from units.compat.mock import Mock + from units.compat.mock import patch + + from units.modules.utils import set_module_args + + +fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') +fixture_data = {} + + +def load_fixture(name): + path = os.path.join(fixture_path, name) + + if path in fixture_data: + return fixture_data[path] + + with open(path) as f: + data = f.read() + + try: + data = json.loads(data) + except Exception: + pass + + fixture_data[path] = data + return data + + +class TestParameters(unittest.TestCase): + def test_module_parameters(self): + args = dict( + default_partition='Common', + default_role='admin', + console_access='yes', + description='this is a role' + + ) + + p = ModuleParameters(params=args) + assert p.default_partition == 'Common' + assert p.default_role == 'admin' + assert p.console_access == 'tmsh' + assert p.description == 'this is a role' + + def test_api_parameters(self): + args = load_fixture('load_remote_user_settings.json') + p = ApiParameters(params=args) + assert p.default_partition == 'all' + assert p.default_role == 'no-access' + assert p.console_access == 'disabled' + assert p.description is None + + +class TestManager(unittest.TestCase): + + def setUp(self): + self.spec = ArgumentSpec() + + def test_create_remote_syslog(self, *args): + set_module_args(dict( + default_partition='Foobar', + default_role='auditor', + console_access='yes', + description='this is a role', + provider=dict( + server='localhost', + password='password', + user='admin' + ) + )) + + current = ApiParameters(params=load_fixture('load_remote_user_settings.json')) + + module = AnsibleModule( + argument_spec=self.spec.argument_spec, + supports_check_mode=self.spec.supports_check_mode + ) + + # Override methods in the specific type of manager + mm = ModuleManager(module=module) + mm.update_on_device = Mock(return_value=True) + mm.read_current_from_device = Mock(return_value=current) + + results = mm.exec_module() + + assert results['changed'] is True + assert results['description'] == 'this is a role' + assert results['default_partition'] == 'Foobar' + assert results['default_role'] == 'auditor' + assert results['console_access'] == 'yes'