Debian Codegraph @

ansible_collections/dellemc/enterprise_sonic/plugins/modules/sonic_command.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2024, Peter Sprygada <[email protected]>
5 # Copyright: (c) 2025, Dell Inc.
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11 DOCUMENTATION = """
12 ---
13 module: sonic_command
14 version_added: 1.0.0
15 notes:
16 - Tested against Enterprise SONiC Distribution by Dell Technologies.
17 - Supports C(check_mode).
18 author: Dhivya P (@dhivayp)
19 short_description: Runs commands on devices running Enterprise SONiC
20 description:
21 - Runs commands on remote devices running Enterprise SONiC Distribution
22 by Dell Technologies. Sends arbitrary commands to an Enterprise SONiC node and
23 returns the results that are read from the device. This module includes an
24 argument that causes the module to wait for a specific condition
25 before returning or time out if the condition is not met.
26 - This module does not support running commands in configuration mode.
27 To configure SONiC devices, use M(dellemc.enterprise_sonic.sonic_config).
28 options:
29 commands:
30 description:
31 - List of commands to send to the remote Enterprise SONiC devices over the
32 configured provider. The resulting output from the command
33 is returned. If the I(wait_for) argument is provided, the
34 module is not returned until the condition is satisfied or
35 the number of retries has expired. If a command sent to the
36 device requires answering a prompt, it is possible to pass
37 a dict containing I(command), I(answer) and I(prompt).
38 Common answers are 'yes' or "\\r" (carriage return, must be
39 double quotes). See examples.
40 type: list
41 elements: str
42 required: true
43 wait_for:
44 description:
45 - List of conditions to evaluate against the output of the
46 command. The task waits for each condition to be true
47 before moving forward. If the conditional is not true
48 within the configured number of retries, the task fails.
49 See examples.
50 type: list
51 elements: str
52 match:
53 description:
54 - The I(match) argument is used in conjunction with the
55 I(wait_for) argument to specify the match policy. Valid
56 values are C(all) or C(any). If the value is set to C(all)
57 then all conditionals in the wait_for must be satisfied. If
58 the value is set to C(any) then only one of the values must be
59 satisfied.
60 type: str
61 default: all
62 choices: [ 'all', 'any' ]
63 retries:
64 description:
65 - Specifies the number of retries a command should be run
66 before it is considered failed. The command is run on the
67 target device every retry and evaluated against the
68 I(wait_for) conditions.
69 type: int
70 default: 10
71 interval:
72 description:
73 - Configures the interval in seconds to wait between retries
74 of the command. If the command does not pass the specified
75 conditions, the interval indicates how long to wait before
76 trying the command again.
77 type: int
78 default: 1
79 """
80
81 EXAMPLES = """
82 - name: Runs show version on remote devices
83 dellemc.enterprise_sonic.sonic_command:
84 commands: show version
85
86 - name: Runs show version and checks to see if output contains 'Dell'
87 dellemc.enterprise_sonic.sonic_command:
88 commands: show version
89 wait_for: result[0] contains Dell
90
91 - name: Runs multiple commands on remote nodes
92 dellemc.enterprise_sonic.sonic_command:
93 commands:
94 - show version
95 - show interface
96
97 - name: Runs multiple commands and evaluate the output
98 dellemc.enterprise_sonic.sonic_command:
99 commands:
100 - 'show version'
101 - 'show system'
102 wait_for:
103 - result[0] contains Dell
104 - result[1] contains Hostname
105
106 - name: Runs commands that require answering a prompt
107 dellemc.enterprise_sonic.sonic_command:
108 commands:
109 - command: 'reload'
110 prompt: '[confirm yes/no]: ?$'
111 answer: 'no'
112 """
113
114 RETURN = """
115 stdout:
116 description: The set of responses from the commands.
117 returned: always apart from low level errors (such as action plugin)
118 type: list
119 sample: ['...', '...']
120 stdout_lines:
121 description: The value of stdout split into a list.
122 returned: always apart from low level errors (such as action plugin)
123 type: list
124 sample: [['...', '...'], ['...'], ['...']]
125 failed_conditions:
126 description: The list of conditionals that have failed.
127 returned: failed
128 type: list
129 sample: ['...', '...']
130 warnings:
131 description: The list of warnings (if any) generated by module based on arguments.
132 returned: always
133 type: list
134 sample: ['...', '...']
135 """
136
137 import time
138
139 from ansible.module_utils._text import to_text
140 from ansible.module_utils.basic import AnsibleModule
141 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.parsing import (
142 Conditional,
143 )
144 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
145 EntityCollection,
146 to_lines,
147 )
148 from ansible_collections.dellemc.enterprise_sonic.plugins.module_utils.network.sonic.sonic import run_commands
149 from ansible_collections.dellemc.enterprise_sonic.plugins.module_utils.network.sonic.utils.utils import command_list_str_to_dict
150
151
152 def transform_commands_dict(module, commands_dict):
153 transform = EntityCollection(
154 module,
155 dict(
156 command=dict(key=True),
157 output=dict(),
158 prompt=dict(type="list"),
159 answer=dict(type="list"),
160 newline=dict(type="bool", default=True),
161 sendonly=dict(type="bool", default=False),
162 check_all=dict(type="bool", default=False),
163 ),
164 )
165
166 return transform(commands_dict)
167
168
169 def parse_commands(module, warnings):
170 commands_dict = command_list_str_to_dict(module, warnings, module.params["commands"])
171 commands = transform_commands_dict(module, commands_dict)
172 return commands
173
174
175 def main():
176 """
177 Main entry point for module execution
178 """
179 argument_spec = dict(
180 # { command: <str>, prompt: <str>, response: <str> }
181 commands=dict(type='list', required=True, elements="str"),
182
183 wait_for=dict(type='list', elements="str"),
184 match=dict(default='all', choices=['all', 'any']),
185
186 retries=dict(default=10, type='int'),
187 interval=dict(default=1, type='int')
188 )
189
190 module = AnsibleModule(argument_spec=argument_spec,
191 supports_check_mode=True)
192 result = {'changed': False}
193
194 warnings = list()
195 # check_args(module, warnings)
196 commands = parse_commands(module, warnings)
197 result['warnings'] = warnings
198
199 wait_for = module.params['wait_for'] or list()
200 try:
201 conditionals = [Conditional(c) for c in wait_for]
202 except AttributeError as exc:
203 module.fail_json(msg=to_text(exc))
204 retries = module.params['retries']
205 interval = module.params['interval']
206 match = module.params['match']
207
208 while retries > 0:
209 responses = run_commands(module, commands)
210 for item in list(conditionals):
211 if item(responses):
212 if match == 'any':
213 conditionals = list()
214 break
215 conditionals.remove(item)
216
217 if not conditionals:
218 break
219
220 time.sleep(interval)
221 retries -= 1
222
223 if conditionals:
224 failed_conditions = [item.raw for item in conditionals]
225 msg = 'One or more conditional statements have not been satisfied.'
226 module.fail_json(msg=msg, failed_conditions=failed_conditions)
227
228 result.update({
229 'stdout': responses,
230 'stdout_lines': list(to_lines(responses))
231 })
232
233 module.exit_json(**result)
234
235
236 if __name__ == '__main__':
237 main()