1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

added new functionality to ops_command

* commands argument now accepts a dict arguments
* waitfor has been renamed to wait_for with an alias to waitfor
* only show commands are allowed when check mode is specified
* config mode is no longer allowed in the command stack
* add argument match with valid values any, all

Tested on OpenSwitch 0.4.0
This commit is contained in:
Peter Sprygada 2016-08-30 17:12:52 -04:00 committed by Matt Clay
parent 882f201aa0
commit ef46627f1f

View file

@ -37,15 +37,29 @@ options:
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 I(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']
version_added: "2.2"
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 I(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']
version_added: "2.2"
retries: retries:
description: description:
- Specifies the number of retries a command should by tried - Specifies the number of retries a command should by tried
@ -65,21 +79,32 @@ options:
""" """
EXAMPLES = """ EXAMPLES = """
- ops_command: # Note: examples below use the following provider dict to handle
commands: # transport and authentication to the node.
- show version vars:
register: output cli:
host: "{{ inventory_hostname }}"
username: netop
password: netop
transport: cli
- ops_command: - ops_command:
commands: commands:
- show version - show version
waitfor: provider: "{{ cli }}"
- ops_command:
commands:
- show version
wait_for:
- "result[0] contains OpenSwitch" - "result[0] contains OpenSwitch"
provider: "{{ cli }}"
- ops_command: - ops_command:
commands: commands:
- show version - show version
- show interfaces - show interfaces
provider: "{{ cli }}"
""" """
RETURN = """ RETURN = """
@ -101,9 +126,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.openswitch import NetworkModule, NetworkError
import time VALID_KEYS = ['command', 'prompt', 'response']
def to_lines(stdout): def to_lines(stdout):
for item in stdout: for item in stdout:
@ -111,57 +139,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')
transport=dict(default='cli', choices=['cli'])
) )
module = get_module(argument_spec=spec, module = NetworkModule(argument_spec=spec,
supports_check_mode=True) connect_on_load=False,
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='ops_command does not support running '
'config mode commands. Please use '
'ops_config instead')
try:
runner.add_command(**cmd)
except AddCommandError:
exc = get_exception()
warnings.append('duplicate command detected: %s' % cmd)
for item in conditionals:
runner.add_conditional(item)
runner.retries = module.params['retries']
runner.interval = module.params['interval']
runner.match = module.params['match']
try: try:
queue = set() runner.run()
for entry in (module.params['waitfor'] or list()): except FailedConditionsError:
queue.add(Conditional(entry))
except AttributeError:
exc = get_exception() exc = get_exception()
module.fail_json(msg=exc.message) module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc))
result = dict(changed=False) result = dict(changed=False, stdout=list())
while retries > 0: for cmd in commands:
response = module.execute(commands) try:
result['stdout'] = response output = runner.get_command(cmd['command'])
except ValueError:
for item in list(queue): output = 'command not executed due to check_mode, see warnings'
if item(response): result['stdout'].append(output)
queue.remove(item)
if not queue:
break
time.sleep(interval)
retries -= 1
else:
failed_conditions = [item.raw for item in queue]
module.fail_json(msg='timeout waiting for value', failed_conditions=failed_conditions)
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.shell import *
from ansible.module_utils.netcfg import *
from ansible.module_utils.openswitch import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()