mirror of
https://github.com/ansible-collections/community.general.git
synced 2025-07-22 12:50:22 -07:00
Modifying cnos-facts, cnos_command and cnos-config in line with the design followed in Ansible. Adding unit test cases for these modules. Added plugins to support them. (#39955)
* Modifying cnos-facts, cnos_command and cnos-config in line with the design followed in Ansible. Adding unit test cases for these modules. Added plugins to support them. * Removing doc fragment conflicts with other modules * Replacing show with display
This commit is contained in:
parent
30f992f260
commit
1cb4619c9a
27 changed files with 3395 additions and 216 deletions
|
@ -1,166 +1,271 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
#
|
||||
# Copyright (C) 2017 Lenovo, Inc.
|
||||
# (C) 2017 Red Hat Inc.
|
||||
# Copyright (C) 2017 Lenovo.
|
||||
#
|
||||
# This file is part of Ansible
|
||||
# GNU General Public License v3.0+
|
||||
#
|
||||
# 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,
|
||||
# This program 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/>.
|
||||
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
#
|
||||
# Module to send CLI commands to Lenovo Switches
|
||||
# Module to execute CNOS Commands on Lenovo Switches.
|
||||
# Lenovo Networking
|
||||
#
|
||||
#
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
DOCUMENTATION = """
|
||||
---
|
||||
module: cnos_command
|
||||
author: "Dave Kasberg (@dkasberg)"
|
||||
short_description: Execute a single command on devices running Lenovo CNOS
|
||||
version_added: "2.6"
|
||||
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
|
||||
short_description: Run arbitrary commands on Lenovo CNOS devices
|
||||
description:
|
||||
- This module allows you to modify the switch running configuration. It provides a way to
|
||||
execute a single CNOS command on a switch by evaluating the current running configuration
|
||||
and executing the command only if the specific setting has not been already configured.
|
||||
The CNOS command is passed as an argument of the method.
|
||||
This module uses SSH to manage network device configuration.
|
||||
The results of the operation will be placed in a directory named 'results'
|
||||
that must be created by the user in their local directory to where the playbook is run.
|
||||
For more information about this module from Lenovo and customizing it usage for your
|
||||
use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_command.html)
|
||||
version_added: "2.3"
|
||||
extends_documentation_fragment: cnos
|
||||
- Sends arbitrary commands to an CNOS node and returns the results
|
||||
read from the device. The C(cnos_command) 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.
|
||||
options:
|
||||
clicommand:
|
||||
provider:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- A dict object containing connection details.
|
||||
suboptions:
|
||||
host:
|
||||
description:
|
||||
- This specifies the CLI command as an attribute to this method. The command is
|
||||
passed using double quotes. The variables can be placed directly on to the CLI
|
||||
commands or can be invoked from the vars directory.
|
||||
- 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
|
||||
default: Null
|
||||
'''
|
||||
EXAMPLES = '''
|
||||
Tasks : The following are examples of using the module cnos_command. These are written in the main.yml file of the tasks directory.
|
||||
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.
|
||||
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.
|
||||
commands:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- List of commands to send to the remote 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 retires as expired.
|
||||
required: true
|
||||
wait_for:
|
||||
version_added: "2.6"
|
||||
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.
|
||||
match:
|
||||
version_added: "2.6"
|
||||
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.
|
||||
default: all
|
||||
choices: ['any', 'all']
|
||||
retries:
|
||||
version_added: "2.6"
|
||||
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.
|
||||
default: 10
|
||||
interval:
|
||||
version_added: "2.6"
|
||||
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.
|
||||
default: 1
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
# Note: examples below use the following provider dict to handle
|
||||
# transport and authentication to the node.
|
||||
---
|
||||
- name: Test Command
|
||||
vars:
|
||||
cli:
|
||||
host: "{{ inventory_hostname }}"
|
||||
port: 22
|
||||
username: admin
|
||||
password: admin
|
||||
timeout: 30
|
||||
|
||||
---
|
||||
- name: test contains operator
|
||||
cnos_command:
|
||||
host: "{{ inventory_hostname }}"
|
||||
username: "{{ hostvars[inventory_hostname]['username'] }}"
|
||||
password: "{{ hostvars[inventory_hostname]['password'] }}"
|
||||
enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"
|
||||
deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"
|
||||
outputfile: "./results/test_command_{{ inventory_hostname }}_output.txt"
|
||||
clicommand: "display users"
|
||||
commands:
|
||||
- show version
|
||||
- show system memory
|
||||
wait_for:
|
||||
- "result[0] contains 'Lenovo'"
|
||||
- "result[1] contains 'MemFree'"
|
||||
provider: "{{ cli }}"
|
||||
register: result
|
||||
|
||||
'''
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
- assert:
|
||||
that:
|
||||
- "result.changed == false"
|
||||
- "result.stdout is defined"
|
||||
|
||||
- name: get output for single command
|
||||
cnos_command:
|
||||
commands: ['show version']
|
||||
provider: "{{ cli }}"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- "result.changed == false"
|
||||
- "result.stdout is defined"
|
||||
|
||||
- name: get output for multiple commands
|
||||
cnos_command:
|
||||
commands:
|
||||
- show version
|
||||
- show interface information
|
||||
provider: "{{ cli }}"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- "result.changed == false"
|
||||
- "result.stdout is defined"
|
||||
- "result.stdout | length == 2"
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
stdout:
|
||||
description: the set of responses from the commands
|
||||
returned: always
|
||||
type: string
|
||||
sample: "Command Applied"
|
||||
'''
|
||||
type: list
|
||||
sample: ['...', '...']
|
||||
stdout_lines:
|
||||
description: The value of stdout split into a list
|
||||
returned: always
|
||||
type: list
|
||||
sample: [['...', '...'], ['...'], ['...']]
|
||||
failed_conditions:
|
||||
description: the conditionals that failed
|
||||
returned: failed
|
||||
type: list
|
||||
sample: ['...', '...']
|
||||
"""
|
||||
|
||||
import sys
|
||||
try:
|
||||
import paramiko
|
||||
HAS_PARAMIKO = True
|
||||
except ImportError:
|
||||
HAS_PARAMIKO = False
|
||||
import time
|
||||
import socket
|
||||
import array
|
||||
import json
|
||||
import time
|
||||
import re
|
||||
try:
|
||||
from ansible.module_utils.network.cnos import cnos
|
||||
HAS_LIB = True
|
||||
except:
|
||||
HAS_LIB = False
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from collections import defaultdict
|
||||
from ansible.module_utils.network.cnos.cnos import run_commands, check_args
|
||||
from ansible.module_utils.network.cnos.cnos import cnos_argument_spec
|
||||
from ansible.module_utils.network.common.parsing 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 main():
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
clicommand=dict(required=True),
|
||||
outputfile=dict(required=True),
|
||||
host=dict(required=True),
|
||||
deviceType=dict(required=True),
|
||||
username=dict(required=True),
|
||||
password=dict(required=True, no_log=True),
|
||||
enablePassword=dict(required=False, no_log=True),),
|
||||
supports_check_mode=False)
|
||||
spec = dict(
|
||||
# { command: <str>, prompt: <str>, response: <str> }
|
||||
commands=dict(type='list', required=True),
|
||||
|
||||
username = module.params['username']
|
||||
password = module.params['password']
|
||||
enablePassword = module.params['enablePassword']
|
||||
cliCommand = module.params['clicommand']
|
||||
deviceType = module.params['deviceType']
|
||||
outputfile = module.params['outputfile']
|
||||
hostIP = module.params['host']
|
||||
output = ""
|
||||
if not HAS_PARAMIKO:
|
||||
module.fail_json(msg='paramiko is required for this module')
|
||||
wait_for=dict(type='list'),
|
||||
match=dict(default='all', choices=['all', 'any']),
|
||||
|
||||
# Create instance of SSHClient object
|
||||
remote_conn_pre = paramiko.SSHClient()
|
||||
retries=dict(default=10, type='int'),
|
||||
interval=dict(default=1, type='int')
|
||||
)
|
||||
|
||||
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
|
||||
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
spec.update(cnos_argument_spec)
|
||||
|
||||
# initiate SSH connection with the switch
|
||||
remote_conn_pre.connect(hostIP, username=username, password=password)
|
||||
time.sleep(2)
|
||||
module = AnsibleModule(argument_spec=spec, supports_check_mode=True)
|
||||
result = {'changed': False}
|
||||
|
||||
# Use invoke_shell to establish an 'interactive session'
|
||||
remote_conn = remote_conn_pre.invoke_shell()
|
||||
time.sleep(2)
|
||||
wait_for = module.params['wait_for'] or list()
|
||||
conditionals = [Conditional(c) for c in wait_for]
|
||||
|
||||
# Enable and enter configure terminal then send command
|
||||
output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn)
|
||||
commands = module.params['commands']
|
||||
retries = module.params['retries']
|
||||
interval = module.params['interval']
|
||||
match = module.params['match']
|
||||
|
||||
output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn)
|
||||
while retries > 0:
|
||||
responses = run_commands(module, commands)
|
||||
|
||||
# Make terminal length = 0
|
||||
output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn)
|
||||
for item in list(conditionals):
|
||||
if item(responses):
|
||||
if match == 'any':
|
||||
conditionals = list()
|
||||
break
|
||||
conditionals.remove(item)
|
||||
|
||||
# Go to config mode
|
||||
output = output + cnos.waitForDeviceResponse("configure d\n", "(config)#", 2, remote_conn)
|
||||
if not conditionals:
|
||||
break
|
||||
|
||||
# Send the CLi command
|
||||
output = output + cnos.waitForDeviceResponse(cliCommand + "\n", "(config)#", 2, remote_conn)
|
||||
time.sleep(interval)
|
||||
retries -= 1
|
||||
|
||||
# Save it into the file
|
||||
file = open(outputfile, "a")
|
||||
file.write(output)
|
||||
file.close()
|
||||
if conditionals:
|
||||
failed_conditions = [item.raw for item in conditionals]
|
||||
msg = 'One or more conditional statements have not been 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)
|
||||
|
||||
# Logic to check when changes occur or not
|
||||
errorMsg = cnos.checkOutputForError(output)
|
||||
if(errorMsg is None):
|
||||
module.exit_json(changed=True, msg="CLI command executed and results saved in file ")
|
||||
else:
|
||||
module.fail_json(msg=errorMsg)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
317
lib/ansible/modules/network/cnos/cnos_config.py
Normal file
317
lib/ansible/modules/network/cnos/cnos_config.py
Normal file
|
@ -0,0 +1,317 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# (C) 2017 Red Hat Inc.
|
||||
# Copyright (C) 2017 Lenovo.
|
||||
#
|
||||
# GNU General Public License v3.0+
|
||||
#
|
||||
# This program 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.
|
||||
#
|
||||
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
#
|
||||
# Module to configure Lenovo Switches.
|
||||
# Lenovo Networking
|
||||
#
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = """
|
||||
---
|
||||
module: cnos_config
|
||||
version_added: "2.6"
|
||||
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
|
||||
short_description: Manage Lenovo CNOS configuration sections
|
||||
description:
|
||||
- Lenovo CNOS configurations use a simple block indent file syntax
|
||||
for segmenting configuration into sections. This module provides
|
||||
an implementation for working with CNOS configuration sections in
|
||||
a deterministic way.
|
||||
notes:
|
||||
- Tested against CNOS 10.8.0.42
|
||||
options:
|
||||
provider:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- A dict object containing connection details.
|
||||
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.
|
||||
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.
|
||||
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 ordered set of parents that uniquely identify the section
|
||||
the commands should be checked against. If the parents argument
|
||||
is omitted, the commands are checked against the set of top
|
||||
level or global 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.
|
||||
default: line
|
||||
choices: ['line', 'strict', 'exact', 'none']
|
||||
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', 'config']
|
||||
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(config) argument allows the
|
||||
implementer to pass in the configuration to use as the base
|
||||
config for comparison.
|
||||
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. If the directory does not
|
||||
exist, it is created.
|
||||
type: bool
|
||||
default: 'no'
|
||||
comment:
|
||||
description:
|
||||
- Allows a commit description to be specified to be included
|
||||
when the configuration is committed. If the configuration is
|
||||
not changed or committed, this argument is ignored.
|
||||
default: 'configured by cnos_config'
|
||||
admin:
|
||||
description:
|
||||
- Enters into administration configuration mode for making config
|
||||
changes to the device.
|
||||
type: bool
|
||||
default: 'no'
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
Tasks: The following are examples of using the module cnos_config.
|
||||
---
|
||||
- name: configure top level configuration
|
||||
cnos_config:
|
||||
"lines: hostname {{ inventory_hostname }}"
|
||||
|
||||
- name: configure interface settings
|
||||
cnos_config:
|
||||
lines:
|
||||
- enable
|
||||
- ip ospf enable
|
||||
parents: interface ip 13
|
||||
|
||||
- name: load a config from disk and replace the current config
|
||||
cnos_config:
|
||||
src: config.cfg
|
||||
backup: yes
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
updates:
|
||||
description: The set of commands that will be pushed to the remote device
|
||||
returned: Only when lines is specified.
|
||||
type: list
|
||||
sample: ['...', '...']
|
||||
backup_path:
|
||||
description: The full path to the backup file
|
||||
returned: when backup is yes
|
||||
type: string
|
||||
sample: /playbooks/ansible/backup/cnos01.2016-07-16@22:28:34
|
||||
"""
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils.network.cnos.cnos import load_config, get_config
|
||||
from ansible.module_utils.network.cnos.cnos import cnos_argument_spec
|
||||
from ansible.module_utils.network.cnos.cnos import check_args
|
||||
from ansible.module_utils.network.common.config import NetworkConfig, dumps
|
||||
|
||||
|
||||
DEFAULT_COMMIT_COMMENT = 'configured by cnos_config'
|
||||
|
||||
|
||||
def get_running_config(module):
|
||||
contents = module.params['config']
|
||||
if not contents:
|
||||
contents = get_config(module)
|
||||
return NetworkConfig(indent=1, contents=contents)
|
||||
|
||||
|
||||
def get_candidate(module):
|
||||
candidate = NetworkConfig(indent=1)
|
||||
if module.params['src']:
|
||||
candidate.load(module.params['src'])
|
||||
elif module.params['lines']:
|
||||
parents = module.params['parents'] or list()
|
||||
candidate.add(module.params['lines'], parents=parents)
|
||||
return candidate
|
||||
|
||||
|
||||
def run(module, result):
|
||||
match = module.params['match']
|
||||
replace = module.params['replace']
|
||||
replace_config = replace == 'config'
|
||||
path = module.params['parents']
|
||||
comment = module.params['comment']
|
||||
admin = module.params['admin']
|
||||
check_mode = module.check_mode
|
||||
|
||||
candidate = get_candidate(module)
|
||||
|
||||
if match != 'none' and replace != 'config':
|
||||
contents = get_running_config(module)
|
||||
configobj = NetworkConfig(contents=contents, indent=1)
|
||||
commands = candidate.difference(configobj, path=path, match=match,
|
||||
replace=replace)
|
||||
else:
|
||||
commands = candidate.items
|
||||
|
||||
if commands:
|
||||
commands = dumps(commands, 'commands').split('\n')
|
||||
|
||||
if any((module.params['lines'], module.params['src'])):
|
||||
if module.params['before']:
|
||||
commands[:0] = module.params['before']
|
||||
|
||||
if module.params['after']:
|
||||
commands.extend(module.params['after'])
|
||||
|
||||
result['commands'] = commands
|
||||
|
||||
diff = load_config(module, commands)
|
||||
if diff:
|
||||
result['diff'] = dict(prepared=diff)
|
||||
result['changed'] = True
|
||||
|
||||
|
||||
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', 'config']),
|
||||
|
||||
config=dict(),
|
||||
backup=dict(type='bool', default=False),
|
||||
comment=dict(default=DEFAULT_COMMIT_COMMENT),
|
||||
admin=dict(type='bool', default=False)
|
||||
)
|
||||
|
||||
argument_spec.update(cnos_argument_spec)
|
||||
|
||||
mutually_exclusive = [('lines', 'src'),
|
||||
('parents', 'src')]
|
||||
|
||||
required_if = [('match', 'strict', ['lines']),
|
||||
('match', 'exact', ['lines']),
|
||||
('replace', 'block', ['lines']),
|
||||
('replace', 'config', ['src'])]
|
||||
|
||||
module = AnsibleModule(argument_spec=argument_spec,
|
||||
mutually_exclusive=mutually_exclusive,
|
||||
required_if=required_if,
|
||||
supports_check_mode=True)
|
||||
|
||||
warnings = list()
|
||||
check_args(module, warnings)
|
||||
|
||||
result = dict(changed=False, warnings=warnings)
|
||||
|
||||
if module.params['backup']:
|
||||
result['__backup__'] = get_config(module)
|
||||
|
||||
run(module, result)
|
||||
|
||||
module.exit_json(**result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
|
@ -1,146 +1,594 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
#
|
||||
# Copyright (C) 2017 Lenovo, Inc.
|
||||
# (C) 2017 Red Hat Inc.
|
||||
# Copyright (C) 2017 Lenovo.
|
||||
#
|
||||
# This file is part of Ansible
|
||||
# GNU General Public License v3.0+
|
||||
#
|
||||
# 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,
|
||||
# This program 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/>.
|
||||
#
|
||||
# Module to show sys info of Lenovo Switches
|
||||
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
# Module to Collect facts from Lenovo Switches running Lenovo CNOS commands
|
||||
# Lenovo Networking
|
||||
#
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: cnos_facts
|
||||
author: "Dave Kasberg (@dkasberg)"
|
||||
short_description: Collect facts on devices running Lenovo CNOS
|
||||
description:
|
||||
- This module allows you to view the switch information. It executes the show sysinfo CLI command on a switch
|
||||
and returns a file containing all the system information of the target network device. This module uses SSH to
|
||||
manage network device configuration. The results of the operation can be viewed in results directory.
|
||||
For more information about this module from Lenovo and customizing it usage for your
|
||||
use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_facts.html)
|
||||
version_added: "2.3"
|
||||
extends_documentation_fragment: cnos
|
||||
options: {}
|
||||
|
||||
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
|
||||
short_description: Collect facts from remote devices running Lenovo CNOS
|
||||
description:
|
||||
- Collects a base set of device facts from a remote Lenovo device
|
||||
running on CNOS. This module prepends all of the
|
||||
base network fact keys with C(ansible_net_<fact>). The facts
|
||||
module will always collect a base set of facts from the device
|
||||
and can enable or disable collection of additional facts.
|
||||
notes:
|
||||
- Tested against CNOS 10.8.0.42
|
||||
options:
|
||||
authorize:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- Instructs the module to enter privileged mode on the remote device
|
||||
before sending any commands. If not specified, the device will
|
||||
attempt to execute all commands in non-privileged mode. If the value
|
||||
is not specified in the task, the value of environment variable
|
||||
C(ANSIBLE_NET_AUTHORIZE) will be used instead.
|
||||
type: bool
|
||||
default: 'no'
|
||||
auth_pass:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- Specifies the password to use if required to enter privileged mode
|
||||
on the remote device. If I(authorize) is false, then this argument
|
||||
does nothing. If the value is not specified in the task, the value of
|
||||
environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead.
|
||||
provider:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- A dict object containing connection details.
|
||||
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.
|
||||
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.
|
||||
gather_subset:
|
||||
version_added: "2.6"
|
||||
description:
|
||||
- When supplied, this argument will restrict the facts collected
|
||||
to a given subset. Possible values for this argument include
|
||||
all, hardware, config, and interfaces. Can specify a list of
|
||||
values to include a larger subset. Values can also be used
|
||||
with an initial C(M(!)) to specify that a specific subset should
|
||||
not be collected.
|
||||
required: false
|
||||
default: '!config'
|
||||
'''
|
||||
EXAMPLES = '''
|
||||
Tasks : The following are examples of using the module cnos_facts. These are written in the main.yml file of the tasks directory.
|
||||
Tasks: The following are examples of using the module cnos_facts.
|
||||
---
|
||||
- name: Test Sys Info
|
||||
- name: Test cnos Facts
|
||||
cnos_facts:
|
||||
provider={{ cli }}
|
||||
|
||||
vars:
|
||||
cli:
|
||||
host: "{{ inventory_hostname }}"
|
||||
username: "{{ hostvars[inventory_hostname]['username'] }}"
|
||||
password: "{{ hostvars[inventory_hostname]['password'] }}"
|
||||
deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}"
|
||||
enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}"
|
||||
outputfile: "./results/cnos_facts_{{ inventory_hostname }}_output.txt"
|
||||
port: 22
|
||||
username: admin
|
||||
password: admin
|
||||
transport: cli
|
||||
timeout: 30
|
||||
authorize: True
|
||||
auth_pass:
|
||||
|
||||
---
|
||||
# Collect all facts from the device
|
||||
- cnos_facts:
|
||||
gather_subset: all
|
||||
provider: "{{ cli }}"
|
||||
|
||||
# Collect only the config and default facts
|
||||
- cnos_facts:
|
||||
gather_subset:
|
||||
- config
|
||||
provider: "{{ cli }}"
|
||||
|
||||
# Do not collect hardware facts
|
||||
- cnos_facts:
|
||||
gather_subset:
|
||||
- "!hardware"
|
||||
provider: "{{ cli }}"
|
||||
'''
|
||||
RETURN = '''
|
||||
msg:
|
||||
description: Success or failure message
|
||||
returned: always
|
||||
type: string
|
||||
sample: "Device Sys Info is saved to file"
|
||||
ansible_net_gather_subset:
|
||||
description: The list of fact subsets collected from the device
|
||||
returned: always
|
||||
type: list
|
||||
# default
|
||||
ansible_net_model:
|
||||
description: The model name returned from the Lenovo CNOS device
|
||||
returned: always
|
||||
type: str
|
||||
ansible_net_serialnum:
|
||||
description: The serial number of the Lenovo CNOS device
|
||||
returned: always
|
||||
type: str
|
||||
ansible_net_version:
|
||||
description: The CNOS operating system version running on the remote device
|
||||
returned: always
|
||||
type: str
|
||||
ansible_net_hostname:
|
||||
description: The configured hostname of the device
|
||||
returned: always
|
||||
type: string
|
||||
ansible_net_image:
|
||||
description: Indicates the active image for the device
|
||||
returned: always
|
||||
type: string
|
||||
# hardware
|
||||
ansible_net_memfree_mb:
|
||||
description: The available free memory on the remote device in MB
|
||||
returned: when hardware is configured
|
||||
type: int
|
||||
# config
|
||||
ansible_net_config:
|
||||
description: The current active config from the device
|
||||
returned: when config is configured
|
||||
type: str
|
||||
# interfaces
|
||||
ansible_net_all_ipv4_addresses:
|
||||
description: All IPv4 addresses configured on the device
|
||||
returned: when interfaces is configured
|
||||
type: list
|
||||
ansible_net_all_ipv6_addresses:
|
||||
description: All IPv6 addresses configured on the device
|
||||
returned: when interfaces is configured
|
||||
type: list
|
||||
ansible_net_interfaces:
|
||||
description: A hash of all interfaces running on the system.
|
||||
This gives information on description, mac address, mtu, speed,
|
||||
duplex and operstatus
|
||||
returned: when interfaces is configured
|
||||
type: dict
|
||||
ansible_net_neighbors:
|
||||
description: The list of LLDP neighbors from the remote device
|
||||
returned: when interfaces is configured
|
||||
type: dict
|
||||
'''
|
||||
|
||||
import sys
|
||||
try:
|
||||
import paramiko
|
||||
HAS_PARAMIKO = True
|
||||
except ImportError:
|
||||
HAS_PARAMIKO = False
|
||||
import time
|
||||
import socket
|
||||
import array
|
||||
import json
|
||||
import time
|
||||
import re
|
||||
try:
|
||||
from ansible.module_utils.network.cnos import cnos
|
||||
HAS_LIB = True
|
||||
except:
|
||||
HAS_LIB = False
|
||||
|
||||
from ansible.module_utils.network.cnos.cnos import run_commands
|
||||
from ansible.module_utils.network.cnos.cnos import cnos_argument_spec
|
||||
from ansible.module_utils.network.cnos.cnos import check_args
|
||||
from ansible.module_utils._text import to_text
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from collections import defaultdict
|
||||
from ansible.module_utils.six import iteritems
|
||||
from ansible.module_utils.six.moves import zip
|
||||
|
||||
|
||||
class FactsBase(object):
|
||||
|
||||
COMMANDS = list()
|
||||
|
||||
def __init__(self, module):
|
||||
self.module = module
|
||||
self.facts = dict()
|
||||
self.responses = None
|
||||
self.PERSISTENT_COMMAND_TIMEOUT = 60
|
||||
|
||||
def populate(self):
|
||||
self.responses = run_commands(self.module, self.COMMANDS,
|
||||
check_rc=False)
|
||||
|
||||
def run(self, cmd):
|
||||
return run_commands(self.module, cmd, check_rc=False)
|
||||
|
||||
|
||||
class Default(FactsBase):
|
||||
|
||||
COMMANDS = ['display sys-info', 'display running-config']
|
||||
|
||||
def populate(self):
|
||||
super(Default, self).populate()
|
||||
data = self.responses[0]
|
||||
data_run = self.responses[1]
|
||||
if data:
|
||||
self.facts['version'] = self.parse_version(data)
|
||||
self.facts['serialnum'] = self.parse_serialnum(data)
|
||||
self.facts['model'] = self.parse_model(data)
|
||||
self.facts['image'] = self.parse_image(data)
|
||||
if data_run:
|
||||
self.facts['hostname'] = self.parse_hostname(data_run)
|
||||
|
||||
def parse_version(self, data):
|
||||
for line in data.split('\n'):
|
||||
line = line.strip()
|
||||
match = re.match(r'System Software Revision (.*?)',
|
||||
line, re.M | re.I)
|
||||
if match:
|
||||
vers = line.split(':')
|
||||
ver = vers[1].strip()
|
||||
return ver
|
||||
return "NA"
|
||||
|
||||
def parse_hostname(self, data_run):
|
||||
for line in data_run.split('\n'):
|
||||
line = line.strip()
|
||||
match = re.match(r'hostname (.*?)', line, re.M | re.I)
|
||||
if match:
|
||||
hosts = line.split()
|
||||
hostname = hosts[1].strip('\"')
|
||||
return hostname
|
||||
return "NA"
|
||||
|
||||
def parse_model(self, data):
|
||||
for line in data.split('\n'):
|
||||
line = line.strip()
|
||||
match = re.match(r'System Model (.*?)', line, re.M | re.I)
|
||||
if match:
|
||||
mdls = line.split(':')
|
||||
mdl = mdls[1].strip()
|
||||
return mdl
|
||||
return "NA"
|
||||
|
||||
def parse_image(self, data):
|
||||
match = re.search(r'(.*) image1(.*)', data, re.M | re.I)
|
||||
if match:
|
||||
return "Image1"
|
||||
else:
|
||||
return "Image1"
|
||||
|
||||
def parse_serialnum(self, data):
|
||||
for line in data.split('\n'):
|
||||
line = line.strip()
|
||||
match = re.match(r'System Serial Number (.*?)', line, re.M | re.I)
|
||||
if match:
|
||||
serNums = line.split(':')
|
||||
ser = serNums[1].strip()
|
||||
return ser
|
||||
return "NA"
|
||||
|
||||
|
||||
class Hardware(FactsBase):
|
||||
|
||||
COMMANDS = [
|
||||
'display running-config'
|
||||
]
|
||||
|
||||
def populate(self):
|
||||
super(Hardware, self).populate()
|
||||
data = self.run(['display process memory'])
|
||||
data = to_text(data, errors='surrogate_or_strict').strip()
|
||||
data = data.replace(r"\n", "\n")
|
||||
if data:
|
||||
for line in data.split('\n'):
|
||||
line = line.strip()
|
||||
match = re.match(r'Mem: (.*?)', line, re.M | re.I)
|
||||
if match:
|
||||
memline = line.split(':')
|
||||
mems = memline[1].strip().split()
|
||||
self.facts['memtotal_mb'] = int(mems[0]) / 1024
|
||||
self.facts['memused_mb'] = int(mems[1]) / 1024
|
||||
self.facts['memfree_mb'] = int(mems[2]) / 1024
|
||||
self.facts['memshared_mb'] = int(mems[3]) / 1024
|
||||
self.facts['memavailable_mb'] = int(mems[5]) / 1024
|
||||
|
||||
def parse_memtotal(self, data):
|
||||
match = re.search(r'^MemTotal:\s*(.*) kB', data, re.M | re.I)
|
||||
if match:
|
||||
return int(match.group(1)) / 1024
|
||||
|
||||
def parse_memfree(self, data):
|
||||
match = re.search(r'^MemFree:\s*(.*) kB', data, re.M | re.I)
|
||||
if match:
|
||||
return int(match.group(1)) / 1024
|
||||
|
||||
|
||||
class Config(FactsBase):
|
||||
|
||||
COMMANDS = ['display running-config']
|
||||
|
||||
def populate(self):
|
||||
super(Config, self).populate()
|
||||
data = self.responses[0]
|
||||
if data:
|
||||
self.facts['config'] = data
|
||||
|
||||
|
||||
class Interfaces(FactsBase):
|
||||
|
||||
COMMANDS = ['display interface brief']
|
||||
|
||||
def populate(self):
|
||||
super(Interfaces, self).populate()
|
||||
|
||||
self.facts['all_ipv4_addresses'] = list()
|
||||
self.facts['all_ipv6_addresses'] = list()
|
||||
|
||||
data1 = self.run(['display interface status'])
|
||||
data1 = to_text(data1, errors='surrogate_or_strict').strip()
|
||||
data1 = data1.replace(r"\n", "\n")
|
||||
data2 = self.run(['display interface mac-address'])
|
||||
data2 = to_text(data2, errors='surrogate_or_strict').strip()
|
||||
data2 = data2.replace(r"\n", "\n")
|
||||
lines1 = None
|
||||
lines2 = None
|
||||
if data1:
|
||||
lines1 = self.parse_interfaces(data1)
|
||||
if data2:
|
||||
lines2 = self.parse_interfaces(data2)
|
||||
if lines1 is not None and lines2 is not None:
|
||||
self.facts['interfaces'] = self.populate_interfaces(lines1, lines2)
|
||||
data3 = self.run(['display lldp neighbors'])
|
||||
data3 = to_text(data3, errors='surrogate_or_strict').strip()
|
||||
data3 = data3.replace(r"\n", "\n")
|
||||
if data3:
|
||||
lines3 = self.parse_neighbors(data3)
|
||||
if lines3 is not None:
|
||||
self.facts['neighbors'] = self.populate_neighbors(lines3)
|
||||
|
||||
data4 = self.run(['display ip interface brief vrf all'])
|
||||
data5 = self.run(['display ipv6 interface brief vrf all'])
|
||||
data4 = to_text(data4, errors='surrogate_or_stdisplay').strip()
|
||||
data4 = data4.replace(r"\n", "\n")
|
||||
data5 = to_text(data5, errors='surrogate_or_strict').strip()
|
||||
data5 = data5.replace(r"\n", "\n")
|
||||
lines4 = None
|
||||
lines5 = None
|
||||
if data4:
|
||||
lines4 = self.parse_ipaddresses(data4)
|
||||
ipv4_interfaces = self.set_ip_interfaces(lines4)
|
||||
self.facts['all_ipv4_addresses'] = ipv4_interfaces
|
||||
if data5:
|
||||
lines5 = self.parse_ipaddresses(data5)
|
||||
ipv6_interfaces = self.set_ipv6_interfaces(lines5)
|
||||
self.facts['all_ipv6_addresses'] = ipv6_interfaces
|
||||
|
||||
def parse_ipaddresses(self, data):
|
||||
parsed = list()
|
||||
for line in data.split('\n'):
|
||||
if len(line) == 0:
|
||||
continue
|
||||
else:
|
||||
line = line.strip()
|
||||
match = re.match(r'^(Ethernet+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(po+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(mgmt+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(loopback+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
return parsed
|
||||
|
||||
def populate_interfaces(self, lines1, lines2):
|
||||
interfaces = dict()
|
||||
for line1, line2 in zip(lines1, lines2):
|
||||
line = line1 + " " + line2
|
||||
intfSplit = line.split()
|
||||
innerData = dict()
|
||||
innerData['description'] = intfSplit[1].strip()
|
||||
innerData['macaddress'] = intfSplit[8].strip()
|
||||
innerData['type'] = intfSplit[6].strip()
|
||||
innerData['speed'] = intfSplit[5].strip()
|
||||
innerData['duplex'] = intfSplit[4].strip()
|
||||
innerData['operstatus'] = intfSplit[2].strip()
|
||||
interfaces[intfSplit[0].strip()] = innerData
|
||||
return interfaces
|
||||
|
||||
def parse_interfaces(self, data):
|
||||
parsed = list()
|
||||
for line in data.split('\n'):
|
||||
if len(line) == 0:
|
||||
continue
|
||||
else:
|
||||
line = line.strip()
|
||||
match = re.match(r'^(Ethernet+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(po+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(mgmt+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
# match = re.match(r'^(loopback+)', line)
|
||||
# if match:
|
||||
# key = match.group(1)
|
||||
# parsed.append(line)
|
||||
return parsed
|
||||
|
||||
def set_ip_interfaces(self, line4):
|
||||
ipv4_addresses = list()
|
||||
for line in line4:
|
||||
ipv4Split = line.split()
|
||||
if 'Ethernet' in ipv4Split[0]:
|
||||
ipv4_addresses.append(ipv4Split[1])
|
||||
if 'mgmt' in ipv4Split[0]:
|
||||
ipv4_addresses.append(ipv4Split[1])
|
||||
if 'po' in ipv4Split[0]:
|
||||
ipv4_addresses.append(ipv4Split[1])
|
||||
if 'loopback' in ipv4Split[0]:
|
||||
ipv4_addresses.append(ipv4Split[1])
|
||||
return ipv4_addresses
|
||||
|
||||
def set_ipv6_interfaces(self, line4):
|
||||
ipv6_addresses = list()
|
||||
for line in line4:
|
||||
ipv6Split = line.split()
|
||||
if 'Ethernet' in ipv6Split[0]:
|
||||
ipv6_addresses.append(ipv6Split[1])
|
||||
if 'mgmt' in ipv6Split[0]:
|
||||
ipv6_addresses.append(ipv6Split[1])
|
||||
if 'po' in ipv6Split[0]:
|
||||
ipv6_addresses.append(ipv6Split[1])
|
||||
if 'loopback' in ipv6Split[0]:
|
||||
ipv6_addresses.append(ipv6Split[1])
|
||||
return ipv6_addresses
|
||||
|
||||
def populate_neighbors(self, lines3):
|
||||
neighbors = dict()
|
||||
for line in lines3:
|
||||
neighborSplit = line.split()
|
||||
innerData = dict()
|
||||
innerData['Local Interface'] = neighborSplit[1].strip()
|
||||
innerData['Hold Time'] = neighborSplit[2].strip()
|
||||
innerData['Capability'] = neighborSplit[3].strip()
|
||||
innerData['Remote Port'] = neighborSplit[4].strip()
|
||||
neighbors[neighborSplit[0].strip()] = innerData
|
||||
return neighbors
|
||||
|
||||
def parse_neighbors(self, neighbors):
|
||||
parsed = list()
|
||||
for line in neighbors.split('\n'):
|
||||
if len(line) == 0:
|
||||
continue
|
||||
else:
|
||||
line = line.strip()
|
||||
if 'Ethernet' in line:
|
||||
parsed.append(line)
|
||||
if 'mgmt' in line:
|
||||
parsed.append(line)
|
||||
if 'po' in line:
|
||||
parsed.append(line)
|
||||
if 'loopback' in line:
|
||||
parsed.append(line)
|
||||
return parsed
|
||||
|
||||
FACT_SUBSETS = dict(
|
||||
default=Default,
|
||||
hardware=Hardware,
|
||||
interfaces=Interfaces,
|
||||
config=Config,
|
||||
)
|
||||
|
||||
VALID_SUBSETS = frozenset(FACT_SUBSETS.keys())
|
||||
|
||||
PERSISTENT_COMMAND_TIMEOUT = 60
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
outputfile=dict(required=True),
|
||||
host=dict(required=True),
|
||||
username=dict(required=True),
|
||||
password=dict(required=True, no_log=True),
|
||||
enablePassword=dict(required=False, no_log=True),),
|
||||
supports_check_mode=False)
|
||||
"""main entry point for module execution
|
||||
"""
|
||||
argument_spec = dict(
|
||||
gather_subset=dict(default=['!config'], type='list')
|
||||
)
|
||||
|
||||
username = module.params['username']
|
||||
password = module.params['password']
|
||||
enablePassword = module.params['enablePassword']
|
||||
cliCommand = "display sys-info"
|
||||
outputfile = module.params['outputfile']
|
||||
hostIP = module.params['host']
|
||||
output = ""
|
||||
if not HAS_PARAMIKO:
|
||||
module.fail_json(msg='paramiko is required for this module')
|
||||
argument_spec.update(cnos_argument_spec)
|
||||
|
||||
# Create instance of SSHClient object
|
||||
remote_conn_pre = paramiko.SSHClient()
|
||||
module = AnsibleModule(argument_spec=argument_spec,
|
||||
supports_check_mode=True)
|
||||
|
||||
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
|
||||
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
gather_subset = module.params['gather_subset']
|
||||
|
||||
# initiate SSH connection with the switch
|
||||
remote_conn_pre.connect(hostIP, username=username, password=password)
|
||||
time.sleep(2)
|
||||
runable_subsets = set()
|
||||
exclude_subsets = set()
|
||||
|
||||
# Use invoke_shell to establish an 'interactive session'
|
||||
remote_conn = remote_conn_pre.invoke_shell()
|
||||
time.sleep(2)
|
||||
for subset in gather_subset:
|
||||
if subset == 'all':
|
||||
runable_subsets.update(VALID_SUBSETS)
|
||||
continue
|
||||
|
||||
# Enable and enter configure terminal then send command
|
||||
output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn)
|
||||
if subset.startswith('!'):
|
||||
subset = subset[1:]
|
||||
if subset == 'all':
|
||||
exclude_subsets.update(VALID_SUBSETS)
|
||||
continue
|
||||
exclude = True
|
||||
else:
|
||||
exclude = False
|
||||
|
||||
output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn)
|
||||
if subset not in VALID_SUBSETS:
|
||||
module.fail_json(msg='Bad subset')
|
||||
|
||||
# Make terminal length = 0
|
||||
output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn)
|
||||
if exclude:
|
||||
exclude_subsets.add(subset)
|
||||
else:
|
||||
runable_subsets.add(subset)
|
||||
|
||||
# Send the CLi command
|
||||
output = output + cnos.waitForDeviceResponse(cliCommand + "\n", "#", 2, remote_conn)
|
||||
if not runable_subsets:
|
||||
runable_subsets.update(VALID_SUBSETS)
|
||||
|
||||
# Save it into the file
|
||||
file = open(outputfile, "a")
|
||||
file.write(output)
|
||||
file.close()
|
||||
runable_subsets.difference_update(exclude_subsets)
|
||||
runable_subsets.add('default')
|
||||
|
||||
facts = dict()
|
||||
facts['gather_subset'] = list(runable_subsets)
|
||||
|
||||
instances = list()
|
||||
for key in runable_subsets:
|
||||
instances.append(FACT_SUBSETS[key](module))
|
||||
|
||||
for inst in instances:
|
||||
inst.populate()
|
||||
facts.update(inst.facts)
|
||||
|
||||
ansible_facts = dict()
|
||||
for key, value in iteritems(facts):
|
||||
key = 'ansible_net_%s' % key
|
||||
ansible_facts[key] = value
|
||||
|
||||
warnings = list()
|
||||
check_args(module, warnings)
|
||||
|
||||
module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
|
||||
|
||||
errorMsg = cnos.checkOutputForError(output)
|
||||
if(errorMsg is None):
|
||||
module.exit_json(changed=True, msg="Device Sys Info is saved to file ")
|
||||
else:
|
||||
module.fail_json(msg=errorMsg)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue