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

New voss_config module (#47533)

* New voss_config module

* Updated test import paths as per #46996
This commit is contained in:
Lindsay Hill 2018-11-01 01:37:41 -07:00 committed by Ganesh Nalawade
parent 87de2dde9f
commit a1b0d20368
10 changed files with 961 additions and 18 deletions

View file

@ -26,12 +26,21 @@
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# #
import json import json
from ansible.module_utils._text import to_text import re
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.network.common.utils import to_list, ComplexList from ansible.module_utils.network.common.utils import to_list, ComplexList
from ansible.module_utils.connection import Connection, ConnectionError from ansible.module_utils.connection import Connection, ConnectionError
from ansible.module_utils.network.common.config import NetworkConfig, ConfigLine
_DEVICE_CONFIGS = {} _DEVICE_CONFIGS = {}
DEFAULT_COMMENT_TOKENS = ['#', '!', '/*', '*/', 'echo']
DEFAULT_IGNORE_LINES_RE = set([
re.compile(r"Preparing to Display Configuration\.\.\.")
])
def get_connection(module): def get_connection(module):
if hasattr(module, '_voss_connection'): if hasattr(module, '_voss_connection'):
@ -58,10 +67,6 @@ def get_capabilities(module):
return module._voss_capabilities return module._voss_capabilities
def check_args(module, warnings):
pass
def get_defaults_flag(module): def get_defaults_flag(module):
connection = get_connection(module) connection = get_connection(module)
try: try:
@ -71,7 +76,7 @@ def get_defaults_flag(module):
return to_text(out, errors='surrogate_then_replace').strip() return to_text(out, errors='surrogate_then_replace').strip()
def get_config(module, flags=None): def get_config(module, source='running', flags=None):
flag_str = ' '.join(to_list(flags)) flag_str = ' '.join(to_list(flags))
try: try:
@ -79,7 +84,7 @@ def get_config(module, flags=None):
except KeyError: except KeyError:
connection = get_connection(module) connection = get_connection(module)
try: try:
out = connection.get_config(flags=flags) out = connection.get_config(source=source, flags=flags)
except ConnectionError as exc: except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
cfg = to_text(out, errors='surrogate_then_replace').strip() cfg = to_text(out, errors='surrogate_then_replace').strip()
@ -114,3 +119,101 @@ def load_config(module, commands):
return resp.get('response') return resp.get('response')
except ConnectionError as exc: except ConnectionError as exc:
module.fail_json(msg=to_text(exc)) module.fail_json(msg=to_text(exc))
def get_sublevel_config(running_config, module):
contents = list()
current_config_contents = list()
sublevel_config = VossNetworkConfig(indent=0)
obj = running_config.get_object(module.params['parents'])
if obj:
contents = obj._children
for c in contents:
if isinstance(c, ConfigLine):
current_config_contents.append(c.raw)
sublevel_config.add(current_config_contents, module.params['parents'])
return sublevel_config
def ignore_line(text, tokens=None):
for item in (tokens or DEFAULT_COMMENT_TOKENS):
if text.startswith(item):
return True
for regex in DEFAULT_IGNORE_LINES_RE:
if regex.match(text):
return True
def voss_parse(lines, indent=None, comment_tokens=None):
toplevel = re.compile(r'(^interface.*$)|(^router \w+$)|(^router vrf \w+$)')
exitline = re.compile(r'^exit$')
entry_reg = re.compile(r'([{};])')
ancestors = list()
config = list()
dup_parent_index = None
for line in to_native(lines, errors='surrogate_or_strict').split('\n'):
text = entry_reg.sub('', line).strip()
cfg = ConfigLine(text)
if not text or ignore_line(text, comment_tokens):
continue
# Handle top level commands
if toplevel.match(text):
# Looking to see if we have existing parent
for index, item in enumerate(config):
if item.text == text:
# This means we have an existing parent with same label
dup_parent_index = index
break
ancestors = [cfg]
config.append(cfg)
# Handle 'exit' line
elif exitline.match(text):
ancestors = list()
if dup_parent_index is not None:
# We're working with a duplicate parent
# Don't need to store exit, just go to next line in config
dup_parent_index = None
else:
cfg._parents = ancestors[:1]
config.append(cfg)
# Handle sub-level commands. Only have single sub-level
elif ancestors:
cfg._parents = ancestors[:1]
if dup_parent_index is not None:
# Update existing entry, since this already exists in config
config[int(dup_parent_index)].add_child(cfg)
new_index = dup_parent_index + 1
config.insert(new_index, cfg)
else:
ancestors[0].add_child(cfg)
config.append(cfg)
else:
# Global command, no further special handling needed
config.append(cfg)
return config
class VossNetworkConfig(NetworkConfig):
def load(self, s):
self._config_text = s
self._items = voss_parse(s, self._indent)
def _diff_line(self, other):
updates = list()
for item in self.items:
if str(item) == "exit":
if updates and updates[-1]._parents:
updates.append(item)
elif item not in other:
updates.append(item)
return updates

View file

@ -37,6 +37,7 @@ description:
argument that will cause the module to wait for a specific condition argument that will cause the module to wait for a specific condition
before returning or timing out if the condition is not met. before returning or timing out if the condition is not met.
- This module does not support running commands in configuration mode. - This module does not support running commands in configuration mode.
Please use M(voss_config) to configure VOSS devices.
notes: notes:
- Tested against VOSS 7.0.0 - Tested against VOSS 7.0.0
options: options:
@ -139,7 +140,6 @@ import re
import time import time
from ansible.module_utils.network.voss.voss import run_commands from ansible.module_utils.network.voss.voss import run_commands
from ansible.module_utils.network.voss.voss import check_args
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.utils import ComplexList from ansible.module_utils.network.common.utils import ComplexList
from ansible.module_utils.network.common.parsing import Conditional from ansible.module_utils.network.common.parsing import Conditional
@ -196,7 +196,6 @@ def main():
result = {'changed': False} result = {'changed': False}
warnings = list() warnings = list()
check_args(module, warnings)
commands = parse_commands(module, warnings) commands = parse_commands(module, warnings)
result['warnings'] = warnings result['warnings'] = warnings

View file

@ -0,0 +1,424 @@
#!/usr/bin/python
# Copyright: (c) 2018, Extreme 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': 'community'}
DOCUMENTATION = """
---
module: voss_config
version_added: "2.8"
author: "Lindsay Hill (@LindsayHill)"
short_description: Manage Extreme VOSS configuration sections
description:
- Extreme VOSS configurations use a simple flat text file syntax.
This module provides an implementation for working with EXOS
configuration lines in a deterministic way.
notes:
- Tested against VOSS 7.0.0
- Abbreviated commands are NOT idempotent, see
L(Network FAQ,../network/user_guide/faq.html#why-do-the-config-modules-always-return-changed-true-with-abbreviated-commands).
options:
lines:
description:
- The ordered set of commands that should be configured in the
section. The commands must be the exact same commands as found
in the device running-config. Be sure to note the configuration
command syntax as some commands are automatically modified by the
device config parser.
aliases: ['commands']
parents:
description:
- The parent line that uniquely identifies the section the commands
should be checked against. If this argument is omitted, the commands
are checked against the set of top level or global commands. Note
that VOSS configurations only support one level of nested commands.
src:
description:
- Specifies the source path to the file that contains the configuration
or configuration template to load. The path to the source file can
either be the full path on the Ansible control host or a relative
path from the playbook or role root directory. This argument is mutually
exclusive with I(lines), I(parents).
before:
description:
- The ordered set of commands to push on to the command stack if
a change needs to be made. This allows the playbook designer
the opportunity to perform configuration commands prior to pushing
any changes without affecting how the set of commands are matched
against the system.
after:
description:
- The ordered set of commands to append to the end of the command
stack if a change needs to be made. Just like with I(before) this
allows the playbook designer to append a set of commands to be
executed after the command set.
match:
description:
- Instructs the module on the way to perform the matching of
the set of commands against the current device config. If
match is set to I(line), commands are matched line by line. If
match is set to I(strict), command lines are matched with respect
to position. If match is set to I(exact), command lines
must be an equal match. Finally, if match is set to I(none), the
module will not attempt to compare the source configuration with
the running configuration on the remote device.
choices: ['line', 'strict', 'exact', 'none']
default: line
replace:
description:
- Instructs the module on the way to perform the configuration
on the device. If the replace argument is set to I(line) then
the modified lines are pushed to the device in configuration
mode. If the replace argument is set to I(block) then the entire
command block is pushed to the device in configuration mode if any
line is not correct.
default: line
choices: ['line', 'block']
backup:
description:
- This argument will cause the module to create a full backup of
the current C(running-config) from the remote device before any
changes are made. The backup file is written to the C(backup)
folder in the playbook root directory or role root directory, if
playbook is part of an ansible role. If the directory does not exist,
it is created.
type: bool
default: 'no'
running_config:
description:
- The module, by default, will connect to the remote device and
retrieve the current running-config to use as a base for comparing
against the contents of source. There are times when it is not
desirable to have the task get the current running-config for
every task in a playbook. The I(running_config) argument allows the
implementer to pass in the configuration to use as the base
config for comparison.
aliases: ['config']
defaults:
description:
- This argument specifies whether or not to collect all defaults
when getting the remote device running config. When enabled,
the module will get the current config by issuing the command
C(show running-config verbose).
type: bool
default: 'no'
save_when:
description:
- When changes are made to the device running-configuration, the
changes are not copied to non-volatile storage by default. Using
this argument will change that behavior. If the argument is set to
I(always), then the running-config will always be saved and the
I(modified) flag will always be set to True. If the argument is set
to I(modified), then the running-config will only be saved if it
has changed since the last save to startup-config. If the argument
is set to I(never), the running-config will never be saved.
If the argument is set to I(changed), then the running-config
will only be saved if the task has made a change.
default: never
choices: ['always', 'never', 'modified', 'changed']
diff_against:
description:
- When using the C(ansible-playbook --diff) command line argument
the module can generate diffs against different sources.
- When this option is configure as I(startup), the module will return
the diff of the running-config against the startup-config.
- When this option is configured as I(intended), the module will
return the diff of the running-config against the configuration
provided in the C(intended_config) argument.
- When this option is configured as I(running), the module will
return the before and after diff of the running-config with respect
to any changes made to the device configuration.
choices: ['running', 'startup', 'intended']
diff_ignore_lines:
description:
- Use this argument to specify one or more lines that should be
ignored during the diff. This is used for lines in the configuration
that are automatically updated by the system. This argument takes
a list of regular expressions or exact line matches.
intended_config:
description:
- The C(intended_config) provides the master configuration that
the node should conform to and is used to check the final
running-config against. This argument will not modify any settings
on the remote device and is strictly used to check the compliance
of the current device's configuration against. When specifying this
argument, the task should also modify the C(diff_against) value and
set it to I(intended).
"""
EXAMPLES = """
- name: configure system name
voss_config:
lines: prompt "{{ inventory_hostname }}"
- name: configure interface settings
voss_config:
lines:
- name "ServerA"
backup: yes
parents: interface GigabitEthernet 1/1
- name: check the running-config against master config
voss_config:
diff_against: intended
intended_config: "{{ lookup('file', 'master.cfg') }}"
- name: check the startup-config against the running-config
voss_config:
diff_against: startup
diff_ignore_lines:
- qos queue-profile .*
- name: save running to startup when modified
voss_config:
save_when: modified
"""
RETURN = """
updates:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['prompt "VSP200"']
commands:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['interface GigabitEthernet 1/1', 'name "ServerA"', 'exit']
backup_path:
description: The full path to the backup file
returned: when backup is yes
type: string
sample: /playbooks/ansible/backup/vsp200_config.2018-08-21@15:00:21
"""
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import ConnectionError
from ansible.module_utils.network.voss.voss import run_commands, get_config
from ansible.module_utils.network.voss.voss import get_defaults_flag, get_connection
from ansible.module_utils.network.voss.voss import get_sublevel_config, VossNetworkConfig
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.config import dumps
def get_candidate_config(module):
candidate = VossNetworkConfig(indent=0)
if module.params['src']:
candidate.load(module.params['src'])
elif module.params['lines']:
parents = module.params['parents'] or list()
commands = module.params['lines'][0]
if (isinstance(commands, dict)) and (isinstance(commands['command'], list)):
candidate.add(commands['command'], parents=parents)
elif (isinstance(commands, dict)) and (isinstance(commands['command'], str)):
candidate.add([commands['command']], parents=parents)
else:
candidate.add(module.params['lines'], parents=parents)
return candidate
def get_running_config(module, current_config=None, flags=None):
running = module.params['running_config']
if not running:
if not module.params['defaults'] and current_config:
running = current_config
else:
running = get_config(module, flags=flags)
return running
def save_config(module, result):
result['changed'] = True
if not module.check_mode:
run_commands(module, 'save config\r')
else:
module.warn('Skipping command `save config` '
'due to check_mode. Configuration not copied to '
'non-volatile storage')
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(type='path'),
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line', choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
running_config=dict(aliases=['config']),
intended_config=dict(),
defaults=dict(type='bool', default=False),
backup=dict(type='bool', default=False),
save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'),
diff_against=dict(choices=['startup', 'intended', 'running']),
diff_ignore_lines=dict(type='list'),
)
mutually_exclusive = [('lines', 'src'),
('parents', 'src')]
required_if = [('match', 'strict', ['lines']),
('match', 'exact', ['lines']),
('replace', 'block', ['lines']),
('diff_against', 'intended', ['intended_config'])]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
required_if=required_if,
supports_check_mode=True)
result = {'changed': False}
parents = module.params['parents'] or list()
match = module.params['match']
replace = module.params['replace']
warnings = list()
result['warnings'] = warnings
diff_ignore_lines = module.params['diff_ignore_lines']
config = None
contents = None
flags = get_defaults_flag(module) if module.params['defaults'] else []
connection = get_connection(module)
if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'):
contents = get_config(module, flags=flags)
config = VossNetworkConfig(indent=0, contents=contents)
if module.params['backup']:
result['__backup__'] = contents
if any((module.params['lines'], module.params['src'])):
candidate = get_candidate_config(module)
if match != 'none':
config = get_running_config(module)
config = VossNetworkConfig(contents=config, indent=0)
if parents:
config = get_sublevel_config(config, module)
configobjs = candidate.difference(config, match=match, replace=replace)
else:
configobjs = candidate.items
if configobjs:
commands = dumps(configobjs, 'commands')
commands = commands.split('\n')
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
result['commands'] = commands
result['updates'] = commands
# send the configuration commands to the device and merge
# them with the current running config
if not module.check_mode:
if commands:
try:
connection.edit_config(candidate=commands)
except ConnectionError as exc:
module.fail_json(msg=to_text(commands, errors='surrogate_then_replace'))
result['changed'] = True
running_config = module.params['running_config']
startup = None
if module.params['save_when'] == 'always':
save_config(module, result)
elif module.params['save_when'] == 'modified':
match = module.params['match']
replace = module.params['replace']
try:
# Note we need to re-retrieve running config, not use cached version
running = connection.get_config(source='running')
startup = connection.get_config(source='startup')
response = connection.get_diff(candidate=startup, running=running, diff_match=match,
diff_ignore_lines=diff_ignore_lines, path=None,
diff_replace=replace)
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
config_diff = response['config_diff']
if config_diff:
save_config(module, result)
elif module.params['save_when'] == 'changed' and result['changed']:
save_config(module, result)
if module._diff:
if not running_config:
try:
# Note we need to re-retrieve running config, not use cached version
contents = connection.get_config(source='running')
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
else:
contents = running_config
# recreate the object in order to process diff_ignore_lines
running_config = VossNetworkConfig(indent=0, contents=contents,
ignore_lines=diff_ignore_lines)
if module.params['diff_against'] == 'running':
if module.check_mode:
module.warn("unable to perform diff against running-config due to check mode")
contents = None
else:
contents = config.config_text
elif module.params['diff_against'] == 'startup':
if not startup:
try:
contents = connection.get_config(source='startup')
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
else:
contents = startup
elif module.params['diff_against'] == 'intended':
contents = module.params['intended_config']
if contents is not None:
base_config = VossNetworkConfig(indent=0, contents=contents,
ignore_lines=diff_ignore_lines)
if running_config.sha1 != base_config.sha1:
if module.params['diff_against'] == 'intended':
before = running_config
after = base_config
elif module.params['diff_against'] in ('startup', 'running'):
before = base_config
after = running_config
result.update({
'changed': True,
'diff': {'before': str(before), 'after': str(after)}
})
module.exit_json(**result)
if __name__ == '__main__':
main()

View file

@ -129,7 +129,6 @@ ansible_net_neighbors:
import re import re
from ansible.module_utils.network.voss.voss import run_commands from ansible.module_utils.network.voss.voss import run_commands
from ansible.module_utils.network.voss.voss import check_args
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
@ -502,7 +501,6 @@ def main():
ansible_facts[key] = value ansible_facts[key] = value
warnings = list() warnings = list()
check_args(module, warnings)
module.exit_json(ansible_facts=ansible_facts, warnings=warnings) module.exit_json(ansible_facts=ansible_facts, warnings=warnings)

View file

@ -0,0 +1,113 @@
#
# (c) 2018 Extreme Networks 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 <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import time
import glob
from ansible.plugins.action.normal import ActionModule as _ActionModule
from ansible.module_utils._text import to_text
from ansible.module_utils.six.moves.urllib.parse import urlsplit
from ansible.utils.vars import merge_hash
PRIVATE_KEYS_RE = re.compile('__.+__')
class ActionModule(_ActionModule):
def run(self, tmp=None, task_vars=None):
if self._task.args.get('src'):
try:
self._handle_template()
except ValueError as exc:
return dict(failed=True, msg=to_text(exc))
result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
if self._task.args.get('backup') and result.get('__backup__'):
# User requested backup and no error occurred in module.
# NOTE: If there is a parameter error, _backup key may not be in results.
filepath = self._write_backup(task_vars['inventory_hostname'],
result['__backup__'])
result['backup_path'] = filepath
# strip out any keys that have two leading and two trailing
# underscore characters
for key in list(result.keys()):
if PRIVATE_KEYS_RE.match(key):
del result[key]
return result
def _get_working_path(self):
cwd = self._loader.get_basedir()
if self._task._role is not None:
cwd = self._task._role._role_path
return cwd
def _write_backup(self, host, contents):
backup_path = self._get_working_path() + '/backup'
if not os.path.exists(backup_path):
os.mkdir(backup_path)
for fn in glob.glob('%s/%s*' % (backup_path, host)):
os.remove(fn)
tstamp = time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime(time.time()))
filename = '%s/%s_config.%s' % (backup_path, host, tstamp)
open(filename, 'w').write(contents)
return filename
def _handle_template(self):
src = self._task.args.get('src')
working_path = self._get_working_path()
if os.path.isabs(src) or urlsplit('src').scheme:
source = src
else:
source = self._loader.path_dwim_relative(working_path, 'templates', src)
if not source:
source = self._loader.path_dwim_relative(working_path, src)
if not os.path.exists(source):
raise ValueError('path specified in src not found')
try:
with open(source, 'r') as f:
template_data = to_text(f.read())
except IOError:
return dict(failed=True, msg='unable to load src file')
# Create a template search path in the following order:
# [working_path, self_role_path, dependent_role_paths, dirname(source)]
searchpath = [working_path]
if self._task._role is not None:
searchpath.append(self._task._role._role_path)
if hasattr(self._task, "_block:"):
dep_chain = self._task._block.get_dep_chain()
if dep_chain is not None:
for role in dep_chain:
searchpath.append(role._role_path)
searchpath.append(os.path.dirname(source))
self._templar.environment.loader.searchpath = searchpath
self._task.args['src'] = self._templar.template(template_data)

View file

@ -27,6 +27,7 @@ from ansible.module_utils._text import to_text
from ansible.module_utils.common._collections_compat import Mapping from ansible.module_utils.common._collections_compat import Mapping
from ansible.module_utils.network.common.config import NetworkConfig, dumps from ansible.module_utils.network.common.config import NetworkConfig, dumps
from ansible.module_utils.network.common.utils import to_list from ansible.module_utils.network.common.utils import to_list
from ansible.module_utils.network.voss.voss import VossNetworkConfig
from ansible.plugins.cliconf import CliconfBase, enable_mode from ansible.plugins.cliconf import CliconfBase, enable_mode
@ -44,12 +45,11 @@ class Cliconf(CliconfBase):
flags = [] flags = []
if source == 'running': if source == 'running':
cmd = 'show running-config ' cmd = 'show running-config '
cmd += ' '.join(to_list(flags))
cmd = cmd.strip()
else: else:
cmd = 'more /intflash/config.cfg' cmd = 'more /intflash/config.cfg'
cmd += ' '.join(to_list(flags))
cmd = cmd.strip()
return self.send_command(cmd) return self.send_command(cmd)
def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'): def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'):
@ -83,11 +83,11 @@ class Cliconf(CliconfBase):
:return: Configuration diff in json format. :return: Configuration diff in json format.
{ {
'config_diff': '', 'config_diff': '',
'banner_diff': {}
} }
""" """
diff = {} diff = {}
device_operations = self.get_device_operations() device_operations = self.get_device_operations()
option_values = self.get_option_values() option_values = self.get_option_values()
@ -101,18 +101,20 @@ class Cliconf(CliconfBase):
raise ValueError("'replace' value %s in invalid, valid values are %s" % (diff_replace, ', '.join(option_values['diff_replace']))) raise ValueError("'replace' value %s in invalid, valid values are %s" % (diff_replace, ', '.join(option_values['diff_replace'])))
# prepare candidate configuration # prepare candidate configuration
candidate_obj = NetworkConfig(indent=1) candidate_obj = VossNetworkConfig(indent=0, ignore_lines=diff_ignore_lines)
candidate_obj.load(candidate) candidate_obj.load(candidate)
if running and diff_match != 'none': if running and diff_match != 'none':
# running configuration # running configuration
running_obj = NetworkConfig(indent=1, contents=running, ignore_lines=diff_ignore_lines) running_obj = VossNetworkConfig(indent=0, contents=running, ignore_lines=diff_ignore_lines)
configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace) configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace)
else: else:
configdiffobjs = candidate_obj.items configdiffobjs = candidate_obj.items
diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else '' diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else ''
diff['diff_path'] = path
diff['diff_replace'] = diff_replace
return diff return diff
@enable_mode @enable_mode
@ -191,7 +193,7 @@ class Cliconf(CliconfBase):
def get_capabilities(self): def get_capabilities(self):
result = dict() result = dict()
result['rpc'] = self.get_base_rpc() + ['edit_banner', 'get_diff', 'run_commands', 'get_defaults_flag'] result['rpc'] = self.get_base_rpc() + ['get_diff', 'run_commands', 'get_defaults_flag']
result['network_api'] = 'cliconf' result['network_api'] = 'cliconf'
result['device_info'] = self.get_device_info() result['device_info'] = self.get_device_info()
result['device_operations'] = self.get_device_operations() result['device_operations'] = self.get_device_operations()

