mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-04-06 12:07:14 +00:00
Initial commit
This commit is contained in:
commit
aebc1b03fd
4861 changed files with 812621 additions and 0 deletions
228
plugins/modules/network/enos/enos_command.py
Normal file
228
plugins/modules/network/enos/enos_command.py
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
#!/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 execute ENOS 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 = '''
|
||||
---
|
||||
module: enos_command
|
||||
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
|
||||
short_description: Run arbitrary commands on Lenovo ENOS devices
|
||||
description:
|
||||
- Sends arbitrary commands to an ENOS node and returns the results
|
||||
read from the device. The C(enos_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.
|
||||
extends_documentation_fragment:
|
||||
- community.general.enos
|
||||
|
||||
options:
|
||||
commands:
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
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.
|
||||
---
|
||||
vars:
|
||||
cli:
|
||||
host: "{{ inventory_hostname }}"
|
||||
port: 22
|
||||
username: admin
|
||||
password: admin
|
||||
timeout: 30
|
||||
|
||||
---
|
||||
- name: test contains operator
|
||||
enos_command:
|
||||
commands:
|
||||
- show version
|
||||
- show system memory
|
||||
wait_for:
|
||||
- "result[0] contains 'Lenovo'"
|
||||
- "result[1] contains 'MemFree'"
|
||||
provider: "{{ cli }}"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- "result.changed == false"
|
||||
- "result.stdout is defined"
|
||||
|
||||
- name: get output for single command
|
||||
enos_command:
|
||||
commands: ['show version']
|
||||
provider: "{{ cli }}"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- "result.changed == false"
|
||||
- "result.stdout is defined"
|
||||
|
||||
- name: get output for multiple commands
|
||||
enos_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: 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 time
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible_collections.community.general.plugins.module_utils.network.enos.enos import run_commands, check_args
|
||||
from ansible_collections.community.general.plugins.module_utils.network.enos.enos import enos_argument_spec
|
||||
from ansible_collections.ansible.netcommon.plugins.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():
|
||||
spec = dict(
|
||||
# { command: <str>, prompt: <str>, response: <str> }
|
||||
commands=dict(type='list', required=True),
|
||||
|
||||
wait_for=dict(type='list'),
|
||||
match=dict(default='all', choices=['all', 'any']),
|
||||
|
||||
retries=dict(default=10, type='int'),
|
||||
interval=dict(default=1, type='int')
|
||||
)
|
||||
|
||||
spec.update(enos_argument_spec)
|
||||
|
||||
module = AnsibleModule(argument_spec=spec, supports_check_mode=True)
|
||||
result = {'changed': False}
|
||||
|
||||
wait_for = module.params['wait_for'] or list()
|
||||
conditionals = [Conditional(c) for c in wait_for]
|
||||
|
||||
commands = module.params['commands']
|
||||
retries = module.params['retries']
|
||||
interval = module.params['interval']
|
||||
match = module.params['match']
|
||||
|
||||
while retries > 0:
|
||||
responses = run_commands(module, commands)
|
||||
|
||||
for item in list(conditionals):
|
||||
if item(responses):
|
||||
if match == 'any':
|
||||
conditionals = list()
|
||||
break
|
||||
conditionals.remove(item)
|
||||
|
||||
if not conditionals:
|
||||
break
|
||||
|
||||
time.sleep(interval)
|
||||
retries -= 1
|
||||
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
310
plugins/modules/network/enos/enos_config.py
Normal file
310
plugins/modules/network/enos/enos_config.py
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
#!/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: enos_config
|
||||
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
|
||||
short_description: Manage Lenovo ENOS configuration sections
|
||||
description:
|
||||
- Lenovo ENOS configurations use a simple block indent file syntax
|
||||
for segmenting configuration into sections. This module provides
|
||||
an implementation for working with ENOS configuration sections in
|
||||
a deterministic way.
|
||||
extends_documentation_fragment:
|
||||
- community.general.enos
|
||||
|
||||
notes:
|
||||
- Tested against ENOS 8.4.1
|
||||
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 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. If the C(backup_options) value is not given,
|
||||
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 enos_config'
|
||||
admin:
|
||||
description:
|
||||
- Enters into administration configuration mode for making config
|
||||
changes to the device.
|
||||
type: bool
|
||||
default: 'no'
|
||||
backup_options:
|
||||
description:
|
||||
- This is a dict object containing configurable options related to backup file path.
|
||||
The value of this option is read only when C(backup) is set to I(yes), if C(backup) is set
|
||||
to I(no) this option will be silently ignored.
|
||||
suboptions:
|
||||
filename:
|
||||
description:
|
||||
- The filename to be used to store the backup configuration. If the filename
|
||||
is not given it will be generated based on the hostname, current time and date
|
||||
in format defined by <hostname>_config.<current-date>@<current-time>
|
||||
dir_path:
|
||||
description:
|
||||
- This option provides the path ending with directory name in which the backup
|
||||
configuration file will be stored. If the directory does not exist it will be first
|
||||
created and the filename is either the value of C(filename) or default filename
|
||||
as described in C(filename) options description. If the path value is not given
|
||||
in that case a I(backup) directory will be created in the current working directory
|
||||
and backup configuration will be copied in C(filename) within I(backup) directory.
|
||||
type: path
|
||||
type: dict
|
||||
'''
|
||||
|
||||
EXAMPLES = """
|
||||
- name: configure top level configuration
|
||||
enos_config:
|
||||
"lines: hostname {{ inventory_hostname }}"
|
||||
|
||||
- name: configure interface settings
|
||||
enos_config:
|
||||
lines:
|
||||
- enable
|
||||
- ip ospf enable
|
||||
parents: interface ip 13
|
||||
|
||||
- name: load a config from disk and replace the current config
|
||||
enos_config:
|
||||
src: config.cfg
|
||||
backup: yes
|
||||
|
||||
- name: configurable backup path
|
||||
enos_config:
|
||||
src: config.cfg
|
||||
backup: yes
|
||||
backup_options:
|
||||
filename: backup.cfg
|
||||
dir_path: /home/user
|
||||
"""
|
||||
|
||||
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: str
|
||||
sample: /playbooks/ansible/backup/enos01.2016-07-16@22:28:34
|
||||
"""
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible_collections.community.general.plugins.module_utils.network.enos.enos import load_config, get_config
|
||||
from ansible_collections.community.general.plugins.module_utils.network.enos.enos import enos_argument_spec
|
||||
from ansible_collections.community.general.plugins.module_utils.network.enos.enos import check_args
|
||||
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import NetworkConfig, dumps
|
||||
|
||||
|
||||
DEFAULT_COMMIT_COMMENT = 'configured by enos_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
|
||||
"""
|
||||
backup_spec = dict(
|
||||
filename=dict(),
|
||||
dir_path=dict(type='path')
|
||||
)
|
||||
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),
|
||||
backup_options=dict(type='dict', options=backup_spec),
|
||||
comment=dict(default=DEFAULT_COMMIT_COMMENT),
|
||||
admin=dict(type='bool', default=False)
|
||||
)
|
||||
|
||||
argument_spec.update(enos_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()
|
||||
507
plugins/modules/network/enos/enos_facts.py
Normal file
507
plugins/modules/network/enos/enos_facts.py
Normal file
|
|
@ -0,0 +1,507 @@
|
|||
#!/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 Collect facts from Lenovo Switches running Lenovo ENOS 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: enos_facts
|
||||
author: "Anil Kumar Muraleedharan (@amuraleedhar)"
|
||||
short_description: Collect facts from remote devices running Lenovo ENOS
|
||||
description:
|
||||
- Collects a base set of device facts from a remote Lenovo device
|
||||
running on ENOS. 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.
|
||||
extends_documentation_fragment:
|
||||
- community.general.enos
|
||||
|
||||
notes:
|
||||
- Tested against ENOS 8.4.1
|
||||
options:
|
||||
gather_subset:
|
||||
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 enos_facts.
|
||||
---
|
||||
- name: Test Enos Facts
|
||||
enos_facts:
|
||||
provider={{ cli }}
|
||||
|
||||
vars:
|
||||
cli:
|
||||
host: "{{ inventory_hostname }}"
|
||||
port: 22
|
||||
username: admin
|
||||
password: admin
|
||||
transport: cli
|
||||
timeout: 30
|
||||
authorize: True
|
||||
auth_pass:
|
||||
|
||||
---
|
||||
# Collect all facts from the device
|
||||
- enos_facts:
|
||||
gather_subset: all
|
||||
provider: "{{ cli }}"
|
||||
|
||||
# Collect only the config and default facts
|
||||
- enos_facts:
|
||||
gather_subset:
|
||||
- config
|
||||
provider: "{{ cli }}"
|
||||
|
||||
# Do not collect hardware facts
|
||||
- enos_facts:
|
||||
gather_subset:
|
||||
- "!hardware"
|
||||
provider: "{{ cli }}"
|
||||
|
||||
'''
|
||||
RETURN = '''
|
||||
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 ENOS device
|
||||
returned: always
|
||||
type: str
|
||||
ansible_net_serialnum:
|
||||
description: The serial number of the Lenovo ENOS device
|
||||
returned: always
|
||||
type: str
|
||||
ansible_net_version:
|
||||
description: The ENOS 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: str
|
||||
ansible_net_image:
|
||||
description: Indicates the active image for the device
|
||||
returned: always
|
||||
type: str
|
||||
# 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 re
|
||||
|
||||
from ansible_collections.community.general.plugins.module_utils.network.enos.enos import run_commands, enos_argument_spec, check_args
|
||||
from ansible.module_utils._text import to_text
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
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 = ['show version', 'show run']
|
||||
|
||||
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):
|
||||
match = re.search(r'^Software Version (.*?) ', data, re.M | re.I)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
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):
|
||||
match = re.search(r'^Lenovo RackSwitch (\S+)', data, re.M | re.I)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
def parse_image(self, data):
|
||||
match = re.search(r'(.*) image1(.*)', data, re.M | re.I)
|
||||
if match:
|
||||
return "Image1"
|
||||
else:
|
||||
return "Image2"
|
||||
|
||||
def parse_serialnum(self, data):
|
||||
match = re.search(r'^Switch Serial No: (\S+)', data, re.M | re.I)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
|
||||
class Hardware(FactsBase):
|
||||
|
||||
COMMANDS = [
|
||||
'show system memory'
|
||||
]
|
||||
|
||||
def populate(self):
|
||||
super(Hardware, self).populate()
|
||||
data = self.run(['show system memory'])
|
||||
data = to_text(data, errors='surrogate_or_strict').strip()
|
||||
data = data.replace(r"\n", "\n")
|
||||
if data:
|
||||
self.facts['memtotal_mb'] = self.parse_memtotal(data)
|
||||
self.facts['memfree_mb'] = self.parse_memfree(data)
|
||||
|
||||
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 = ['show running-config']
|
||||
|
||||
def populate(self):
|
||||
super(Config, self).populate()
|
||||
data = self.responses[0]
|
||||
if data:
|
||||
self.facts['config'] = data
|
||||
|
||||
|
||||
class Interfaces(FactsBase):
|
||||
|
||||
COMMANDS = ['show interface status']
|
||||
|
||||
def populate(self):
|
||||
super(Interfaces, self).populate()
|
||||
|
||||
self.facts['all_ipv4_addresses'] = list()
|
||||
self.facts['all_ipv6_addresses'] = list()
|
||||
|
||||
data1 = self.run(['show interface status'])
|
||||
data1 = to_text(data1, errors='surrogate_or_strict').strip()
|
||||
data1 = data1.replace(r"\n", "\n")
|
||||
data2 = self.run(['show lldp port'])
|
||||
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(['show lldp remote-device port'])
|
||||
data3 = to_text(data3, errors='surrogate_or_strict').strip()
|
||||
data3 = data3.replace(r"\n", "\n")
|
||||
|
||||
lines3 = None
|
||||
if data3:
|
||||
lines3 = self.parse_neighbors(data3)
|
||||
if lines3 is not None:
|
||||
self.facts['neighbors'] = self.populate_neighbors(lines3)
|
||||
|
||||
data4 = self.run(['show interface ip'])
|
||||
data4 = data4[0].split('\n')
|
||||
lines4 = None
|
||||
if data4:
|
||||
lines4 = self.parse_ipaddresses(data4)
|
||||
ipv4_interfaces = self.set_ipv4_interfaces(lines4)
|
||||
self.facts['all_ipv4_addresses'] = ipv4_interfaces
|
||||
ipv6_interfaces = self.set_ipv6_interfaces(lines4)
|
||||
self.facts['all_ipv6_addresses'] = ipv6_interfaces
|
||||
|
||||
def parse_ipaddresses(self, data4):
|
||||
parsed = list()
|
||||
for line in data4:
|
||||
if len(line) == 0:
|
||||
continue
|
||||
else:
|
||||
line = line.strip()
|
||||
if len(line) == 0:
|
||||
continue
|
||||
match = re.search(r'IP4', line, re.M | re.I)
|
||||
if match:
|
||||
key = match.group()
|
||||
parsed.append(line)
|
||||
match = re.search(r'IP6', line, re.M | re.I)
|
||||
if match:
|
||||
key = match.group()
|
||||
parsed.append(line)
|
||||
return parsed
|
||||
|
||||
def set_ipv4_interfaces(self, line4):
|
||||
ipv4_addresses = list()
|
||||
for line in line4:
|
||||
ipv4Split = line.split()
|
||||
if ipv4Split[1] == "IP4":
|
||||
ipv4_addresses.append(ipv4Split[2])
|
||||
return ipv4_addresses
|
||||
|
||||
def set_ipv6_interfaces(self, line4):
|
||||
ipv6_addresses = list()
|
||||
for line in line4:
|
||||
ipv6Split = line.split()
|
||||
if ipv6Split[1] == "IP6":
|
||||
ipv6_addresses.append(ipv6Split[2])
|
||||
return ipv6_addresses
|
||||
|
||||
def populate_neighbors(self, lines3):
|
||||
neighbors = dict()
|
||||
for line in lines3:
|
||||
neighborSplit = line.split("|")
|
||||
innerData = dict()
|
||||
innerData['Remote Chassis ID'] = neighborSplit[2].strip()
|
||||
innerData['Remote Port'] = neighborSplit[3].strip()
|
||||
sysName = neighborSplit[4].strip()
|
||||
if sysName is not None:
|
||||
innerData['Remote System Name'] = neighborSplit[4].strip()
|
||||
else:
|
||||
innerData['Remote System Name'] = "NA"
|
||||
neighbors[neighborSplit[0].strip()] = innerData
|
||||
return neighbors
|
||||
|
||||
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[6].strip()
|
||||
innerData['macaddress'] = intfSplit[8].strip()
|
||||
innerData['mtu'] = intfSplit[9].strip()
|
||||
innerData['speed'] = intfSplit[1].strip()
|
||||
innerData['duplex'] = intfSplit[2].strip()
|
||||
innerData['operstatus'] = intfSplit[5].strip()
|
||||
if("up" not in intfSplit[5].strip()) and ("down" not in intfSplit[5].strip()):
|
||||
innerData['description'] = intfSplit[7].strip()
|
||||
innerData['macaddress'] = intfSplit[9].strip()
|
||||
innerData['mtu'] = intfSplit[10].strip()
|
||||
innerData['operstatus'] = intfSplit[6].strip()
|
||||
interfaces[intfSplit[0].strip()] = innerData
|
||||
return interfaces
|
||||
|
||||
def parse_neighbors(self, neighbors):
|
||||
parsed = list()
|
||||
for line in neighbors.split('\n'):
|
||||
if len(line) == 0:
|
||||
continue
|
||||
else:
|
||||
line = line.strip()
|
||||
match = re.match(r'^([0-9]+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(INT+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(EXT+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(MGT+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
return parsed
|
||||
|
||||
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'^([0-9]+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(INT+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(EXT+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
parsed.append(line)
|
||||
match = re.match(r'^(MGT+)', line)
|
||||
if match:
|
||||
key = match.group(1)
|
||||
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():
|
||||
"""main entry point for module execution
|
||||
"""
|
||||
argument_spec = dict(
|
||||
gather_subset=dict(default=['!config'], type='list')
|
||||
)
|
||||
|
||||
argument_spec.update(enos_argument_spec)
|
||||
|
||||
module = AnsibleModule(argument_spec=argument_spec,
|
||||
supports_check_mode=True)
|
||||
|
||||
gather_subset = module.params['gather_subset']
|
||||
|
||||
runable_subsets = set()
|
||||
exclude_subsets = set()
|
||||
|
||||
for subset in gather_subset:
|
||||
if subset == 'all':
|
||||
runable_subsets.update(VALID_SUBSETS)
|
||||
continue
|
||||
|
||||
if subset.startswith('!'):
|
||||
subset = subset[1:]
|
||||
if subset == 'all':
|
||||
exclude_subsets.update(VALID_SUBSETS)
|
||||
continue
|
||||
exclude = True
|
||||
else:
|
||||
exclude = False
|
||||
|
||||
if subset not in VALID_SUBSETS:
|
||||
module.fail_json(msg='Bad subset')
|
||||
|
||||
if exclude:
|
||||
exclude_subsets.add(subset)
|
||||
else:
|
||||
runable_subsets.add(subset)
|
||||
|
||||
if not runable_subsets:
|
||||
runable_subsets.update(VALID_SUBSETS)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue