mirror of
https://github.com/ansible-collections/community.general.git
synced 2025-07-22 12:50:22 -07:00
refactors eos_command module (#20739)
* eos_command now uses network_cli connection plugin * adds unit test cases for eos_command module
This commit is contained in:
parent
57660abf33
commit
c8dcc7f5d6
3 changed files with 259 additions and 100 deletions
|
@ -16,9 +16,11 @@
|
|||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
ANSIBLE_METADATA = {'status': ['preview'],
|
||||
'supported_by': 'core',
|
||||
'version': '1.0'}
|
||||
ANSIBLE_METADATA = {
|
||||
'status': ['preview'],
|
||||
'supported_by': 'core',
|
||||
'version': '1.0'
|
||||
}
|
||||
|
||||
DOCUMENTATION = """
|
||||
---
|
||||
|
@ -31,7 +33,7 @@ description:
|
|||
read from the device. This 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: eos
|
||||
extends_documentation_fragment: eapi
|
||||
options:
|
||||
commands:
|
||||
description:
|
||||
|
@ -83,32 +85,20 @@ options:
|
|||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
# Note: examples below use the following provider dict to handle
|
||||
# transport and authentication to the node.
|
||||
vars:
|
||||
cli:
|
||||
host: "{{ inventory_hostname }}"
|
||||
username: admin
|
||||
password: admin
|
||||
transport: cli
|
||||
|
||||
- name: run show version on remote devices
|
||||
eos_command:
|
||||
commands: show version
|
||||
provider: "{{ cli }}"
|
||||
|
||||
- name: run show version and check to see if output contains Arista
|
||||
eos_command:
|
||||
commands: show version
|
||||
wait_for: result[0] contains Arista
|
||||
provider: "{{ cli }}"
|
||||
|
||||
- name: run multiple commands on remote nodes
|
||||
eos_command:
|
||||
commands:
|
||||
- show version
|
||||
- show interfaces
|
||||
provider: "{{ cli }}"
|
||||
|
||||
- name: run multiple commands and evaluate the output
|
||||
eos_command:
|
||||
|
@ -118,69 +108,90 @@ vars:
|
|||
wait_for:
|
||||
- result[0] contains Arista
|
||||
- result[1] contains Loopback0
|
||||
provider: "{{ cli }}"
|
||||
|
||||
- name: run commands and specify the output format
|
||||
eos_command:
|
||||
commands:
|
||||
- command: show version
|
||||
output: json
|
||||
provider: "{{ cli }}"
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
import ansible.module_utils.eos
|
||||
from functools import partial
|
||||
|
||||
from ansible.module_utils.basic import get_exception
|
||||
from ansible.module_utils.network import NetworkModule, NetworkError
|
||||
from ansible.module_utils.netcli import CommandRunner
|
||||
from ansible.module_utils.netcli import AddCommandError, AddConditionError
|
||||
from ansible.module_utils.netcli import FailedConditionsError
|
||||
from ansible.module_utils.netcli import FailedConditionalError
|
||||
from ansible.module_utils import eos
|
||||
from ansible.module_utils import eapi
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils.local import LocalAnsibleModule
|
||||
from ansible.module_utils.six import string_types
|
||||
|
||||
from ansible.module_utils.netcli import Conditional
|
||||
from ansible.module_utils.network_common import ComplexList
|
||||
|
||||
SHARED_LIB = 'eos'
|
||||
|
||||
VALID_KEYS = ['command', 'output', 'prompt', 'response']
|
||||
|
||||
def get_ansible_module():
|
||||
if SHARED_LIB == 'eos':
|
||||
return LocalAnsibleModule
|
||||
return AnsibleModule
|
||||
|
||||
def invoke(name, *args, **kwargs):
|
||||
obj = globals().get(SHARED_LIB)
|
||||
func = getattr(obj, name)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
run_commands = partial(invoke, 'run_commands')
|
||||
|
||||
def check_args(module, warnings):
|
||||
if SHARED_LIB == 'eapi':
|
||||
eapi.check_args(module)
|
||||
|
||||
def to_lines(stdout):
|
||||
lines = list()
|
||||
for item in stdout:
|
||||
if isinstance(item, string_types):
|
||||
item = str(item).split('\n')
|
||||
yield item
|
||||
lines.append(item)
|
||||
return lines
|
||||
|
||||
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', 'json']:
|
||||
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):
|
||||
cast = ComplexList(dict(
|
||||
command=dict(key=True),
|
||||
output=dict(),
|
||||
prompt=dict(),
|
||||
response=dict()
|
||||
))
|
||||
|
||||
commands = cast(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']
|
||||
)
|
||||
return commands
|
||||
|
||||
def to_cli(obj):
|
||||
cmd = obj['command']
|
||||
if obj.get('output') == 'json':
|
||||
cmd += ' | json'
|
||||
return cmd
|
||||
|
||||
def main():
|
||||
spec = dict(
|
||||
"""entry point for module execution
|
||||
"""
|
||||
argument_spec = dict(
|
||||
# { command: <str>, output: <str>, prompt: <str>, response: <str> }
|
||||
commands=dict(type='list', required=True),
|
||||
|
||||
|
@ -191,70 +202,59 @@ def main():
|
|||
interval=dict(default=1, type='int')
|
||||
)
|
||||
|
||||
module = NetworkModule(argument_spec=spec,
|
||||
supports_check_mode=True)
|
||||
argument_spec.update(eapi.eapi_argument_spec)
|
||||
|
||||
commands = list(parse_commands(module))
|
||||
conditionals = module.params['wait_for'] or list()
|
||||
cls = get_ansible_module()
|
||||
module = cls(argument_spec=argument_spec, supports_check_mode=True)
|
||||
|
||||
warnings = list()
|
||||
check_args(module, warnings)
|
||||
|
||||
runner = CommandRunner(module)
|
||||
result = {'changed': False}
|
||||
|
||||
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='eos_command does not support running '
|
||||
'config mode commands. Please use '
|
||||
'eos_config instead')
|
||||
try:
|
||||
runner.add_command(**cmd)
|
||||
except AddCommandError:
|
||||
exc = get_exception()
|
||||
warnings.append('duplicate command detected: %s' % cmd)
|
||||
commands = parse_commands(module, warnings)
|
||||
if warnings:
|
||||
result['warnings'] = warnings
|
||||
|
||||
try:
|
||||
for item in conditionals:
|
||||
runner.add_conditional(item)
|
||||
except AddConditionError:
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=str(exc), condition=exc.condition)
|
||||
wait_for = module.params['wait_for'] or list()
|
||||
conditionals = [Conditional(c) for c in wait_for]
|
||||
|
||||
retries = module.params['retries']
|
||||
interval = module.params['interval']
|
||||
match = module.params['match']
|
||||
|
||||
runner.retries = module.params['retries']
|
||||
runner.interval = module.params['interval']
|
||||
runner.match = module.params['match']
|
||||
commands = [to_cli(c) for c in commands]
|
||||
|
||||
try:
|
||||
runner.run()
|
||||
except FailedConditionsError:
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
|
||||
except FailedConditionalError:
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
|
||||
except NetworkError:
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=str(exc), **exc.kwargs)
|
||||
while retries > 0:
|
||||
responses = run_commands(module, commands)
|
||||
|
||||
result = dict(changed=False, stdout=list())
|
||||
for item in list(conditionals):
|
||||
if item(responses):
|
||||
if match == 'any':
|
||||
conditionals = list()
|
||||
break
|
||||
conditionals.remove(item)
|
||||
|
||||
for cmd in commands:
|
||||
try:
|
||||
output = runner.get_command(cmd['command'], cmd.get('output'))
|
||||
except ValueError:
|
||||
output = 'command not executed due to check_mode, see warnings'
|
||||
result['stdout'].append(output)
|
||||
if not conditionals:
|
||||
break
|
||||
|
||||
result['warnings'] = warnings
|
||||
result['stdout_lines'] = list(to_lines(result['stdout']))
|
||||
time.sleep(interval)
|
||||
retries -= 1
|
||||
|
||||
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.update({
|
||||
'changed': False,
|
||||
'stdout': responses,
|
||||
'stdout_lines': to_lines(responses)
|
||||
})
|
||||
|
||||
module.exit_json(**result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
SHARED_LIB = 'eapi'
|
||||
main()
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue