mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-05-07 05:42:50 +00:00
nso_action for Cisco NSO (#32781)
nso_action module for execution actions/RPCs in NSO.
This commit is contained in:
committed by
John R Barker
parent
29d3505cb4
commit
b2bc98c161
@@ -25,6 +25,13 @@ from ansible.module_utils.urls import open_url
|
||||
import json
|
||||
import re
|
||||
|
||||
try:
|
||||
unicode
|
||||
HAVE_UNICODE = True
|
||||
except NameError:
|
||||
unicode = str
|
||||
HAVE_UNICODE = False
|
||||
|
||||
|
||||
nso_argument_spec = dict(
|
||||
url=dict(required=True),
|
||||
@@ -484,3 +491,66 @@ def verify_version(client):
|
||||
(version[1] == 4 and (len(version) < 3 or version[2] < 3))):
|
||||
raise ModuleFailException(
|
||||
'unsupported NSO version {0}, only 4.4.3 or later is supported'.format(version_str))
|
||||
|
||||
|
||||
def normalize_value(expected_value, value, key):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(expected_value, bool):
|
||||
return value == 'true'
|
||||
if isinstance(expected_value, int):
|
||||
try:
|
||||
return int(value)
|
||||
except TypeError:
|
||||
raise ModuleFailException(
|
||||
'returned value {0} for {1} is not a valid integer'.format(
|
||||
key, value))
|
||||
if isinstance(expected_value, float):
|
||||
try:
|
||||
return float(value)
|
||||
except TypeError:
|
||||
raise ModuleFailException(
|
||||
'returned value {0} for {1} is not a valid float'.format(
|
||||
key, value))
|
||||
if isinstance(expected_value, (list, tuple)):
|
||||
if not isinstance(value, (list, tuple)):
|
||||
raise ModuleFailException(
|
||||
'returned value {0} for {1} is not a list'.format(value, key))
|
||||
if len(expected_value) != len(value):
|
||||
raise ModuleFailException(
|
||||
'list length mismatch for {0}'.format(key))
|
||||
|
||||
normalized_value = []
|
||||
for i in range(len(expected_value)):
|
||||
normalized_value.append(
|
||||
normalize_value(expected_value[i], value[i], '{0}[{1}]'.format(key, i)))
|
||||
return normalized_value
|
||||
|
||||
if isinstance(expected_value, dict):
|
||||
if not isinstance(value, dict):
|
||||
raise ModuleFailException(
|
||||
'returned value {0} for {1} is not a dict'.format(value, key))
|
||||
if len(expected_value) != len(value):
|
||||
raise ModuleFailException(
|
||||
'dict length mismatch for {0}'.format(key))
|
||||
|
||||
normalized_value = {}
|
||||
for k in expected_value.keys():
|
||||
n_k = normalize_value(k, k, '{0}[{1}]'.format(key, k))
|
||||
if n_k not in value:
|
||||
raise ModuleFailException('missing {0} in value'.format(n_k))
|
||||
normalized_value[n_k] = normalize_value(expected_value[k], value[k], '{0}[{1}]'.format(key, k))
|
||||
return normalized_value
|
||||
|
||||
if HAVE_UNICODE:
|
||||
if isinstance(expected_value, unicode) and isinstance(value, str):
|
||||
return value.decode('utf-8')
|
||||
if isinstance(expected_value, str) and isinstance(value, unicode):
|
||||
return value.encode('utf-8')
|
||||
else:
|
||||
if hasattr(expected_value, 'encode') and hasattr(value, 'decode'):
|
||||
return value.decode('utf-8')
|
||||
if hasattr(expected_value, 'decode') and hasattr(value, 'encode'):
|
||||
return value.encode('utf-8')
|
||||
|
||||
return value
|
||||
|
||||
182
lib/ansible/modules/network/nso/nso_action.py
Normal file
182
lib/ansible/modules/network/nso/nso_action.py
Normal file
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2017 Cisco and/or its affiliates.
|
||||
#
|
||||
# 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
|
||||
|
||||
ANSIBLE_METADATA = {
|
||||
'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'
|
||||
}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: nso_action
|
||||
extends_documentation_fragment: nso
|
||||
short_description: Executes Cisco NSO actions and verifies output.
|
||||
description:
|
||||
- This module provices support for executing Cisco NSO actions and then
|
||||
verifying that the output is as expected.
|
||||
author: "Claes Nästén (@cnasten)"
|
||||
options:
|
||||
path:
|
||||
description: Path to NSO action.
|
||||
required: true
|
||||
input:
|
||||
description: >
|
||||
NSO action parameters.
|
||||
output_required:
|
||||
description: >
|
||||
Required output parameters.
|
||||
output_invalid:
|
||||
description: >
|
||||
List of result parameter names that will cause the task to fail if they
|
||||
are present.
|
||||
validate_strict:
|
||||
description: >
|
||||
If set to true, the task will fail if any output parameters not in
|
||||
output_required is present in the output.
|
||||
version_added: "2.5"
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Sync NSO device
|
||||
nso_config:
|
||||
url: http://localhost:8080/jsonrpc
|
||||
username: username
|
||||
password: password
|
||||
path: /ncs:devices/device{ce0}/sync-from
|
||||
output_required:
|
||||
result: true
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
output:
|
||||
description: Action output
|
||||
returned: success
|
||||
type: dict
|
||||
sample:
|
||||
result: true
|
||||
'''
|
||||
|
||||
from ansible.module_utils.network.nso.nso import connect, verify_version, nso_argument_spec
|
||||
from ansible.module_utils.network.nso.nso import normalize_value
|
||||
from ansible.module_utils.network.nso.nso import ModuleFailException, NsoException
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
|
||||
|
||||
class NsoAction(object):
|
||||
def __init__(self, check_mode, client,
|
||||
path, input,
|
||||
output_required, output_invalid, validate_strict):
|
||||
self._check_mode = check_mode
|
||||
self._client = client
|
||||
self._path = path
|
||||
self._input = input
|
||||
self._output_required = output_required
|
||||
self._output_invalid = output_invalid
|
||||
self._validate_strict = validate_strict
|
||||
|
||||
def main(self):
|
||||
schema = self._client.get_schema(path=self._path)
|
||||
if schema['data']['kind'] != 'action':
|
||||
raise ModuleFailException('{0} is not an action'.format(self._path))
|
||||
|
||||
input_schema = [c for c in schema['data']['children']
|
||||
if c.get('is_action_input', False)]
|
||||
|
||||
for key, value in self._input.items():
|
||||
child = next((c for c in input_schema if c['name'] == key), None)
|
||||
if child is None:
|
||||
raise ModuleFailException('no parameter {0}'.format(key))
|
||||
|
||||
# implement type validation in the future
|
||||
|
||||
if self._check_mode:
|
||||
return {}
|
||||
else:
|
||||
return self._run_and_verify()
|
||||
|
||||
def _run_and_verify(self):
|
||||
output = self._client.run_action(None, self._path, self._input)
|
||||
for key, value in self._output_required.items():
|
||||
if key not in output:
|
||||
raise ModuleFailException('{0} not in result'.format(key))
|
||||
|
||||
n_value = normalize_value(value, output[key], key)
|
||||
if value != n_value:
|
||||
msg = '{0} value mismatch. expected {1} got {2}'.format(
|
||||
key, value, n_value)
|
||||
raise ModuleFailException(msg)
|
||||
|
||||
for key in self._output_invalid.keys():
|
||||
if key in output:
|
||||
raise ModuleFailException('{0} not allowed in result'.format(key))
|
||||
|
||||
if self._validate_strict:
|
||||
for name in output.keys():
|
||||
if name not in self._output_required:
|
||||
raise ModuleFailException('{0} not allowed in result'.format(name))
|
||||
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = dict(
|
||||
path=dict(required=True),
|
||||
input=dict(required=False, type='dict', default={}),
|
||||
output_required=dict(required=False, type='dict', default={}),
|
||||
output_invalid=dict(required=False, type='dict', default={}),
|
||||
validate_strict=dict(required=False, type='bool', default=False)
|
||||
)
|
||||
argument_spec.update(nso_argument_spec)
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=argument_spec,
|
||||
supports_check_mode=True
|
||||
)
|
||||
p = module.params
|
||||
|
||||
client = connect(p)
|
||||
nso_action = NsoAction(
|
||||
module.check_mode, client,
|
||||
p['path'],
|
||||
p['input'],
|
||||
p['output_required'],
|
||||
p['output_invalid'],
|
||||
p['validate_strict'])
|
||||
try:
|
||||
verify_version(client)
|
||||
|
||||
output = nso_action.main()
|
||||
client.logout()
|
||||
module.exit_json(changed=True, output=output)
|
||||
except NsoException as ex:
|
||||
client.logout()
|
||||
module.fail_json(msg=ex.message)
|
||||
except ModuleFailException as ex:
|
||||
client.logout()
|
||||
module.fail_json(msg=ex.message)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -34,4 +34,6 @@ options:
|
||||
password:
|
||||
description: NSO password
|
||||
required: true
|
||||
requirements:
|
||||
- Cisco NSO version 4.4.3 or higher
|
||||
'''
|
||||
|
||||
Reference in New Issue
Block a user