Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 from __future__ import absolute_import, division, print_function
4
5
6 __metaclass__ = type
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10
11 DOCUMENTATION = """
12 module: nxos_snapshot
13 extends_documentation_fragment:
14 - cisco.nxos.nxos
15 short_description: Manage snapshots of the running states of selected features.
16 description:
17 - Create snapshots of the running states of selected features, add new show commands
18 for snapshot creation, delete and compare existing snapshots.
19 version_added: 1.0.0
20 author:
21 - Gabriele Gerbino (@GGabriele)
22 notes:
23 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
24 - Unsupported for Cisco MDS
25 - C(transport=cli) may cause timeout errors.
26 - The C(element_key1) and C(element_key2) parameter specify the tags used to distinguish
27 among row entries. In most cases, only the element_key1 parameter needs to specified
28 to be able to distinguish among row entries.
29 - C(action=compare) will always store a comparison report on a local file.
30 options:
31 action:
32 description:
33 - Define what snapshot action the module would perform.
34 required: true
35 choices:
36 - add
37 - compare
38 - create
39 - delete
40 - delete_all
41 type: str
42 snapshot_name:
43 description:
44 - Snapshot name, to be used when C(action=create) or C(action=delete).
45 type: str
46 description:
47 description:
48 - Snapshot description to be used when C(action=create).
49 type: str
50 snapshot1:
51 description:
52 - First snapshot to be used when C(action=compare).
53 type: str
54 snapshot2:
55 description:
56 - Second snapshot to be used when C(action=compare).
57 type: str
58 comparison_results_file:
59 description:
60 - Name of the file where snapshots comparison will be stored when C(action=compare).
61 type: str
62 compare_option:
63 description:
64 - Snapshot options to be used when C(action=compare).
65 choices:
66 - summary
67 - ipv4routes
68 - ipv6routes
69 type: str
70 section:
71 description:
72 - Used to name the show command output, to be used when C(action=add).
73 type: str
74 show_command:
75 description:
76 - Specify a new show command, to be used when C(action=add).
77 type: str
78 row_id:
79 description:
80 - Specifies the tag of each row entry of the show command's XML output, to be
81 used when C(action=add).
82 type: str
83 element_key1:
84 description:
85 - Specify the tags used to distinguish among row entries, to be used when C(action=add).
86 type: str
87 element_key2:
88 description:
89 - Specify the tags used to distinguish among row entries, to be used when C(action=add).
90 type: str
91 save_snapshot_locally:
92 description:
93 - Specify to locally store a new created snapshot, to be used when C(action=create).
94 type: bool
95 default: false
96 path:
97 description:
98 - Specify the path of the file where new created snapshot or snapshots comparison
99 will be stored, to be used when C(action=create) and C(save_snapshot_locally=true)
100 or C(action=compare).
101 default: ./
102 type: str
103 """
104
105 EXAMPLES = """
106 # Create a snapshot and store it locally
107 - cisco.nxos.nxos_snapshot:
108 action: create
109 snapshot_name: test_snapshot
110 description: Done with Ansible
111 save_snapshot_locally: true
112 path: /home/user/snapshots/
113
114 # Delete a snapshot
115 - cisco.nxos.nxos_snapshot:
116 action: delete
117 snapshot_name: test_snapshot
118
119 # Delete all existing snapshots
120 - cisco.nxos.nxos_snapshot:
121 action: delete_all
122
123 # Add a show command for snapshots creation
124 - cisco.nxos.nxos_snapshot:
125 section: myshow
126 show_command: show ip interface brief
127 row_id: ROW_intf
128 element_key1: intf-name
129
130 # Compare two snapshots
131 - cisco.nxos.nxos_snapshot:
132 action: compare
133 snapshot1: pre_snapshot
134 snapshot2: post_snapshot
135 comparison_results_file: compare_snapshots.txt
136 compare_option: summary
137 path: ../snapshot_reports/
138 """
139
140 RETURN = """
141 commands:
142 description: commands sent to the device
143 returned: verbose mode
144 type: list
145 sample: ["snapshot create post_snapshot Post-snapshot"]
146 """
147
148 import os
149 import re
150
151 from ansible.module_utils.basic import AnsibleModule
152
153 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
154 load_config,
155 run_commands,
156 )
157
158
159 def execute_show_command(command, module):
160 command = [{"command": command, "output": "text"}]
161
162 return run_commands(module, command)
163
164
165 def get_existing(module):
166 existing = []
167 command = "show snapshots"
168
169 body = execute_show_command(command, module)[0]
170 if body:
171 split_body = body.splitlines()
172 snapshot_regex = (
173 r"(?P<name>\S+)\s+(?P<date>\w+\s+\w+\s+\d+\s+\d+"
174 r":\d+:\d+\s+\d+)\s+(?P<description>.*)"
175 )
176 for snapshot in split_body:
177 temp = {}
178 try:
179 match_snapshot = re.match(snapshot_regex, snapshot, re.DOTALL)
180 snapshot_group = match_snapshot.groupdict()
181 temp["name"] = snapshot_group["name"]
182 temp["date"] = snapshot_group["date"]
183 temp["description"] = snapshot_group["description"]
184 existing.append(temp)
185 except AttributeError:
186 pass
187
188 return existing
189
190
191 def action_create(module, existing_snapshots):
192 commands = list()
193 exist = False
194 for snapshot in existing_snapshots:
195 if module.params["snapshot_name"] == snapshot["name"]:
196 exist = True
197
198 if exist is False:
199 commands.append(
200 "snapshot create {0} {1}".format(
201 module.params["snapshot_name"],
202 module.params["description"],
203 ),
204 )
205
206 return commands
207
208
209 def action_add(module, existing_snapshots):
210 commands = list()
211 command = "show snapshot sections"
212 sections = []
213 body = execute_show_command(command, module)[0]
214
215 if body:
216 section_regex = r".*\[(?P<section>\S+)\].*"
217 split_body = body.split("\n\n")
218 for section in split_body:
219 temp = {}
220 for line in section.splitlines():
221 try:
222 match_section = re.match(section_regex, section, re.DOTALL)
223 temp["section"] = match_section.groupdict()["section"]
224 except (AttributeError, KeyError):
225 pass
226
227 if "show command" in line:
228 temp["show_command"] = line.split("show command: ")[1]
229 elif "row id" in line:
230 temp["row_id"] = line.split("row id: ")[1]
231 elif "key1" in line:
232 temp["element_key1"] = line.split("key1: ")[1]
233 elif "key2" in line:
234 temp["element_key2"] = line.split("key2: ")[1]
235
236 if temp:
237 sections.append(temp)
238
239 proposed = {
240 "section": module.params["section"],
241 "show_command": module.params["show_command"],
242 "row_id": module.params["row_id"],
243 "element_key1": module.params["element_key1"],
244 "element_key2": module.params["element_key2"] or "-",
245 }
246
247 if proposed not in sections:
248 if module.params["element_key2"]:
249 commands.append(
250 'snapshot section add {0} "{1}" {2} {3} {4}'.format(
251 module.params["section"],
252 module.params["show_command"],
253 module.params["row_id"],
254 module.params["element_key1"],
255 module.params["element_key2"],
256 ),
257 )
258 else:
259 commands.append(
260 'snapshot section add {0} "{1}" {2} {3}'.format(
261 module.params["section"],
262 module.params["show_command"],
263 module.params["row_id"],
264 module.params["element_key1"],
265 ),
266 )
267
268 return commands
269
270
271 def action_compare(module, existing_snapshots):
272 command = "show snapshot compare {0} {1}".format(
273 module.params["snapshot1"],
274 module.params["snapshot2"],
275 )
276
277 if module.params["compare_option"]:
278 command += " {0}".format(module.params["compare_option"])
279
280 body = execute_show_command(command, module)[0]
281 return body
282
283
284 def action_delete(module, existing_snapshots):
285 commands = list()
286
287 exist = False
288 for snapshot in existing_snapshots:
289 if module.params["snapshot_name"] == snapshot["name"]:
290 exist = True
291
292 if exist:
293 commands.append("snapshot delete {0}".format(module.params["snapshot_name"]))
294
295 return commands
296
297
298 def action_delete_all(module, existing_snapshots):
299 commands = list()
300 if existing_snapshots:
301 commands.append("snapshot delete all")
302 return commands
303
304
305 def invoke(name, *args, **kwargs):
306 func = globals().get(name)
307 if func:
308 return func(*args, **kwargs)
309
310
311 def write_on_file(content, filename, module):
312 path = module.params["path"]
313 if path[-1] != "/":
314 path += "/"
315 filepath = "{0}{1}".format(path, filename)
316 try:
317 report = open(filepath, "w")
318 report.write(content)
319 report.close()
320 except Exception:
321 module.fail_json(msg="Error while writing on file.")
322
323 return filepath
324
325
326 def main():
327 argument_spec = dict(
328 action=dict(
329 required=True,
330 choices=["create", "add", "compare", "delete", "delete_all"],
331 ),
332 snapshot_name=dict(type="str"),
333 description=dict(type="str"),
334 snapshot1=dict(type="str"),
335 snapshot2=dict(type="str"),
336 compare_option=dict(choices=["summary", "ipv4routes", "ipv6routes"]),
337 comparison_results_file=dict(type="str"),
338 section=dict(type="str"),
339 show_command=dict(type="str"),
340 row_id=dict(type="str"),
341 element_key1=dict(type="str", no_log=False),
342 element_key2=dict(type="str", no_log=False),
343 save_snapshot_locally=dict(type="bool", default=False),
344 path=dict(type="str", default="./"),
345 )
346
347 required_if = [
348 (
349 "action",
350 "compare",
351 ["snapshot1", "snapshot2", "comparison_results_file"],
352 ),
353 ("action", "create", ["snapshot_name", "description"]),
354 (
355 "action",
356 "add",
357 ["section", "show_command", "row_id", "element_key1"],
358 ),
359 ("action", "delete", ["snapshot_name"]),
360 ]
361
362 module = AnsibleModule(
363 argument_spec=argument_spec,
364 required_if=required_if,
365 supports_check_mode=True,
366 )
367
368 action = module.params["action"]
369 comparison_results_file = module.params["comparison_results_file"]
370
371 if not os.path.isdir(module.params["path"]):
372 module.fail_json(msg="{0} is not a valid directory name.".format(module.params["path"]))
373
374 existing_snapshots = invoke("get_existing", module)
375 action_results = invoke("action_%s" % action, module, existing_snapshots)
376
377 result = {"changed": False, "commands": []}
378
379 if not module.check_mode:
380 if action == "compare":
381 result["commands"] = []
382
383 if module.params["path"] and comparison_results_file:
384 snapshot1 = module.params["snapshot1"]
385 snapshot2 = module.params["snapshot2"]
386 compare_option = module.params["compare_option"]
387 command = "show snapshot compare {0} {1}".format(snapshot1, snapshot2)
388 if compare_option:
389 command += " {0}".format(compare_option)
390 content = execute_show_command(command, module)[0]
391 if content:
392 write_on_file(content, comparison_results_file, module)
393 else:
394 if action_results:
395 load_config(module, action_results)
396 result["commands"] = action_results
397 result["changed"] = True
398
399 if (
400 action == "create"
401 and module.params["path"]
402 and module.params["save_snapshot_locally"]
403 ):
404 command = "show snapshot dump {0} | json".format(module.params["snapshot_name"])
405 content = execute_show_command(command, module)[0]
406 if content:
407 write_on_file(str(content), module.params["snapshot_name"], module)
408
409 module.exit_json(**result)
410
411
412 if __name__ == "__main__":
413 main()