Refactor iosxr_command to make use of network_connection plugin (#20772)

This commit is contained in:
Ricardo Carrillo Cruz 2017-01-30 17:52:19 +01:00 committed by GitHub
parent bbaab6ee5b
commit e70bc06ea1
3 changed files with 300 additions and 76 deletions

View file

@ -24,7 +24,7 @@ DOCUMENTATION = """
---
module: iosxr_command
version_added: "2.1"
author: "Peter Sprygada (@privateip)"
author: "Ricardo Carrillo Cruz (@rcarrillocruz)"
short_description: Run commands on remote devices running Cisco iosxr
description:
- Sends arbitrary commands to an iosxr node and returns the results
@ -33,7 +33,6 @@ description:
before returning or timing out if the condition is not met.
- This module does not support running commands in configuration mode.
Please use M(iosxr_config) to configure iosxr devices.
extends_documentation_fragment: iosxr
options:
commands:
description:
@ -85,32 +84,21 @@ options:
"""
EXAMPLES = """
# Note: examples below use the following provider dict to handle
# transport and authentication to the node.
vars:
cli:
host: "{{ inventory_hostname }}"
username: root
password: root
tasks:
- name: run show version on remote devices
iosxr_command:
commands: show version
provider: "{{ cli }}"
- name: run show version and check to see if output contains iosxr
iosxr_command:
commands: show version
wait_for: result[0] contains IOS-XR
provider: "{{ cli }}"
- name: run multiple commands on remote nodes
iosxr_command:
commands:
- show version
- show interfaces
provider: "{{ cli }}"
- name: run multiple commands and evaluate the output
iosxr_command:
@ -120,7 +108,6 @@ tasks:
wait_for:
- result[0] contains IOS-XR
- result[1] contains Loopback0
provider: "{{ cli }}"
"""
RETURN = """
@ -129,24 +116,38 @@ stdout:
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 list of conditionals that have failed
returned: failed
type: list
sample: ['...', '...']
start:
description: The time the job started
returned: always
type: str
sample: "2016-11-16 10:38:15.126146"
end:
description: The time the job ended
returned: always
type: str
sample: "2016-11-16 10:38:25.595612"
delta:
description: The time elapsed to perform all operations
returned: always
type: str
sample: "0:00:10.469466"
"""
import ansible.module_utils.iosxr
from ansible.module_utils.basic import get_exception
from ansible.module_utils.netcli import CommandRunner
from ansible.module_utils.netcli import AddCommandError, FailedConditionsError
from ansible.module_utils.network import NetworkModule, NetworkError
import time
from ansible.module_utils.local import LocalAnsibleModule
from ansible.module_utils.iosxr import run_commands
from ansible.module_utils.network_common import ComplexList
from ansible.module_utils.netcli import Conditional
from ansible.module_utils.six import string_types
VALID_KEYS = ['command', 'output', 'prompt', 'response']
@ -157,18 +158,27 @@ def to_lines(stdout):
item = str(item).split('\n')
yield item
def parse_commands(module):
for cmd in module.params['commands']:
if isinstance(cmd, string_types):
cmd = dict(command=cmd, output=None)
elif 'command' not in cmd:
module.fail_json(msg='command keyword argument is required')
elif cmd.get('output') not in [None, 'text']:
module.fail_json(msg='invalid output specified for command')
elif not set(cmd.keys()).issubset(VALID_KEYS):
module.fail_json(msg='unknown command keyword specified. Valid '
'values are %s' % ', '.join(VALID_KEYS))
yield cmd
def parse_commands(module, warnings):
command = ComplexList(dict(
command=dict(key=True),
prompt=dict(),
response=dict()
))
commands = command(module.params['commands'])
for index, item in enumerate(commands):
if module.check_mode and not item['command'].startswith('show'):
warnings.append(
'only show commands are supported when using check mode, not '
'executing `%s`' % item['command']
)
elif item['command'].startswith('conf'):
module.fail_json(
msg='iosxr_command does not support running config mode '
'commands. Please use iosxr_config instead'
)
commands[index] = module.jsonify(item)
return commands
def main():
spec = dict(
@ -182,62 +192,49 @@ def main():
interval=dict(default=1, type='int')
)
module = NetworkModule(argument_spec=spec,
connect_on_load=False,
module = LocalAnsibleModule(argument_spec=spec,
supports_check_mode=True)
commands = list(parse_commands(module))
conditionals = module.params['wait_for'] or list()
warnings = list()
commands = parse_commands(module, warnings)
runner = CommandRunner(module)
wait_for = module.params['wait_for'] or list()
conditionals = [Conditional(c) for c in wait_for]
for cmd in commands:
if module.check_mode and not cmd['command'].startswith('show'):
warnings.append('only show commands are supported when using '
'check mode, not executing `%s`' % cmd['command'])
else:
if cmd['command'].startswith('conf'):
module.fail_json(msg='iosxr_command does not support running '
'config mode commands. Please use '
'iosxr_config instead')
try:
runner.add_command(**cmd)
except AddCommandError:
exc = get_exception()
warnings.append('duplicate command detected: %s' % cmd)
retries = module.params['retries']
interval = module.params['interval']
match = module.params['match']
for item in conditionals:
runner.add_conditional(item)
while retries > 0:
responses = run_commands(module, commands)
runner.retries = module.params['retries']
runner.interval = module.params['interval']
runner.match = module.params['match']
for item in list(conditionals):
if item(responses):
if match == 'any':
conditionals = list()
break
conditionals.remove(item)
try:
runner.run()
except FailedConditionsError:
exc = get_exception()
module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc))
if not conditionals:
break
result = dict(changed=False, stdout=list())
time.sleep(interval)
retries -= 1
for cmd in commands:
try:
output = runner.get_command(cmd['command'])
except ValueError:
output = 'command not executed due to check_mode, see warnings'
result['stdout'].append(output)
if conditionals:
failed_conditions = [item.raw for item in conditionals]
msg = 'One or more conditional statements have not be satisfied'
module.fail_json(msg=msg, failed_conditions=failed_conditions)
result['warnings'] = warnings
result['stdout_lines'] = list(to_lines(result['stdout']))
result = {
'changed': False,
'stdout': responses,
'warnings': warnings,
'stdout_lines': list(to_lines(responses))
}
module.exit_json(**result)
if __name__ == '__main__':
main()