View file

@ -0,0 +1,16 @@
prompt "VSP300"
interface GigabitEthernet 1/1
name "ServerA"
vlacp enable
exit
interface GigabitEthernet 1/2
name "ServerB"
vlacp enable
no shutdown
exit
interface loopback 1
ip address 1 1.1.1.1/255.255.255.255
exit
interface loopback 1
ipv6 interface address 2011:0:0:0:0:0:0:1/128
exit

View file

@ -0,0 +1,6 @@
interface loopback 1
ip address 1 2.2.2.2/255.255.255.255
exit
interface loopback 1
ipv6 interface address 2011:0:0:0:0:0:0:2/128
exit

View file

@ -0,0 +1,10 @@
prompt "VSP8K"
interface GigabitEthernet 1/1
name "UNUSED"
vlacp enable
exit
interface GigabitEthernet 1/2
name "ServerB"
vlacp enable
no shutdown
exit

View file

@ -0,0 +1,272 @@
#
# (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 <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch, MagicMock
from ansible.modules.network.voss import voss_config
from ansible.plugins.cliconf.voss import Cliconf
from units.modules.utils import set_module_args
from .voss_module import TestVossModule, load_fixture
class TestVossConfigModule(TestVossModule):
module = voss_config
def setUp(self):
super(TestVossConfigModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.voss.voss_config.get_config')
self.get_config = self.mock_get_config.start()
self.mock_get_connection = patch('ansible.modules.network.voss.voss_config.get_connection')
self.get_connection = self.mock_get_connection.start()
self.conn = self.get_connection()
self.conn.edit_config = MagicMock()
self.mock_run_commands = patch('ansible.modules.network.voss.voss_config.run_commands')
self.run_commands = self.mock_run_commands.start()
self.cliconf_obj = Cliconf(MagicMock())
self.running_config = load_fixture('voss_config_config.cfg')
def tearDown(self):
super(TestVossConfigModule, self).tearDown()
self.mock_get_config.stop()
self.mock_run_commands.stop()
self.mock_get_connection.stop()
def load_fixtures(self, commands=None):
config_file = 'voss_config_config.cfg'
self.get_config.return_value = load_fixture(config_file)
self.get_connection.edit_config.return_value = None
def test_voss_config_unchanged(self):
src = load_fixture('voss_config_config.cfg')
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(src, src))
set_module_args(dict(src=src))
self.execute_module()
def test_voss_config_src(self):
src = load_fixture('voss_config_src.cfg')
set_module_args(dict(src=src))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(src, self.running_config))
commands = ['prompt "VSP8K"', 'interface GigabitEthernet 1/1',
'name "UNUSED"', 'exit']
self.execute_module(changed=True, commands=commands)
def test_voss_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_voss_config_save_always(self):
self.run_commands.return_value = "Hostname foo"
set_module_args(dict(save_when='always'))
self.execute_module(changed=True)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.conn.edit_config.call_count, 0)
args = self.run_commands.call_args[0][1]
self.assertIn('save config\r', args)
def test_voss_config_save_changed_true(self):
src = load_fixture('voss_config_src.cfg')
set_module_args(dict(src=src, save_when='changed'))
commands = ['prompt "VSP8K"', 'interface GigabitEthernet 1/1',
'name "UNUSED"', 'exit']
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(src, self.running_config))
self.execute_module(changed=True, commands=commands)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 1)
self.assertEqual(self.conn.edit_config.call_count, 1)
args = self.run_commands.call_args[0][1]
self.assertIn('save config\r', args)
def test_voss_config_save_changed_false(self):
set_module_args(dict(save_when='changed'))
self.execute_module(changed=False)
self.assertEqual(self.run_commands.call_count, 0)
self.assertEqual(self.get_config.call_count, 0)
self.assertEqual(self.conn.edit_config.call_count, 0)
def test_voss_config_lines_wo_parents(self):
lines = ['prompt "VSP8K"']
set_module_args(dict(lines=lines))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff('\n'.join(lines), self.running_config))
commands = ['prompt "VSP8K"']
self.execute_module(changed=True, commands=commands)
def test_voss_config_lines_w_parents(self):
lines = ['no shutdown']
parents = ['interface GigabitEthernet 1/1']
set_module_args(dict(lines=lines, parents=parents))
module = MagicMock()
module.params = {'lines': lines, 'parents': parents, 'src': None}
candidate_config = voss_config.get_candidate_config(module)
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(candidate_config, self.running_config))
commands = ['interface GigabitEthernet 1/1', 'no shutdown']
self.execute_module(changed=True, commands=commands)
def test_voss_config_before(self):
lines = ['prompt "VSP8K"']
set_module_args(dict(lines=lines, before=['test1', 'test2']))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff('\n'.join(lines),
self.running_config))
commands = ['test1', 'test2', 'prompt "VSP8K"']
self.execute_module(changed=True, commands=commands, sort=False)
def test_voss_config_after(self):
lines = ['prompt "VSP8K"']
set_module_args(dict(lines=lines, after=['test1', 'test2']))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff('\n'.join(lines),
self.running_config))
commands = ['prompt "VSP8K"', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False)
def test_voss_config_before_after_no_change(self):
lines = ['prompt "VSP300"']
set_module_args(dict(lines=lines,
before=['test1', 'test2'],
after=['test3', 'test4']))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff('\n'.join(lines), self.running_config))
self.execute_module()
def test_voss_config_config(self):
config = 'prompt "VSP300"'
lines = ['prompt router']
set_module_args(dict(lines=lines, config=config))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff('\n'.join(lines), config))
commands = ['prompt router']
self.execute_module(changed=True, commands=commands)
def test_voss_config_replace_block(self):
lines = ['name "ServerB"', 'test string']
parents = ['interface GigabitEthernet 1/2']
set_module_args(dict(lines=lines, replace='block', parents=parents))
module = MagicMock()
module.params = {'lines': lines, 'parents': parents, 'src': None}
candidate_config = voss_config.get_candidate_config(module)
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(candidate_config, self.running_config, diff_replace='block', path=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands)
def test_voss_config_match_none(self):
lines = ['prompt router']
set_module_args(dict(lines=lines, match='none'))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff('\n'.join(lines), self.running_config, diff_match='none'))
self.execute_module(changed=True, commands=lines)
def test_voss_config_match_none_parents(self):
lines = ['name ServerA', 'vlacp enable']
parents = ['interface GigabitEthernet 1/1']
set_module_args(dict(lines=lines, parents=parents, match='none'))
module = MagicMock()
module.params = {'lines': lines, 'parents': parents, 'src': None}
candidate_config = voss_config.get_candidate_config(module)
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(candidate_config, self.running_config, diff_match='none', path=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_voss_config_match_strict(self):
lines = ['name "ServerA"', 'vlacp enable',
'no shutdown']
parents = ['interface GigabitEthernet 1/1']
set_module_args(dict(lines=lines, parents=parents, match='strict'))
module = MagicMock()
module.params = {'lines': lines, 'parents': parents, 'src': None}
candidate_config = voss_config.get_candidate_config(module)
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(candidate_config, self.running_config, diff_match='strict', path=parents))
commands = parents + ['no shutdown']
self.execute_module(changed=True, commands=commands, sort=False)
def test_voss_config_match_exact(self):
lines = ['name "ServerA"', 'vlacp enable', 'no shutdown']
parents = ['interface GigabitEthernet 1/1']
set_module_args(dict(lines=lines, parents=parents, match='exact'))
module = MagicMock()
module.params = {'lines': lines, 'parents': parents, 'src': None}
candidate_config = voss_config.get_candidate_config(module)
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(candidate_config, self.running_config, diff_match='exact', path=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_voss_config_src_and_lines_fails(self):
args = dict(src='foo', lines='foo')
set_module_args(args)
self.execute_module(failed=True)
def test_voss_config_src_and_parents_fails(self):
args = dict(src='foo', parents='foo')
set_module_args(args)
self.execute_module(failed=True)
def test_voss_config_match_exact_requires_lines(self):
args = dict(match='exact')
set_module_args(args)
self.execute_module(failed=True)
def test_voss_config_match_strict_requires_lines(self):
args = dict(match='strict')
set_module_args(args)
self.execute_module(failed=True)
def test_voss_config_replace_block_requires_lines(self):
args = dict(replace='block')
set_module_args(args)
self.execute_module(failed=True)
def test_voss_config_replace_config_requires_src(self):
args = dict(replace='config')
set_module_args(args)
self.execute_module(failed=True)
def test_voss_config_ipv6(self):
lines = ['ip address 1 1.1.1.1/255.255.255.255',
'ipv6 interface address 2011:0:0:0:0:0:0:1/128']
parents = ['interface loopback 1']
set_module_args(dict(lines=lines, parents=parents))
module = MagicMock()
module.params = {'lines': lines, 'parents': parents, 'src': None}
candidate_config = voss_config.get_candidate_config(module)
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(candidate_config, self.running_config))
self.execute_module(changed=False)
def test_voss_config_src_ipv6(self):
src = load_fixture('voss_config_ipv6.cfg')
set_module_args(dict(src=src))
self.conn.get_diff = MagicMock(return_value=self.cliconf_obj.get_diff(src, self.running_config))
commands = ['interface loopback 1', 'ip address 1 2.2.2.2/255.255.255.255',
'ipv6 interface address 2011:0:0:0:0:0:0:2/128', 'exit']
self.execute_module(changed=True, commands=commands)