Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_command.py

raw
1 #!/usr/bin/python
2 # Copyright: Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6
7
8 __metaclass__ = type
9
10
11 DOCUMENTATION = """
12 module: nxos_command
13 extends_documentation_fragment:
14 - cisco.nxos.nxos
15 author: Peter Sprygada (@privateip)
16 notes:
17 - Limited Support for Cisco MDS
18 short_description: Run arbitrary command on Cisco NXOS devices
19 description:
20 - Sends an arbitrary command to an NXOS node and returns the results read from the
21 device. This module includes an argument that will cause the module to wait for
22 a specific condition before returning or timing out if the condition is not met.
23 version_added: 1.0.0
24 options:
25 commands:
26 description:
27 - The commands to send to the remote NXOS device. The resulting output from the
28 command is returned. If the I(wait_for) argument is provided, the module is
29 not returned until the condition is satisfied or the number of retires as expired.
30 - The I(commands) argument also accepts an alternative form that allows for complex
31 values that specify the command to run and the output format to return. This
32 can be done on a command by command basis. The complex argument supports the
33 keywords C(command) and C(output) where C(command) is the command to run and
34 C(output) is one of 'text' or 'json'.
35 - If a command sent to the device requires answering a prompt, it is possible to pass
36 a dict containing command, answer and prompt. Common answers are 'y' or "\\r"
37 (carriage return, must be double quotes). See examples.
38 required: true
39 type: list
40 elements: raw
41 wait_for:
42 description:
43 - Specifies what to evaluate from the output of the command and what conditionals
44 to apply. This argument will cause the task to wait for a particular conditional
45 to be true before moving forward. If the conditional is not true by the configured
46 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 I(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: ['any', 'all']
59 type: str
60 retries:
61 description:
62 - Specifies the number of retries a command should by tried before it is considered
63 failed. The command is run on the target device every retry and evaluated against
64 the I(wait_for) conditionals.
65 - The commands are run once when I(retries) is set to C(0).
66 default: 9
67 type: int
68 interval:
69 description:
70 - Configures the interval in seconds to wait between retries of the command. If
71 the command does not pass the specified conditional, the interval indicates
72 how to long to wait before trying the command again.
73 default: 1
74 type: int
75 """
76
77 EXAMPLES = """
78 - name: run show version on remote devices
79 cisco.nxos.nxos_command:
80 commands: show version
81
82 - name: run show version and check to see if output contains Cisco
83 cisco.nxos.nxos_command:
84 commands: show version
85 wait_for: result[0] contains Cisco
86
87 - name: run multiple commands on remote nodes
88 cisco.nxos.nxos_command:
89 commands:
90 - show version
91 - show interfaces
92
93 - name: run multiple commands and evaluate the output
94 cisco.nxos.nxos_command:
95 commands:
96 - show version
97 - show interfaces
98 wait_for:
99 - result[0] contains Cisco
100 - result[1] contains loopback0
101
102 - name: run commands and specify the output format
103 cisco.nxos.nxos_command:
104 commands:
105 - command: show version
106 output: json
107
108 - name: run commands that require answering a prompt
109 cisco.nxos.nxos_command:
110 commands:
111 - configure terminal
112 - command: no feature npv
113 prompt: Do you want to continue
114 answer: y
115 """
116
117 RETURN = """
118 stdout:
119 description: The set of responses from the commands
120 returned: always apart from low level errors (such as action plugin)
121 type: list
122 sample: ['...', '...']
123 stdout_lines:
124 description: The value of stdout split into a list
125 returned: always apart from low level errors (such as action plugin)
126 type: list
127 sample: [['...', '...'], ['...'], ['...']]
128 failed_conditions:
129 description: The list of conditionals that have failed
130 returned: failed
131 type: list
132 sample: ['...', '...']
133 """
134 import time
135
136 from ansible.module_utils._text import to_text
137 from ansible.module_utils.basic import AnsibleModule
138 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.parsing import (
139 Conditional,
140 FailedConditionalError,
141 )
142 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
143 to_lines,
144 transform_commands,
145 )
146
147 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands
148
149
150 def parse_commands(module, warnings):
151 commands = transform_commands(module)
152
153 if module.check_mode:
154 for item in list(commands):
155 if not item["command"].startswith("show"):
156 warnings.append(
157 "Only show commands are supported when using check mode, not "
158 "executing %s" % item["command"],
159 )
160 commands.remove(item)
161
162 return commands
163
164
165 def to_cli(obj):
166 cmd = obj["command"]
167 if obj.get("output") == "json":
168 cmd += " | json"
169 return cmd
170
171
172 def main():
173 """entry point for module execution"""
174 argument_spec = dict(
175 # { command: <str>, output: <str>, prompt: <str>, response: <str> }
176 commands=dict(type="list", required=True, elements="raw"),
177 wait_for=dict(type="list", aliases=["waitfor"], elements="str"),
178 match=dict(default="all", choices=["any", "all"]),
179 retries=dict(default=9, type="int"),
180 interval=dict(default=1, type="int"),
181 )
182
183 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
184
185 warnings = list()
186 result = {"changed": False, "warnings": warnings}
187 commands = parse_commands(module, warnings)
188 wait_for = module.params["wait_for"] or list()
189 conditionals = []
190
191 try:
192 conditionals = [Conditional(c) for c in wait_for]
193 except AttributeError as exc:
194 module.fail_json(msg=to_text(exc))
195
196 retries = module.params["retries"]
197 interval = module.params["interval"]
198 match = module.params["match"]
199
200 while retries >= 0:
201 responses = run_commands(module, commands)
202
203 for item in list(conditionals):
204 try:
205 if item(responses):
206 if match == "any":
207 conditionals = list()
208 break
209 conditionals.remove(item)
210 except FailedConditionalError as exc:
211 module.fail_json(msg=to_text(exc))
212
213 if not conditionals:
214 break
215
216 time.sleep(interval)
217 retries -= 1
218
219 if conditionals:
220 failed_conditions = [item.raw for item in conditionals]
221 msg = "One or more conditional statements have not been satisfied"
222 module.fail_json(msg=msg, failed_conditions=failed_conditions)
223
224 result.update({"stdout": responses, "stdout_lines": list(to_lines(responses))})
225
226 module.exit_json(**result)
227
228
229 if __name__ == "__main__":
230 main()