diff --git a/docs/docsite/rst/dev_guide/developing_module_utilities.rst b/docs/docsite/rst/dev_guide/developing_module_utilities.rst index c65077e2eea..fb712b71906 100644 --- a/docs/docsite/rst/dev_guide/developing_module_utilities.rst +++ b/docs/docsite/rst/dev_guide/developing_module_utilities.rst @@ -9,6 +9,7 @@ Ansible provides a number of module utilities that provide helper functions that The following is a list of module_utils files and a general description. The module utility source code lives in the `./lib/module_utils` directory under your main Ansible path - for more details on any specific module utility, please see the source code. - a10.py - Utilities used by the a10_server module to manage A10 Networks devices. +- aireos.py - Definitions and helper functions for modules that manage Cisco WLC devices. - api.py - Adds shared support for generic API modules. - aos.py - Module support utilities for managing Apstra AOS Server. - aruba.py - Helper functions for modules working with Aruba networking devices. diff --git a/lib/ansible/config/data/config.yml b/lib/ansible/config/data/config.yml index 4ca6302193e..942baa2f098 100644 --- a/lib/ansible/config/data/config.yml +++ b/lib/ansible/config/data/config.yml @@ -1243,7 +1243,7 @@ MERGE_MULTIPLE_CLI_TAGS: vars: [] yaml: {key: defaults.merge_multiple_cli_tags} NETWORK_GROUP_MODULES: - default: [eos, nxos, ios, iosxr, junos, ce, vyos, sros, dellos9, dellos10, dellos6, asa, aruba] + default: [eos, nxos, ios, iosxr, junos, ce, vyos, sros, dellos9, dellos10, dellos6, asa, aruba, aireos] desc: 'TODO: write it' env: [{name: NETWORK_GROUP_MODULES}] ini: diff --git a/lib/ansible/module_utils/aireos.py b/lib/ansible/module_utils/aireos.py new file mode 100644 index 00000000000..00b7a9c61cf --- /dev/null +++ b/lib/ansible/module_utils/aireos.py @@ -0,0 +1,125 @@ +# This code is part of Ansible, but is an independent component. +# This particular file snippet, and this file snippet only, is BSD licensed. +# Modules you write using this snippet, which is embedded dynamically by Ansible +# still belong to the author of the module, and may assign their own license +# to the complete work. +# +# (c) 2016 Red Hat Inc. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +from ansible.module_utils._text import to_text +from ansible.module_utils.basic import env_fallback, return_values +from ansible.module_utils.network_common import to_list, ComplexList +from ansible.module_utils.connection import exec_command + +_DEVICE_CONFIGS = {} + +aireos_argument_spec = { + 'host': dict(), + 'port': dict(type='int'), + 'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), + 'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True), + 'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'), + 'timeout': dict(type='int'), + 'provider': dict(type='dict') +} + +# Add argument's default value here +ARGS_DEFAULT_VALUE = { + 'timeout': 10 +} + + +def get_argspec(): + return aireos_argument_spec + + +def check_args(module, warnings): + provider = module.params['provider'] or {} + for key in aireos_argument_spec: + if key not in ['provider', 'authorize'] and module.params[key]: + warnings.append('argument %s has been deprecated and will be removed in a future version' % key) + + # set argument's default value if not provided in input + # This is done to avoid unwanted argument deprecation warning + # in case argument is not given as input (outside provider). + for key in ARGS_DEFAULT_VALUE: + if not module.params.get(key, None): + module.params[key] = ARGS_DEFAULT_VALUE[key] + + if provider: + for param in ('auth_pass', 'password'): + if provider.get(param): + module.no_log_values.update(return_values(provider[param])) + + +def get_config(module, flags=[]): + cmd = 'show run-config commands ' + cmd += ' '.join(flags) + cmd = cmd.strip() + + try: + return _DEVICE_CONFIGS[cmd] + except KeyError: + rc, out, err = exec_command(module, cmd) + if rc != 0: + module.fail_json(msg='unable to retrieve current config', stderr=to_text(err, errors='surrogate_then_replace')) + cfg = to_text(out, errors='surrogate_then_replace').strip() + _DEVICE_CONFIGS[cmd] = cfg + return cfg + + +def to_commands(module, commands): + spec = { + 'command': dict(key=True), + 'prompt': dict(), + 'answer': dict() + } + transform = ComplexList(spec, module) + return transform(commands) + + +def run_commands(module, commands, check_rc=True): + responses = list() + commands = to_commands(module, to_list(commands)) + for cmd in commands: + cmd = module.jsonify(cmd) + rc, out, err = exec_command(module, cmd) + if check_rc and rc != 0: + module.fail_json(msg=to_text(err, errors='surrogate_then_replace'), rc=rc) + responses.append(to_text(out, errors='surrogate_then_replace')) + return responses + + +def load_config(module, commands): + + rc, out, err = exec_command(module, 'config') + if rc != 0: + module.fail_json(msg='unable to enter configuration mode', err=to_text(out, errors='surrogate_then_replace')) + + for command in to_list(commands): + if command == 'end': + continue + rc, out, err = exec_command(module, command) + if rc != 0: + module.fail_json(msg=to_text(err, errors='surrogate_then_replace'), command=command, rc=rc) + + exec_command(module, 'end') diff --git a/lib/ansible/modules/network/aireos/__init__.py b/lib/ansible/modules/network/aireos/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/lib/ansible/modules/network/aireos/aireos_command.py b/lib/ansible/modules/network/aireos/aireos_command.py new file mode 100644 index 00000000000..9dc60c569d7 --- /dev/null +++ b/lib/ansible/modules/network/aireos/aireos_command.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# + +ANSIBLE_METADATA = {'metadata_version': '1.0', + 'status': ['preview'], + 'supported_by': 'community'} + +DOCUMENTATION = """ +--- +module: aireos_command +version_added: "2.4" +author: "James Mighion (@jmighion)" +short_description: Run commands on remote devices running Cisco WLC +description: + - Sends arbitrary commands to an aireos node and returns the results + read from the device. This module includes an + argument that will cause the module to wait for a specific condition + before returning or timing out if the condition is not met. + - This module does not support running commands in configuration mode. + Please use M(aireos_config) to configure WLC devices. +extends_documentation_fragment: aireos +options: + commands: + description: + - List of commands to send to the remote aireos device over the + configured provider. The resulting output from the command + is returned. If the I(wait_for) argument is provided, the + module is not returned until the condition is satisfied or + the number of retries has expired. + required: true + wait_for: + description: + - List of conditions to evaluate against the output of the + command. The task will wait for each condition to be true + before moving forward. If the conditional is not true + within the configured number of retries, the task fails. + See examples. + required: false + default: null + aliases: ['waitfor'] + match: + description: + - The I(match) argument is used in conjunction with the + I(wait_for) argument to specify the match policy. Valid + values are C(all) or C(any). If the value is set to C(all) + then all conditionals in the wait_for must be satisfied. If + the value is set to C(any) then only one of the values must be + satisfied. + required: false + default: all + choices: ['any', 'all'] + retries: + description: + - Specifies the number of retries a command should by tried + before it is considered failed. The command is run on the + target device every retry and evaluated against the + I(wait_for) conditions. + required: false + default: 10 + interval: + description: + - Configures the interval in seconds to wait between retries + of the command. If the command does not pass the specified + conditions, the interval indicates how long to wait before + trying the command again. + required: false + default: 1 +""" + +EXAMPLES = """ +tasks: + - name: run show sysinfo on remote devices + aireos_command: + commands: show sysinfo + + - name: run show sysinfo and check to see if output contains Cisco Controller + aireos_command: + commands: show sysinfo + wait_for: result[0] contains 'Cisco Controller' + + - name: run multiple commands on remote nodes + aireos_command: + commands: + - show sysinfo + - show interface summary + + - name: run multiple commands and evaluate the output + aireos_command: + commands: + - show sysinfo + - show interface summary + wait_for: + - result[0] contains Cisco Controller + - result[1] contains Loopback0 +""" + +RETURN = """ +stdout: + description: The set of responses from the commands + returned: always apart from low level errors (such as action plugin) + type: list + sample: ['...', '...'] +stdout_lines: + description: The value of stdout split into a list + returned: always apart from low level errors (such as action plugin) + type: list + sample: [['...', '...'], ['...'], ['...']] +failed_conditions: + description: The list of conditionals that have failed + returned: failed + type: list + sample: ['...', '...'] +""" +import time + +from ansible.module_utils.aireos import run_commands +from ansible.module_utils.aireos import aireos_argument_spec, check_args +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.network_common import ComplexList +from ansible.module_utils.netcli import Conditional +from ansible.module_utils.six import string_types + + +def to_lines(stdout): + for item in stdout: + if isinstance(item, string_types): + item = str(item).split('\n') + yield item + + +def parse_commands(module, warnings): + command = ComplexList(dict( + command=dict(key=True), + prompt=dict(), + answer=dict() + ), module) + commands = command(module.params['commands']) + for index, item in enumerate(commands): + if module.check_mode and not item['command'].startswith('show'): + warnings.append( + 'only show commands are supported when using check mode, not ' + 'executing `%s`' % item['command'] + ) + elif item['command'].startswith('conf'): + module.fail_json( + msg='aireos_command does not support running config mode ' + 'commands. Please use aireos_config instead' + ) + return commands + + +def main(): + """main entry point for module execution + """ + argument_spec = dict( + commands=dict(type='list', required=True), + + wait_for=dict(type='list', aliases=['waitfor']), + match=dict(default='all', choices=['all', 'any']), + + retries=dict(default=10, type='int'), + interval=dict(default=1, type='int') + ) + + argument_spec.update(aireos_argument_spec) + + module = AnsibleModule(argument_spec=argument_spec, + supports_check_mode=True) + + result = {'changed': False} + + warnings = list() + check_args(module, warnings) + commands = parse_commands(module, warnings) + result['warnings'] = warnings + + wait_for = module.params['wait_for'] or list() + conditionals = [Conditional(c) for c in wait_for] + + retries = module.params['retries'] + interval = module.params['interval'] + match = module.params['match'] + + while retries > 0: + responses = run_commands(module, commands) + + for item in list(conditionals): + if item(responses): + if match == 'any': + conditionals = list() + break + conditionals.remove(item) + + if not conditionals: + break + + time.sleep(interval) + retries -= 1 + + if conditionals: + failed_conditions = [item.raw for item in conditionals] + msg = 'One or more conditional statements have not be satisfied' + module.fail_json(msg=msg, failed_conditions=failed_conditions) + + result.update({ + 'changed': False, + 'stdout': responses, + 'stdout_lines': list(to_lines(responses)) + }) + + module.exit_json(**result) + + +if __name__ == '__main__': + main() diff --git a/lib/ansible/plugins/action/aireos.py b/lib/ansible/plugins/action/aireos.py new file mode 100644 index 00000000000..8fcfc09479a --- /dev/null +++ b/lib/ansible/plugins/action/aireos.py @@ -0,0 +1,110 @@ +# +# (c) 2016 Red Hat Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import sys +import copy + +from ansible.plugins.action.normal import ActionModule as _ActionModule +from ansible.module_utils.basic import AnsibleFallbackNotFound +from ansible.module_utils.aireos import aireos_argument_spec +from ansible.module_utils.six import iteritems + +try: + from __main__ import display +except ImportError: + from ansible.utils.display import Display + display = Display() + + +class ActionModule(_ActionModule): + + def run(self, tmp=None, task_vars=None): + + if self._play_context.connection != 'local': + return dict( + failed=True, + msg='invalid connection specified, expected connection=local, ' + 'got %s' % self._play_context.connection + ) + + provider = self.load_provider() + + pc = copy.deepcopy(self._play_context) + pc.connection = 'network_cli' + pc.network_os = 'aireos' + pc.remote_addr = provider['host'] or self._play_context.remote_addr + pc.port = provider['port'] or self._play_context.port or 22 + pc.remote_user = provider['username'] or self._play_context.connection_user + pc.password = provider['password'] or self._play_context.password + pc.timeout = provider['timeout'] or self._play_context.timeout + + display.vvv('using connection plugin %s' % pc.connection, pc.remote_addr) + connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin) + + socket_path = connection.run() + display.vvvv('socket_path: %s' % socket_path, pc.remote_addr) + if not socket_path: + return {'failed': True, + 'msg': 'unable to open shell. Please see: ' + + 'https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell'} + + # make sure we are in the right cli context which should be + # enable mode and not config module + rc, out, err = connection.exec_command('prompt()') + if str(out).strip().endswith(')#'): + display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr) + connection.exec_command('exit') + + task_vars['ansible_socket'] = socket_path + + if self._play_context.become_method == 'enable': + self._play_context.become = False + self._play_context.become_method = None + + result = super(ActionModule, self).run(tmp, task_vars) + return result + + def load_provider(self): + provider = self._task.args.get('provider', {}) + for key, value in iteritems(aireos_argument_spec): + if key != 'provider' and key not in provider: + if key in self._task.args: + provider[key] = self._task.args[key] + elif 'fallback' in value: + provider[key] = self._fallback(value['fallback']) + elif key not in provider: + provider[key] = None + return provider + + def _fallback(self, fallback): + strategy = fallback[0] + args = [] + kwargs = {} + + for item in fallback[1:]: + if isinstance(item, dict): + kwargs = item + else: + args = item + try: + return strategy(*args, **kwargs) + except AnsibleFallbackNotFound: + pass diff --git a/lib/ansible/plugins/cliconf/aireos.py b/lib/ansible/plugins/cliconf/aireos.py new file mode 100644 index 00000000000..08339daddbb --- /dev/null +++ b/lib/ansible/plugins/cliconf/aireos.py @@ -0,0 +1,80 @@ +# +# (c) 2017 Red Hat Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import re +import json + +from itertools import chain + +from ansible.module_utils._text import to_bytes, to_text +from ansible.module_utils.network_common import to_list +from ansible.plugins.cliconf import CliconfBase, enable_mode + + +class Cliconf(CliconfBase): + + def get_device_info(self): + device_info = {} + + device_info['network_os'] = 'aireos' + reply = self.get(b'show sysinfo') + data = to_text(reply, errors='surrogate_or_strict').strip() + + match = re.search(r'Product Version\.* (.*)', data) + if match: + device_info['network_os_version'] = match.group(1) + + match = re.search(r'System Name\.* (.*)', data, re.M) + if match: + device_info['network_os_hostname'] = match.group(1) + + reply = self.get(b'show inventory') + data = to_text(reply, errors='surrogate_or_strict').strip() + + match = re.search(r'DESCR: \"(.*)\"', data, re.M) + if match: + device_info['network_os_model'] = match.group(1) + return device_info + + @enable_mode + def get_config(self, source='running'): + if source not in ('running', 'startup'): + return self.invalid_params("fetching configuration from %s is not supported" % source) + if source == 'running': + cmd = b'show run-config commands' + else: + cmd = b'show run-config startup-commands' + return self.send_command(cmd) + + @enable_mode + def edit_config(self, command): + for cmd in chain([b'config'], to_list(command), [b'end']): + self.send_command(cmd) + + def get(self, *args, **kwargs): + return self.send_command(*args, **kwargs) + + def get_capabilities(self): + result = {} + result['rpc'] = self.get_base_rpc() + result['network_api'] = 'cliconf' + result['device_info'] = self.get_device_info() + return json.dumps(result) diff --git a/lib/ansible/plugins/terminal/aireos.py b/lib/ansible/plugins/terminal/aireos.py new file mode 100644 index 00000000000..b4af3b2fe74 --- /dev/null +++ b/lib/ansible/plugins/terminal/aireos.py @@ -0,0 +1,56 @@ +# +# (c) 2016 Red Hat Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json +import re +import time + +from ansible.errors import AnsibleConnectionFailure +from ansible.plugins.terminal import TerminalBase + + +class TerminalModule(TerminalBase): + + terminal_stdout_re = [ + re.compile(br"[\r\n]?[\w]*\(.+\)?[>#\$](?:\s*)$"), + re.compile(br"User:") + ] + + terminal_stderr_re = [ + re.compile(br"% ?Error"), + re.compile(br"% ?Bad secret"), + re.compile(br"invalid input", re.I), + re.compile(br"incorrect usage", re.I), + re.compile(br"(?:incomplete|ambiguous) command", re.I), + re.compile(br"connection timed out", re.I), + re.compile(br"[^\r\n]+ not found", re.I), + re.compile(br"'[^']' +returned error code: ?\d+"), + ] + + def on_open_shell(self): + try: + commands = ('{"command": "' + self._connection._play_context.remote_user + '", "prompt": "Password:", "answer": "' + + self._connection._play_context.password + '"}', + '{"command": "config paging disable"}') + for cmd in commands: + self._exec_cli_command(cmd) + except AnsibleConnectionFailure: + raise AnsibleConnectionFailure('unable to set terminal parameters') diff --git a/lib/ansible/utils/module_docs_fragments/aireos.py b/lib/ansible/utils/module_docs_fragments/aireos.py new file mode 100644 index 00000000000..abc2cc7662d --- /dev/null +++ b/lib/ansible/utils/module_docs_fragments/aireos.py @@ -0,0 +1,67 @@ +# +# (c) 2017, James Mighion <@jmighion> +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . + + +class ModuleDocFragment(object): + + # Standard files documentation fragment + DOCUMENTATION = """ +options: + provider: + description: + - A dict object containing connection details. + default: null + suboptions: + host: + description: + - Specifies the DNS host name or address for connecting to the remote + device over the specified transport. The value of host is used as + the destination address for the transport. + required: true + port: + description: + - Specifies the port to use when building the connection to the remote. + device. + default: 22 + username: + description: + - Configures the username to use to authenticate the connection to + the remote device. This value is used to authenticate + the SSH session. If the value is not specified in the task, the + value of environment variable C(ANSIBLE_NET_USERNAME) will be used instead. + password: + description: + - Specifies the password to use to authenticate the connection to + the remote device. This value is used to authenticate + the SSH session. If the value is not specified in the task, the + value of environment variable C(ANSIBLE_NET_PASSWORD) will be used instead. + default: null + timeout: + description: + - Specifies the timeout in seconds for communicating with the network device + for either connecting or sending commands. If the timeout is + exceeded before the operation is completed, the module will error. + default: 10 + ssh_keyfile: + description: + - Specifies the SSH key to use to authenticate the connection to + the remote device. This value is the path to the + key used to authenticate the SSH session. If the value is not specified + in the task, the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE) + will be used instead. +""" diff --git a/test/units/modules/network/aireos/__init__.py b/test/units/modules/network/aireos/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/test/units/modules/network/aireos/aireos_module.py b/test/units/modules/network/aireos/aireos_module.py new file mode 100644 index 00000000000..3483447a6dc --- /dev/null +++ b/test/units/modules/network/aireos/aireos_module.py @@ -0,0 +1,114 @@ +# (c) 2016 Red Hat Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import json + +from ansible.compat.tests import unittest +from ansible.compat.tests.mock import patch +from ansible.module_utils import basic +from ansible.module_utils._text import to_bytes + + +def set_module_args(args): + args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) + basic._ANSIBLE_ARGS = to_bytes(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: + pass + + fixture_data[path] = data + return data + + +class AnsibleExitJson(Exception): + pass + + +class AnsibleFailJson(Exception): + pass + + +class TestCiscoWlcModule(unittest.TestCase): + + def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False): + + self.load_fixtures(commands) + + if failed: + result = self.failed() + self.assertTrue(result['failed'], result) + else: + result = self.changed(changed) + self.assertEqual(result['changed'], changed, result) + + if commands is not None: + if sort: + self.assertEqual(sorted(commands), sorted(result['commands']), result['commands']) + else: + self.assertEqual(commands, result['commands'], result['commands']) + + return result + + def failed(self): + def fail_json(*args, **kwargs): + kwargs['failed'] = True + raise AnsibleFailJson(kwargs) + + with patch.object(basic.AnsibleModule, 'fail_json', fail_json): + with self.assertRaises(AnsibleFailJson) as exc: + self.module.main() + + result = exc.exception.args[0] + self.assertTrue(result['failed'], result) + return result + + def changed(self, changed=False): + def exit_json(*args, **kwargs): + if 'changed' not in kwargs: + kwargs['changed'] = False + raise AnsibleExitJson(kwargs) + + with patch.object(basic.AnsibleModule, 'exit_json', exit_json): + with self.assertRaises(AnsibleExitJson) as exc: + self.module.main() + + result = exc.exception.args[0] + self.assertEqual(result['changed'], changed, result) + return result + + def load_fixtures(self, commands=None): + pass diff --git a/test/units/modules/network/aireos/fixtures/show_sysinfo b/test/units/modules/network/aireos/fixtures/show_sysinfo new file mode 100644 index 00000000000..c30d8e53423 --- /dev/null +++ b/test/units/modules/network/aireos/fixtures/show_sysinfo @@ -0,0 +1,43 @@ +Manufacturer's Name.............................. Cisco Systems Inc. +Product Name..................................... Cisco Controller +Product Version.................................. 8.2.110.0 +RTOS Version..................................... 8.2.110.0 +Bootloader Version............................... 8.0.100.0 +Emergency Image Version.......................... 8.0.100.0 + +Build Type....................................... DATA + WPS + +System Name...................................... SOMEHOST +System Location.................................. USA +System Contact................................... SN:E228240;ASSET:LSMTCc1 +System ObjectID.................................. 1.3.6.1.4.1.9.1.1615 +Redundancy Mode.................................. Disabled +IP Address....................................... 10.10.10.10 +IPv6 Address..................................... :: +System Up Time................................... 328 days 7 hrs 54 mins 49 secs +System Timezone Location......................... (GMT) London, Lisbon, Dublin, Edinburgh +System Stats Realtime Interval................... 5 +System Stats Normal Interval..................... 180 + +Configured Country............................... US - United States +Operating Environment............................ Commercial (10 to 35 C) +Internal Temp Alarm Limits....................... 10 to 38 C +Internal Temperature............................. +18 C +Fan Status....................................... OK + + RAID Volume Status +Drive 0.......................................... Good +Drive 1.......................................... Good + +State of 802.11b Network......................... Enabled +State of 802.11a Network......................... Enabled +Number of WLANs.................................. 1 +Number of Active Clients......................... 0 + +Burned-in MAC Address............................ AA:AA:AA:AA:AA:AA +Power Supply 1................................... Present, OK +Power Supply 2................................... Present, OK +Maximum number of APs supported.................. 6000 +System Nas-Id.................................... +WLC MIC Certificate Types........................ SHA1/SHA2 +Licensing Type................................... RTU diff --git a/test/units/modules/network/aireos/test_aireos_command.py b/test/units/modules/network/aireos/test_aireos_command.py new file mode 100644 index 00000000000..e4403c171ed --- /dev/null +++ b/test/units/modules/network/aireos/test_aireos_command.py @@ -0,0 +1,104 @@ +# (c) 2016 Red Hat Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . + +# Make coding more python3-ish +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import json + +from ansible.compat.tests.mock import patch +from ansible.modules.network.aireos import aireos_command +from .aireos_module import TestCiscoWlcModule, load_fixture, set_module_args + + +class TestCiscoWlcCommandModule(TestCiscoWlcModule): + + module = aireos_command + + def setUp(self): + self.mock_run_commands = patch('ansible.modules.network.aireos.aireos_command.run_commands') + self.run_commands = self.mock_run_commands.start() + + def tearDown(self): + self.mock_run_commands.stop() + + def load_fixtures(self, commands=None): + + def load_from_file(*args, **kwargs): + module, commands = args + output = list() + + for item in commands: + try: + obj = json.loads(item['command']) + command = obj['command'] + except ValueError: + command = item['command'] + filename = str(command).replace(' ', '_') + output.append(load_fixture(filename)) + return output + + self.run_commands.side_effect = load_from_file + + def test_aireos_command_simple(self): + set_module_args(dict(commands=['show sysinfo'])) + result = self.execute_module() + self.assertEqual(len(result['stdout']), 1) + self.assertTrue(result['stdout'][0].startswith('Manufacturer\'s Name')) + + def test_aireos_command_multiple(self): + set_module_args(dict(commands=['show sysinfo', 'show sysinfo'])) + result = self.execute_module() + self.assertEqual(len(result['stdout']), 2) + self.assertTrue(result['stdout'][0].startswith('Manufacturer\'s Name')) + + def test_aireos_command_wait_for(self): + wait_for = 'result[0] contains "Cisco Systems Inc"' + set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for)) + self.execute_module() + + def test_aireos_command_wait_for_fails(self): + wait_for = 'result[0] contains "test string"' + set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for)) + self.execute_module(failed=True) + self.assertEqual(self.run_commands.call_count, 10) + + def test_aireos_command_retries(self): + wait_for = 'result[0] contains "test string"' + set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for, retries=2)) + self.execute_module(failed=True) + self.assertEqual(self.run_commands.call_count, 2) + + def test_aireos_command_match_any(self): + wait_for = ['result[0] contains "Cisco Systems Inc"', + 'result[0] contains "test string"'] + set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for, match='any')) + self.execute_module() + + def test_aireos_command_match_all(self): + wait_for = ['result[0] contains "Cisco Systems Inc"', + 'result[0] contains "Cisco Controller"'] + set_module_args(dict(commands=['show sysinfo'], wait_for=wait_for, match='all')) + self.execute_module() + + def test_aireos_command_match_all_failure(self): + wait_for = ['result[0] contains "Cisco Systems Inc"', + 'result[0] contains "test string"'] + commands = ['show sysinfo', 'show sysinfo'] + set_module_args(dict(commands=commands, wait_for=wait_for, match='all')) + self.execute_module(failed=True)