Debian Codegraph @

ansible_collections/cisco/iosxr/plugins/modules/iosxr_command.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright: Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8
9 __metaclass__ = type
10
11 DOCUMENTATION = """
12 module: iosxr_command
13 author: Ricardo Carrillo Cruz (@rcarrillocruz)
14 short_description: Module to run commands on remote devices.
15 description:
16 - Sends arbitrary commands to an IOS XR node and returns the results read from the
17 device. This module includes an argument that will cause the module to wait for
18 a specific condition before returning or timing out if the condition is not met.
19 - This module does not support running commands in configuration mode. Please use
20 M(cisco.iosxr.iosxr_config) to configure iosxr devices.
21 version_added: 1.0.0
22 extends_documentation_fragment:
23 - cisco.iosxr.iosxr
24 notes:
25 - Make sure the user has been authorized to execute commands terminal length 0, terminal
26 width 512 and terminal exec prompt no-timestamp.
27 - This module works with C(network_cli). See L(the IOS-XR Platform Options,../network/user_guide/platform_iosxr.html).
28 - This module does not support C(netconf) connection.
29 options:
30 commands:
31 description:
32 - List of commands to send to the remote iosxr device over the configured provider.
33 The resulting output from the command is returned. If the I(wait_for) argument
34 is provided, the module is not returned until the condition is satisfied or
35 the number of retries has expired.
36 - If a command sent to the device requires answering a prompt, it is possible to pass
37 a dict containing command, answer and prompt. Common answers are 'y' or "\\r"
38 (carriage return, must be double quotes). See examples
39 type: list
40 elements: raw
41 required: true
42 wait_for:
43 description:
44 - List of conditions to evaluate against the output of the command. The task will
45 wait for each condition to be true before moving forward. If the conditional
46 is not true within the configured number of retries, the task fails. See examples.
47 aliases:
48 - waitfor
49 type: list
50 elements: str
51 match:
52 description:
53 - The I(match) argument is used in conjunction with the I(wait_for) argument to
54 specify the match policy. Valid values are C(all) or C(any). If the value
55 is set to C(all) then all conditionals in the wait_for must be satisfied. If
56 the value is set to C(any) then only one of the values must be satisfied.
57 default: all
58 choices:
59 - any
60 - all
61 type: str
62 retries:
63 description:
64 - Specifies the number of retries a command should by tried before it is considered
65 failed. The command is run on the target device every retry and evaluated against
66 the I(wait_for) conditions.
67 default: 10
68 type: int
69 interval:
70 description:
71 - Configures the interval in seconds to wait between retries of the command. If
72 the command does not pass the specified conditions, the interval indicates how
73 long to wait before trying the command again.
74 default: 1
75 type: int
76 """
77
78 EXAMPLES = """
79 - name: run show version on remote devices
80 cisco.iosxr.iosxr_command:
81 commands: show version
82
83 - name: run show version and check to see if output contains iosxr
84 cisco.iosxr.iosxr_command:
85 commands: show version
86 wait_for: result[0] contains IOS-XR
87
88 - name: run multiple commands on remote nodes
89 cisco.iosxr.iosxr_command:
90 commands:
91 - show version
92 - show interfaces
93 - {command: example command that prompts, prompt: expected prompt, answer: true}
94
95 - name: run multiple commands and evaluate the output
96 cisco.iosxr.iosxr_command:
97 commands:
98 - show version
99 - show interfaces
100 wait_for:
101 - result[0] contains IOS-XR
102 - result[1] contains Loopback0
103
104 - name: 'multiple prompt, multiple answer (mandatory check for all prompts)'
105 cisco.iosxr.iosxr_command:
106 commands:
107 - command: key config-key password-encryption
108 prompt:
109 - 'Enter old key :'
110 - 'Enter new key :'
111 - 'Enter confirm key :'
112 answer:
113 - test1234
114 - test12345
115 - test12345
116 check_all: true
117 """
118
119 RETURN = """
120 stdout:
121 description: The set of responses from the commands
122 returned: always apart from low level errors (such as action plugin)
123 type: list
124 sample: ['...', '...']
125 stdout_lines:
126 description: The value of stdout split into a list
127 returned: always apart from low level errors (such as action plugin)
128 type: list
129 sample: [['...', '...'], ['...'], ['...']]
130 failed_conditions:
131 description: The list of conditionals that have failed
132 returned: failed
133 type: list
134 sample: ['...', '...']
135 """
136 import time
137
138 from ansible.module_utils._text import to_text
139 from ansible.module_utils.basic import AnsibleModule
140 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.parsing import (
141 Conditional,
142 )
143 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_lines
144
145 from ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr import run_commands
146
147
148 def parse_commands(module, warnings):
149 commands = module.params["commands"]
150 for item in list(commands):
151 try:
152 command = item["command"]
153 except Exception:
154 command = item
155 if module.check_mode and not command.startswith("show"):
156 warnings.append(
157 "Only show commands are supported when using check mode, not "
158 "executing %s" % command,
159 )
160 commands.remove(item)
161
162 return commands
163
164
165 def main():
166 argument_spec = dict(
167 commands=dict(type="list", required=True, elements="raw"),
168 wait_for=dict(type="list", aliases=["waitfor"], elements="str"),
169 match=dict(default="all", choices=["all", "any"]),
170 retries=dict(default=10, type="int"),
171 interval=dict(default=1, type="int"),
172 )
173
174 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
175
176 warnings = list()
177 result = {"changed": False, "warnings": warnings}
178 commands = parse_commands(module, warnings)
179 wait_for = module.params["wait_for"] or list()
180
181 try:
182 conditionals = [Conditional(c) for c in wait_for]
183 except AttributeError as exc:
184 module.fail_json(msg=to_text(exc))
185
186 retries = module.params["retries"]
187 interval = module.params["interval"]
188 match = module.params["match"]
189
190 while retries > 0:
191 responses = run_commands(module, commands)
192
193 for item in list(conditionals):
194 if item(responses):
195 if match == "any":
196 conditionals = list()
197 break
198 conditionals.remove(item)
199
200 if not conditionals:
201 break
202
203 time.sleep(interval)
204 retries -= 1
205
206 if conditionals:
207 failed_conditions = [item.raw for item in conditionals]
208 msg = "One or more conditional statements have not been satisfied"
209 module.fail_json(msg=msg, failed_conditions=failed_conditions)
210
211 result.update({"stdout": responses, "stdout_lines": list(to_lines(responses))})
212
213 module.exit_json(**result)
214
215
216 if __name__ == "__main__":
217 main()