added new functionality to asa_command

* commands argument now accepts a dict arguments
* only show commands are allowd when check mode is specified
* config mode is no longer allowed in the command stack
* add argument match with valid values any, all
reviewable/pr18780/r1
Peter Sprygada 8 years ago
parent 7b4f78798e
commit dc0290a067

@ -21,7 +21,7 @@ DOCUMENTATION = """
--- ---
module: asa_command module: asa_command
version_added: "2.2" version_added: "2.2"
author: "Peter Sprygada (@privateip) & Patrick Ogenstad (@ogenstad)" author: "Peter Sprygada (@privateip), Patrick Ogenstad (@ogenstad)"
short_description: Run arbitrary commands on Cisco ASA devices. short_description: Run arbitrary commands on Cisco ASA devices.
description: description:
- Sends arbitrary commands to an ASA node and returns the results - Sends arbitrary commands to an ASA node and returns the results
@ -32,27 +32,39 @@ extends_documentation_fragment: asa
options: options:
commands: commands:
description: description:
- List of commands to send to the remote ios device over the - List of commands to send to the remote device over the
configured provider. The resulting output from the command configured provider. The resulting output from the command
is returned. If the I(waitfor) argument is provided, the is returned. If the I(wait_for) argument is provided, the
module is not returned until the condition is satisfied or module is not returned until the condition is satisfied or
the number of retires as expired. the number of retires as expired.
required: true required: true
waitfor: wait_for:
description: description:
- List of conditions to evaluate against the output of the - List of conditions to evaluate against the output of the
command. The task will wait for a each condition to be true command. The task will wait for each condition to be true
before moving forward. If the conditional is not true before moving forward. If the conditional is not true
within the configured number of retries, the task fails. within the configured number of retries, the task fails.
See examples. See examples.
required: false required: false
default: null default: null
aliases: ['waitfor']
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.
required: false
default: all
choices: ['any', 'all']
retries: retries:
description: description:
- Specifies the number of retries a command should by tried - Specifies the number of retries a command should by tried
before it is considered failed. The command is run on the before it is considered failed. The command is run on the
target device every retry and evaluated against the target device every retry and evaluated against the
waitfor conditions. I(wait_for) conditions.
required: false required: false
default: 10 default: 10
interval: interval:
@ -63,25 +75,36 @@ options:
trying the command again. trying the command again.
required: false required: false
default: 1 default: 1
""" """
EXAMPLES = """ EXAMPLES = """
# Note: examples below use the following provider dict to handle
# transport and authentication to the node.
vars:
cli:
host: "{{ inventory_hostname }}"
username: cisco
password: cisco
authorize: yes
auth_pass: cisco
transport: cli
- asa_command: - asa_command:
commands: commands:
- show version - show version
register: output provider: "{{ cli }}"
- asa_command: - asa_command:
commands: commands:
- show asp drop - show asp drop
- show memory - show memory
register: output provider: "{{ cli }}"
- asa_command: - asa_command:
commands: commands:
- show version - show version
provider: "{{ cli }}"
context: system context: system
""" """
@ -104,11 +127,12 @@ failed_conditions:
type: list type: list
sample: ['...', '...'] sample: ['...', '...']
""" """
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.asa import NetworkModule, NetworkError
import time VALID_KEYS = ['command', 'prompt', 'response']
import shlex
import re
def to_lines(stdout): def to_lines(stdout):
for item in stdout: for item in stdout:
@ -116,57 +140,85 @@ def to_lines(stdout):
item = str(item).split('\n') item = str(item).split('\n')
yield item yield item
def parse_commands(module):
for cmd in module.params['commands']:
if isinstance(cmd, basestring):
cmd = dict(command=cmd, output=None)
elif 'command' not in cmd:
module.fail_json(msg='command keyword argument is required')
elif not set(cmd.keys()).issubset(VALID_KEYS):
module.fail_json(msg='unknown keyword specified')
yield cmd
def main(): def main():
spec = dict( spec = dict(
commands=dict(type='list'), # { command: <str>, prompt: <str>, response: <str> }
waitfor=dict(type='list'), commands=dict(type='list', required=True),
wait_for=dict(type='list', aliases=['waitfor']),
match=dict(default='all', choices=['all', 'any']),
retries=dict(default=10, type='int'), retries=dict(default=10, type='int'),
interval=dict(default=1, type='int') interval=dict(default=1, type='int')
) )
module = get_module(argument_spec=spec, module = NetworkModule(argument_spec=spec,
connect_on_load=False,
supports_check_mode=True) supports_check_mode=True)
commands = module.params['commands'] commands = list(parse_commands(module))
conditionals = module.params['wait_for'] or list()
retries = module.params['retries'] warnings = list()
interval = module.params['interval']
runner = CommandRunner(module)
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='asa_command does not support running '
'config mode commands. Please use '
'asa_config instead')
try: try:
queue = set() runner.add_command(**cmd)
for entry in (module.params['waitfor'] or list()): except AddCommandError:
queue.add(Conditional(entry))
except AttributeError:
exc = get_exception() exc = get_exception()
module.fail_json(msg=exc.message) warnings.append('duplicate command detected: %s' % cmd)
result = dict(changed=False) for item in conditionals:
runner.add_conditional(item)
while retries > 0: runner.retries = module.params['retries']
response = module.execute(commands) runner.interval = module.params['interval']
result['stdout'] = response runner.match = module.params['match']
for item in list(queue): try:
if item(response): runner.run()
queue.remove(item) 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 queue: result = dict(changed=False, stdout=list())
break
time.sleep(interval) for cmd in commands:
retries -= 1 try:
else: output = runner.get_command(cmd['command'])
failed_conditions = [item.raw for item in queue] except ValueError:
module.fail_json(msg='timeout waiting for value', failed_conditions=failed_conditions) output = 'command not executed due to check_mode, see warnings'
result['stdout'].append(output)
result['warnings'] = warnings
result['stdout_lines'] = list(to_lines(result['stdout'])) result['stdout_lines'] = list(to_lines(result['stdout']))
return module.exit_json(**result)
from ansible.module_utils.basic import * module.exit_json(**result)
from ansible.module_utils.urls import *
from ansible.module_utils.shell import *
from ansible.module_utils.netcfg import *
from ansible.module_utils.asa import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

Loading…
Cancel
Save