8000 New modules nxos_tms_global and nxos_tms_destgroup by mikewiebe · Pull Request #58018 · ansible/ansible · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

New modules nxos_tms_global and nxos_tms_destgroup #58018

New issue

Have a question about this project? Sign up for a free GitHub acco 8000 unt to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions lib/ansible/module_utils/network/nxos/nxos.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from ansible.module_utils.connection import Connection, ConnectionError
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 CustomNetworkConfig
from ansible.module_utils.six import iteritems, string_types, PY2, PY3
from ansible.module_utils.urls import fetch_url

Expand Down Expand Up @@ -741,6 +742,7 @@ def __init__(self, module, cmd_ref_str):
self._module = module
self._check_imports()
self._yaml_load(cmd_ref_str)
self.cache_existing = None
ref = self._ref

# Create a list of supported commands based on ref keys
Expand Down Expand Up @@ -931,7 +933,7 @@ def set_context(self, context=None):
# Last key in context is the resource key
ref['_resource_key'] = context[-1] if context else ref['_resource_key']

def get_existing(self):
def get_existing(self, cache_output=None):
"""Update ref with existing command states from the device.
Store these states in each command's 'existing' key.
"""
Expand All @@ -943,11 +945,17 @@ def get_existing(self):
return

show_cmd = ref['_template']['get_command']
if cache_output:
output = cache_output
else:
output = self.execute_show_command(show_cmd, 'text') or []
self.cache_existing = output

# Add additional command context if needed.
for filter in ref['_context']:
show_cmd = show_cmd + " | section '{0}'".format(filter)
if ref['_context']:
output = CustomNetworkConfig(indent=2, contents=output)
output = output.get_section(ref['_context'])

output = self.execute_show_command(show_cmd, 'text') or []
if not output:
# Add context to proposed if state is present
if 'present' in ref['_state']:
Expand Down
227 changes: 227 additions & 0 deletions lib/ansible/modules/network/nxos/nxos_tms_destgroup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
#!/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 <http://www.gnu.org/licenses/>.
#

ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}

DOCUMENTATION = '''
---
module: nxos_tms_destgroup
extends_documentation_fragment: nxos
version_added: "2.9"
short_description: Telemetry Monitoring Service (TMS) destination-group configuration
description:
- Manages Telemetry Monitoring Service (TMS) destination-group configuration.
author: Mike Wiebe (@mikewiebe)
notes:
- Tested against N9k Version 7.0(3)I7(5) and later.
- Not supported on N3K/N5K/N6K/N7K
- Module will automatically enable 'feature telemetry' if it is disabled.
options:
identifier:
description:
- Destination group identifier.
- Value must be a int representing the destination group identifier.
required: true
type: int
destination:
description:
- Group destination ipv4, port, protocol and encoding values.
- Value must be a dict defining values for keys (ip, port, protocol, encoding).
required: false
type: dict
aggregate:
description:
- Configure a list of nxos_tms_destgroup instances.
required: false
type: list
state:
description:
- Maka configuration present or absent on the device.
required: false
type: str
choices: ['present', 'absent']
default: 'present'
'''
EXAMPLES = '''
- name: Configure a single destination group instance
nxos_tms_destgroup:
identifier: 2
destination:
ip: 192.168.1.1
port: 50001
protocol: grpc
encoding: gpb

- name: Configure multiple destination group instances using aggregate.
nxos_tms_destgroup:
state: present
aggregate:
- { identifier: 28, destination: {ip: 192.168.0.2, port: 45001, protocol: gRPC, encoding: GPB}}
- { identifier: 2, destination: {ip: 192.168.0.1, port: 50001, protocol: gRPC, encoding: GPB}}
- { identifier: 2, destination: {ip: 192.168.0.2, port: 60001, protocol: gRPC, encoding: GPB}}
- { identifier: 10, destination: {ip: 192.168.0.1, port: 50001, protocol: gRPC, encoding: GPB}}
- { identifier: 10, destination: {ip: 192.168.0.2, port: 45001, protocol: gRPC, encoding: GPB}}
'''

RETURN = '''
cmds:
description: commands sent to the device
returned: always
type: list
sample: ["telemetry", "destination-group 2", "ip address 192.168.1.1 port 50001 protocol gRPC encoding GPB "]
'''

import re
from ansible.module_utils.network.nxos.nxos import NxosCmdRef
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.module_utils.network.nxos.nxos import load_config
from ansible.module_utils.basic import AnsibleModule

