mirror of https://github.com/ansible/ansible.git
updates vyos modules to use socket connection (#21228)
* updates all vyos modules to use socket connection * adds vyos local action handler * adds exec_command() to vyos * updates vyos_config local action * update unit test cases * add base class for testing vyos modulespull/21343/head
parent
85194234ba
commit
8adb108aa9
@ -1,161 +0,0 @@
|
||||
# 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) 2017 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.
|
||||
#
|
||||
import re
|
||||
|
||||
from ansible.module_utils.shell import CliBase
|
||||
from ansible.module_utils.basic import env_fallback, get_exception
|
||||
from ansible.module_utils.network_common import to_list
|
||||
from ansible.module_utils.netcli import Command
|
||||
from ansible.module_utils.six import iteritems
|
||||
from ansible.module_utils.network import NetworkError
|
||||
|
||||
_DEVICE_CONFIGS = {}
|
||||
_DEVICE_CONNECTION = None
|
||||
|
||||
vyos_cli_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),
|
||||
|
||||
'authorize': dict(default=False, fallback=(env_fallback, ['ANSIBLE_NET_AUTHORIZE']), type='bool'),
|
||||
'auth_pass': dict(no_log=True, fallback=(env_fallback, ['ANSIBLE_NET_AUTH_PASS'])),
|
||||
|
||||
'timeout': dict(type='int', default=10),
|
||||
|
||||
'provider': dict(type='dict'),
|
||||
|
||||
# deprecated in Ansible 2.3
|
||||
'transport': dict(),
|
||||
}
|
||||
|
||||
def check_args(module):
|
||||
provider = module.params['provider'] or {}
|
||||
for key in ('host', 'username', 'password'):
|
||||
if not module.params[key] and not provider.get(key):
|
||||
module.fail_json(msg='missing required argument %s' % key)
|
||||
|
||||
class Cli(CliBase):
|
||||
|
||||
CLI_PROMPTS_RE = [
|
||||
re.compile(r"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
|
||||
re.compile(r"\@[\w\-\.]+:\S+?[>#\$] ?$")
|
||||
]
|
||||
|
||||
CLI_ERRORS_RE = [
|
||||
re.compile(r"\n\s*Invalid command:"),
|
||||
re.compile(r"\nCommit failed"),
|
||||
re.compile(r"\n\s+Set failed"),
|
||||
]
|
||||
|
||||
def __init__(self, module):
|
||||
self._module = module
|
||||
super(Cli, self).__init__()
|
||||
|
||||
provider = self._module.params.get('provider') or dict()
|
||||
for key, value in iteritems(provider):
|
||||
if key in nxos_cli_argument_spec:
|
||||
if self._module.params.get(key) is None and value is not None:
|
||||
self._module.params[key] = value
|
||||
|
||||
try:
|
||||
self.connect()
|
||||
except NetworkError:
|
||||
exc = get_exception()
|
||||
self._module.fail_json(msg=str(exc))
|
||||
|
||||
def connect(self, params, **kwargs):
|
||||
super(Cli, self).connect(params, kickstart=False, **kwargs)
|
||||
self.shell.send('set terminal length 0')
|
||||
|
||||
def connection(module):
|
||||
global _DEVICE_CONNECTION
|
||||
if not _DEVICE_CONNECTION:
|
||||
cli = Cli(module)
|
||||
_DEVICE_CONNECTION = cli
|
||||
return _DEVICE_CONNECTION
|
||||
|
||||
def get_config(module, target='commands'):
|
||||
cmd = ' '.join(['show configuration', target])
|
||||
|
||||
try:
|
||||
return _DEVICE_CONFIGS[cmd]
|
||||
except KeyError:
|
||||
conn = connection(module)
|
||||
rc, out, err = conn.exec_command(cmd)
|
||||
if rc != 0:
|
||||
module.fail_json(msg='unable to retrieve current config', stderr=err)
|
||||
cfg = str(out).strip()
|
||||
_DEVICE_CONFIGS[cmd] = cfg
|
||||
return cfg
|
||||
|
||||
def run_commands(module, commands, check_rc=True):
|
||||
responses = list()
|
||||
for cmd in to_list(commands):
|
||||
conn = connection(module)
|
||||
rc, out, err = conn.exec_command(cmd)
|
||||
if check_rc and rc != 0:
|
||||
module.fail_json(msg=err, rc=rc)
|
||||
responses.append(out)
|
||||
return responses
|
||||
|
||||
def load_config(module, commands, commit=False, comment=None, save=False):
|
||||
commands.insert(0, 'configure')
|
||||
|
||||
for cmd in to_list(commands):
|
||||
conn = connection(module)
|
||||
rc, out, err = conn.exec_command(cmd, check_rc=False)
|
||||
if rc != 0:
|
||||
# discard any changes in case of failure
|
||||
conn.exec_command('exit discard')
|
||||
module.fail_json(msg='configuration failed')
|
||||
|
||||
diff = None
|
||||
if module._diff:
|
||||
rc, out, err = conn.exec_command('compare')
|
||||
if not out.startswith('No changes'):
|
||||
rc, out, err = conn.exec_command('show')
|
||||
diff = str(out).strip()
|
||||
|
||||
if commit:
|
||||
cmd = 'commit'
|
||||
if comment:
|
||||
cmd += ' comment "%s"' % comment
|
||||
conn.exec_command(cmd)
|
||||
|
||||
if save:
|
||||
conn.exec_command(cmd)
|
||||
|
||||
if not commit:
|
||||
conn.exec_command('exit discard')
|
||||
else:
|
||||
conn.exec_command('exit')
|
||||
|
||||
if diff:
|
||||
return diff
|
@ -0,0 +1,87 @@
|
||||
#
|
||||
# (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/>.
|
||||
#
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import sys
|
||||
import copy
|
||||
|
||||
from ansible.plugins.action.normal import ActionModule as _ActionModule
|
||||
from ansible.utils.path import unfrackpath
|
||||
from ansible.plugins import connection_loader
|
||||
from ansible.compat.six import iteritems
|
||||
from ansible.module_utils.vyos import vyos_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleFallbackNotFound
|
||||
from ansible.module_utils._text import to_bytes
|
||||
|
||||
class ActionModule(_ActionModule):
|
||||
|
||||
def run(self, tmp=None, task_vars=None):
|
||||
|
||||
pc = copy.deepcopy(self._play_context)
|
||||
pc.connection = 'network_cli'
|
||||
pc.port = provider['port'] or self._play_context.port
|
||||
pc.remote_user = provider['username'] or self._play_context.connection_user
|
||||
pc.password = provider['password'] or self._play_context.password
|
||||
|
||||
socket_path = self._get_socket_path(pc)
|
||||
if not os.path.exists(socket_path):
|
||||
# start the connection if it isn't started
|
||||
connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin)
|
||||
connection.exec_command('EXEC: show version')
|
||||
|
||||
task_vars['ansible_socket'] = socket_path
|
||||
|
||||
return super(ActionModule, self).run(tmp, task_vars)
|
||||
|
||||
def _get_socket_path(self, play_context):
|
||||
ssh = connection_loader.get('ssh', class_only=True)
|
||||
cp = ssh._create_control_path(play_context.remote_addr, play_context.port, play_context.remote_user)
|
||||
path = unfrackpath("$HOME/.ansible/pc")
|
||||
return cp % dict(directory=path)
|
||||
|
||||
def load_provider(self):
|
||||
provider = self._task.args.get('provider', {})
|
||||
for key, value in iteritems(eos_argument_spec):
|
||||
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
|
||||
self._task.args['provider'] = 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
|
||||
|
||||
|
||||
|
@ -1,75 +0,0 @@
|
||||
#
|
||||
# (c) 2015, Peter Sprygada <psprygada@ansible.com>
|
||||
#
|
||||
# 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/>.
|
||||
|
||||
|
||||
class ModuleDocFragment(object):
|
||||
|
||||
# Standard files documentation fragment
|
||||
DOCUMENTATION = """
|
||||
options:
|
||||
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.
|
||||
required: false
|
||||
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.
|
||||
required: false
|
||||
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.
|
||||
required: false
|
||||
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.
|
||||
require: false
|
||||
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.
|
||||
required: false
|
||||
provider:
|
||||
description:
|
||||
- Convenience method that allows all I(vyos) arguments to be passed as
|
||||
a dict object. All constraints (required, choices, etc) must be
|
||||
met either by individual arguments or values in this dict.
|
||||
required: false
|
||||
default: null
|
||||
|
||||
"""
|
@ -0,0 +1,113 @@
|
||||
# (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
|
||||
|
||||
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 TestVyosModule(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:
|
||||
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
|
||||
|
Loading…
Reference in New Issue