TMS_CMD_REF = '''
# The cmd_ref is a yaml formatted list of module commands.
# A leading underscore denotes a non-command variable; e.g. _template.
# TBD: Use Structured Where Possible
---
_template: # _template holds common settings for all commands
# Enable feature telemetry if disabled
feature: telemetry
# Common get syntax for TMS commands
get_command: show run telemetry all
# Parent configuration for TMS commands
context:
- telemetry

destination:
_exclude: ['N3K', 'N5K', 'N6k', 'N7k']
multiple: true
kind: dict
getval: ip address (?P<ip>\\S+) port (?P<port>\\S+) protocol (?P<protocol>\\S+) encoding (?P<encoding>\\S+)
setval: ip address {ip} port {port} protocol {protocol} encoding {encoding}
default:
ip: ~
port: ~
protocol: ~
encoding: ~
'''


def normalize_data(cmd_ref):
''' Normalize playbook values and get_exisiting data '''

playval = cmd_ref._ref.get('destination').get('playval')
existing = cmd_ref._ref.get('destination').get('existing')

keys = ['protocol', 'encoding']
if playval:
for key in keys:
playval[key] = playval[key].lower()
if existing:
for index in existing.keys():
for key in keys:
existing[index][key] = existing[index][key].lower()


def aggregate_input_validation(module, item):
''' Validate aggregate parameter values '''

if 'identifier' not in item:
msg = "aggregate item: {0} is missing required 'identifier' parameter".format(item)
module.fail_json(msg=msg)
if 'destination' in item and not isinstance(item['destination'], dict):
msg = "aggregate item: {0} parameter 'destination' must be a dict".format(item)
msg = msg + " defining values for keys: ip, port, protocol, encoding"
module.fail_json(msg=msg)
if 'destination' not in item and len(item) > 1:
msg = "aggregate item: {0} contains unrecognized parameters.".format(item)
msg = msg + " Make sure 'destination' parameter keys are specified as follows"
msg = msg + " destination: {ip: <ip>, port: <port>, protocol: <prot>, encoding: <enc>}}"
module.fail_json(msg=msg)


def get_aggregate_cmds(module):
''' Get list of commands from aggregate parameter '''

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: a little wordy. Consider:

    params = module.params

params = module.params
cache_existing = None
proposed_cmds = []
aggregate = params.get('aggregate')
for item in aggregate:
aggregate_input_validation(module, item)
for k, v in item.items():
if 'identifier' in k:
params['identifier'] = v
if 'destination' in k:
dest = {}
for k, v in v.items():
dest[k] = v
params['destination'] = dest
resource_key = 'destination-group {0}'.format(params['identifier'])
cmd_ref = NxosCmdRef(module, TMS_CMD_REF)
cmd_ref.set_context([resource_key])
if cache_existing:
cmd_ref.get_existing(cache_existing)
else:
cmd_ref.get_existing()
cache_existing = cmd_ref.cache_existing
cmd_ref.get_playvals()
normalize_data(cmd_ref)
cmds = cmd_ref.get_proposed()
proposed_cmds.extend(cmds)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm okay with the code above, just wondering if it would be good to disambiguate the multi-instance cmd_ref objects in this method's for loop from the single-instance cmd_ref in main() ?
e.g. make these mi_cmd_ref, agg_cmd_ref, etc.

Your call.

Copy link
Contributor Author
@mikewiebe mikewiebe Jun 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nah.. I plan to leave it as is. It's in a separate method so I think it's clear enough and besides the cmd_ref objects in get_aggregate_cmds are discarded and only the resulting command set is returned.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍
yup, just discombobulating the combobulated.


return proposed_cmds


def main():
argument_spec = dict(
identifier=dict(required=False, type='int'),
destination=dict(required=False, type='dict'),
aggregate=dict(required=False, type='list'),
state=dict(choices=['present', 'absent'], default='present', required=False),
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
warnings = list()
check_args(module, warnings)

if module.params.get('aggregate'):
cmds = get_aggregate_cmds(module)
else:
if not module.params.get('identifier'):
module.fail_json(msg='parameter: identifier is required')
resource_key = 'destination-group {0}'.format(module.params['identifier'])
cmd_ref = NxosCmdRef(module, TMS_CMD_REF)
cmd_ref.set_context([resource_key])
cmd_ref.get_existing()
cmd_ref.get_playvals()
normalize_data(cmd_ref)
cmds = cmd_ref.get_proposed()

result = {'changed': False, 'commands': cmds, 'warnings': warnings,
'check_mode': module.check_mode}
if cmds:
result['changed'] = True
if not module.check_mode:
load_config(module, cmds)

module.exit_json(**result)


if __name__ == '__main__':
main()
Loading
0