Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18 from __future__ import absolute_import, division, print_function
19
20
21 __metaclass__ = type
22
23
24 DOCUMENTATION = """
25 module: nxos_install_os
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Set boot options like boot, kickstart image and issu.
29 description:
30 - Install an operating system by setting the boot options like boot image and kickstart
31 image and optionally select to install using ISSU (In Server Software Upgrade).
32 version_added: 1.0.0
33 notes:
34 - Tested against the following platforms and images - N9k 7.0(3)I4(6), 7.0(3)I5(3),
35 7.0(3)I6(1), 7.0(3)I7(1), 7.0(3)F2(2), 7.0(3)F3(2) - N3k 6.0(2)A8(6), 6.0(2)A8(8),
36 7.0(3)I6(1), 7.0(3)I7(1) - N7k 7.3(0)D1(1), 8.0(1), 8.1(1), 8.2(1)
37 - Tested against Cisco MDS NX-OS 9.2(1)
38 - This module requires both the ANSIBLE_PERSISTENT_CONNECT_TIMEOUT and ANSIBLE_PERSISTENT_COMMAND_TIMEOUT
39 timers to be set to 600 seconds or higher. The module will exit if the timers are
40 not set properly.
41 - When using connection local, ANSIBLE_PERSISTENT_CONNECT_TIMEOUT and ANSIBLE_PERSISTENT_COMMAND_TIMEOUT
42 can only be set using ENV variables or the ansible.cfg file.
43 - Do not include full file paths, just the name of the file(s) stored on the top level
44 flash directory.
45 - This module attempts to install the software immediately, which may trigger a reboot.
46 - In check mode, the module will indicate if an upgrade is needed and whether or not
47 the upgrade is disruptive or non-disruptive(ISSU).
48 author:
49 - Jason Edelman (@jedelman8)
50 - Gabriele Gerbibo (@GGabriele)
51 options:
52 system_image_file:
53 description:
54 - Name of the system (or combined) image file on flash.
55 required: true
56 type: str
57 kickstart_image_file:
58 description:
59 - Name of the kickstart image file on flash. (Not required on all Nexus platforms)
60 type: str
61 issu:
62 description:
63 - Upgrade using In Service Software Upgrade (ISSU). (Supported on N5k, N7k, N9k
64 platforms)
65 - Selecting 'required' or 'yes' means that upgrades will only proceed if the switch
66 is capable of ISSU.
67 - Selecting 'desired' means that upgrades will use ISSU if possible but will fall
68 back to disruptive upgrade if needed.
69 - Selecting 'no' means do not use ISSU. Forced disruptive.
70 choices:
71 - "required"
72 - "desired"
73 - "yes"
74 - "no"
75 default: "no"
76 type: str
77 """
78
79 EXAMPLES = """
80 - name: Install OS on N9k
81 check_mode: false
82 cisco.nxos.nxos_install_os:
83 system_image_file: nxos.7.0.3.I6.1.bin
84 issu: desired
85
86 - name: Wait for device to come back up with new image
87 wait_for:
88 port: 22
89 state: started
90 timeout: 500
91 delay: 60
92 host: '{{ inventory_hostname }}'
93
94 - name: Check installed OS for newly installed version
95 nxos_command:
96 commands: [show version | json]
97 register: output
98
99 - assert:
100 that:
101 - output['stdout'][0]['kickstart_ver_str'] == '7.0(3)I6(1)'
102 """
103
104 RETURN = """
105 install_state:
106 description: Boot and install information.
107 returned: always
108 type: dict
109 sample: {
110 "install_state": [
111 "Compatibility check is done:",
112 "Module bootable Impact Install-type Reason",
113 "------ -------- -------------- ------------ ------",
114 " 1 yes non-disruptive reset ",
115 "Images will be upgraded according to following table:",
116 "Module Image Running-Version(pri:alt) New-Version Upg-Required",
117 "------ ---------- ---------------------------------------- -------------------- ------------",
118 " 1 nxos 7.0(3)I6(1) 7.0(3)I7(1) yes",
119 " 1 bios v4.4.0(07/12/2017) v4.4.0(07/12/2017) no"
120 ],
121 }
122 """
123
124
125 import re
126
127 from time import sleep
128
129 from ansible.module_utils.basic import AnsibleModule
130
131 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
132 load_config,
133 run_commands,
134 )
135
136
137 # Output options are 'text' or 'json'
138 def execute_show_command(module, command, output="text"):
139 cmds = [{"command": command, "output": output}]
140
141 return run_commands(module, cmds)
142
143
144 def get_platform(module):
145 """Determine platform type"""
146 data = execute_show_command(module, "show inventory", "json")
147 pid = data[0]["TABLE_inv"]["ROW_inv"][0]["productid"]
148
149 if re.search(r"N3K", pid):
150 type = "N3K"
151 elif re.search(r"N5K", pid):
152 type = "N5K"
153 elif re.search(r"N6K", pid):
154 type = "N6K"
155 elif re.search(r"N7K", pid):
156 type = "N7K"
157 elif re.search(r"N9K", pid):
158 type = "N9K"
159 else:
160 type = "unknown"
161
162 return type
163
164
165 def parse_show_install(data):
166 """Helper method to parse the output of the 'show install all impact' or
167 'install all' commands.
168
169 Sample Output:
170
171 Installer will perform impact only check. Please wait.
172
173 Verifying image bootflash:/nxos.7.0.3.F2.2.bin for boot variable "nxos".
174 [####################] 100% -- SUCCESS
175
176 Verifying image type.
177 [####################] 100% -- SUCCESS
178
179 Preparing "bios" version info using image bootflash:/nxos.7.0.3.F2.2.bin.
180 [####################] 100% -- SUCCESS
181
182 Preparing "nxos" version info using image bootflash:/nxos.7.0.3.F2.2.bin.
183 [####################] 100% -- SUCCESS
184
185 Performing module support checks.
186 [####################] 100% -- SUCCESS
187
188 Notifying services about system upgrade.
189 [####################] 100% -- SUCCESS
190
191
192
193 Compatibility check is done:
194 Module bootable Impact Install-type Reason
195 ------ -------- -------------- ------------ ------
196 8 yes disruptive reset Incompatible image for ISSU
197 21 yes disruptive reset Incompatible image for ISSU
198
199
200 Images will be upgraded according to following table:
201 Module Image Running-Version(pri:alt) New-Version Upg-Required
202 ------ ---------- ---------------------------------------- ------------
203 8 lcn9k 7.0(3)F3(2) 7.0(3)F2(2) yes
204 8 bios v01.17 v01.17 no
205 21 lcn9k 7.0(3)F3(2) 7.0(3)F2(2) yes
206 21 bios v01.70 v01.70 no
207 """
208 if len(data) > 0:
209 data = massage_install_data(data)
210 ud = {"raw": data}
211 ud["processed"] = []
212 ud["disruptive"] = False
213 ud["upgrade_needed"] = False
214 ud["error"] = False
215 ud["invalid_command"] = False
216 ud["install_in_progress"] = False
217 ud["server_error"] = False
218 ud["upgrade_succeeded"] = False
219 ud["use_impact_data"] = False
220
221 # Check for server errors
222 if isinstance(data, int):
223 if data == -1:
224 ud["server_error"] = True
225 elif data >= 500:
226 ud["server_error"] = True
227 elif data == -32603:
228 ud["server_error"] = True
229 elif data == 1:
230 ud["server_error"] = True
231 return ud
232 else:
233 ud["list_data"] = data.split("\n")
234
235 for x in ud["list_data"]:
236 # Check for errors and exit if found.
237 if re.search(r"Pre-upgrade check failed", x):
238 ud["error"] = True
239 break
240 if re.search(r"[I|i]nvalid command", x):
241 ud["invalid_command"] = True
242 ud["error"] = True
243 break
244 if re.search(r"No install all data found", x):
245 ud["error"] = True
246 break
247
248 # Check for potentially transient conditions
249 if re.search(r"Another install procedure may\s*be in progress", x):
250 ud["install_in_progress"] = True
251 break
252 if re.search(r"Backend processing error", x):
253 ud["server_error"] = True
254 break
255 if re.search(r"timed out", x):
256 ud["server_error"] = True
257 break
258 if re.search(r"^(-1|5\d\d)$", x):
259 ud["server_error"] = True
260 break
261
262 # Check for messages indicating a successful upgrade.
263 if re.search(r"Finishing the upgrade", x):
264 ud["upgrade_succeeded"] = True
265 break
266 if re.search(r"Install has been successful", x):
267 ud["upgrade_succeeded"] = True
268 break
269 if re.search(r"Switching over onto standby", x):
270 ud["upgrade_succeeded"] = True
271 break
272
273 # We get these messages when the upgrade is non-disruptive and
274 # we loose connection with the switchover but far enough along that
275 # we can be confident the upgrade succeeded.
276 if re.search(r"timeout .*trying to send command: install", x):
277 ud["upgrade_succeeded"] = True
278 ud["use_impact_data"] = True
279 break
280 if re.search(r"[C|c]onnection failure: timed out", x):
281 ud["upgrade_succeeded"] = True
282 ud["use_impact_data"] = True
283 break
284
285 # Begin normal parsing.
286 if re.search(r"----|Module|Images will|Compatibility", x):
287 ud["processed"].append(x)
288 continue
289 # Check to see if upgrade will be disruptive or non-disruptive and
290 # build dictionary of individual modules and their status.
291 # Sample Line:
292 #
293 # Module bootable Impact Install-type Reason
294 # ------ -------- ---------- ------------ ------
295 # 8 yes disruptive reset Incompatible image
296 rd = r"(\d+)\s+(\S+)\s+(disruptive|non-disruptive)\s+(\S+)"
297 mo = re.search(rd, x)
298 if mo:
299 ud["processed"].append(x)
300 key = "m%s" % mo.group(1)
301 field = "disruptive"
302 if mo.group(3) == "non-disruptive":
303 ud[key] = {field: False}
304 else:
305 ud[field] = True
306 ud[key] = {field: True}
307 field = "bootable"
308 if mo.group(2) == "yes":
309 ud[key].update({field: True})
310 else:
311 ud[key].update({field: False})
312 continue
313
314 # Check to see if switch needs an upgrade and build a dictionary
315 # of individual modules and their individual upgrade status.
316 # Sample Line:
317 #
318 # Module Image Running-Version(pri:alt) New-Version Upg-Required
319 # ------ ----- ---------------------------------------- ------------
320 # 8 lcn9k 7.0(3)F3(2) 7.0(3)F2(2) yes
321 mo = re.search(r"(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)", x)
322 if mo:
323 ud["processed"].append(x)
324 key = "m%s_%s" % (mo.group(1), mo.group(2))
325 field = "upgrade_needed"
326 if mo.group(5) == "yes":
327 ud[field] = True
328 ud[key] = {field: True}
329 else:
330 ud[key] = {field: False}
331 continue
332
333 return ud
334
335
336 def massage_install_data(data):
337 # Transport cli returns a list containing one result item.
338 # Transport nxapi returns a list containing two items. The second item
339 # contains the data we are interested in.
340 default_error_msg = "No install all data found"
341 if len(data) == 1:
342 result_data = data[0]
343 elif len(data) == 2:
344 result_data = data[1]
345 else:
346 result_data = default_error_msg
347
348 # Further processing may be needed for result_data
349 if len(data) == 2 and isinstance(data[1], dict):
350 if "clierror" in data[1].keys():
351 result_data = data[1]["clierror"]
352 elif "code" in data[1].keys() and data[1]["code"] == "500":
353 # We encountered a backend processing error for nxapi
354 result_data = data[1]["msg"]
355 else:
356 result_data = default_error_msg
357 return result_data
358
359
360 def build_install_cmd_set(issu, image, kick, type, force=True):
361 commands = ["terminal dont-ask"]
362
363 # Different NX-OS platforms behave differently for
364 # disruptive and non-disruptive upgrade paths.
365 #
366 # 1) Combined kickstart/system image:
367 # * Use option 'non-disruptive' for issu.
368 # * Omit option 'non-disruptive' for disruptive upgrades.
369 # 2) Separate kickstart + system images.
370 # * Omit hidden 'force' option for issu.
371 # * Use hidden 'force' option for disruptive upgrades.
372 # * Note: Not supported on all platforms
373 if re.search(r"required|desired|yes", issu):
374 if kick is None:
375 issu_cmd = "non-disruptive"
376 else:
377 issu_cmd = ""
378 else:
379 if kick is None:
380 issu_cmd = ""
381 else:
382 issu_cmd = "force" if force else ""
383
384 if type == "impact":
385 rootcmd = "show install all impact"
386 # The force option is not available for the impact command.
387 if kick:
388 issu_cmd = ""
389 else:
390 rootcmd = "install all"
391 if kick is None:
392 commands.append("%s nxos %s %s" % (rootcmd, image, issu_cmd))
393 else:
394 commands.append(
395 "%s %s system %s kickstart %s" % (rootcmd, issu_cmd, image, kick),
396 )
397
398 return commands
399
400
401 def parse_show_version(data):
402 version_data = {"raw": data[0].split("\n")}
403 version_data["version"] = ""
404 version_data["error"] = False
405 for x in version_data["raw"]:
406 mo = re.search(r"(kickstart|system|NXOS):\s+version\s+(\S+)", x)
407 if mo:
408 version_data["version"] = mo.group(2)
409 continue
410
411 if version_data["version"] == "":
412 version_data["error"] = True
413
414 return version_data
415
416
417 def check_mode_legacy(module, issu, image, kick=None):
418 """Some platforms/images/transports don't support the 'install all impact'
419 command so we need to use a different method."""
420 current = execute_show_command(module, "show version", "json")[0]
421 # Call parse_show_data on empty string to create the default upgrade
422 # data structure dictionary
423 data = parse_show_install("")
424 upgrade_msg = "No upgrade required"
425
426 # Process System Image
427 data["error"] = False
428 tsver = "show version image bootflash:%s" % image
429 data["upgrade_cmd"] = [tsver]
430 target_image = parse_show_version(execute_show_command(module, tsver))
431 if target_image["error"]:
432 data["error"] = True
433 data["raw"] = target_image["raw"]
434 if current["kickstart_ver_str"] != target_image["version"] and not data["error"]:
435 data["upgrade_needed"] = True
436 data["disruptive"] = True
437 upgrade_msg = "Switch upgraded: system: %s" % tsver
438
439 # Process Kickstart Image
440 if kick is not None and not data["error"]:
441 tkver = "show version image bootflash:%s" % kick
442 data["upgrade_cmd"].append(tsver)
443 target_kick = parse_show_version(execute_show_command(module, tkver))
444 if target_kick["error"]:
445 data["error"] = True
446 data["raw"] = target_kick["raw"]
447 if current["kickstart_ver_str"] != target_kick["version"] and not data["error"]:
448 data["upgrade_needed"] = True
449 data["disruptive"] = True
450 upgrade_msg = upgrade_msg + " kickstart: %s" % tkver
451
452 data["list_data"] = data["raw"]
453 data["processed"] = upgrade_msg
454 return data
455
456
457 def check_mode_nextgen(module, issu, image, kick=None):
458 """Use the 'install all impact' command for check_mode"""
459 opts = {"ignore_timeout": True}
460 commands = build_install_cmd_set(issu, image, kick, "impact")
461 data = parse_show_install(load_config(module, commands, True, opts))
462 # If an error is encountered when issu is 'desired' then try again
463 # but set issu to 'no'
464 if data["error"] and issu == "desired":
465 issu = "no"
466 commands = build_install_cmd_set(issu, image, kick, "impact")
467 # The system may be busy from the previous call to check_mode so loop
468 # until it's done.
469 data = check_install_in_progress(module, commands, opts)
470 if data["server_error"]:
471 data["error"] = True
472 data["upgrade_cmd"] = commands
473 return data
474
475
476 def check_install_in_progress(module, commands, opts):
477 for attempt in range(20):
478 data = parse_show_install(load_config(module, commands, True, opts))
479 if data["install_in_progress"]:
480 sleep(1)
481 continue
482 break
483 return data
484
485
486 def check_mode(module, issu, image, kick=None):
487 """Check switch upgrade impact using 'show install all impact' command"""
488 data = check_mode_nextgen(module, issu, image, kick)
489 if data["server_error"]:
490 # We encountered an unrecoverable error in the attempt to get upgrade
491 # impact data from the 'show install all impact' command.
492 # Fallback to legacy method.
493 data = check_mode_legacy(module, issu, image, kick)
494 if data["invalid_command"]:
495 # If we are upgrading from a device running a separate kickstart and
496 # system image the impact command will fail.
497 # Fallback to legacy method.
498 data = check_mode_legacy(module, issu, image, kick)
499 return data
500
501
502 def do_install_all(module, issu, image, kick=None):
503 """Perform the switch upgrade using the 'install all' command"""
504 impact_data = check_mode(module, issu, image, kick)
505 if module.check_mode:
506 # Check mode set in the playbook so just return the impact data.
507 msg = "*** SWITCH WAS NOT UPGRADED: IMPACT DATA ONLY ***"
508 impact_data["processed"].append(msg)
509 return impact_data
510 if impact_data["error"]:
511 # Check mode discovered an error so return with this info.
512 return impact_data
513 elif not impact_data["upgrade_needed"]:
514 # The switch is already upgraded. Nothing more to do.
515 return impact_data
516 else:
517 # If we get here, check_mode returned no errors and the switch
518 # needs to be upgraded.
519 if impact_data["disruptive"]:
520 # Check mode indicated that ISSU is not possible so issue the
521 # upgrade command without the non-disruptive flag unless the
522 # playbook specified issu: yes/required.
523 if issu == "yes":
524 msg = "ISSU/ISSD requested but impact data indicates ISSU/ISSD is not possible"
525 module.fail_json(msg=msg, raw_data=impact_data["list_data"])
526 else:
527 issu = "no"
528
529 commands = build_install_cmd_set(issu, image, kick, "install")
530 opts = {"ignore_timeout": True}
531 # The system may be busy from the call to check_mode so loop until
532 # it's done.
533 upgrade = check_install_in_progress(module, commands, opts)
534 if upgrade["invalid_command"] and "force" in commands[1]:
535 # Not all platforms support the 'force' keyword. Check for this
536 # condition and re-try without the 'force' keyword if needed.
537 commands = build_install_cmd_set(issu, image, kick, "install", False)
538 upgrade = check_install_in_progress(module, commands, opts)
539 upgrade["upgrade_cmd"] = commands
540
541 # Special case: If we encounter a server error at this stage
542 # it means the command was sent and the upgrade was started but
543 # we will need to use the impact data instead of the current install
544 # data.
545 if upgrade["server_error"]:
546 upgrade["upgrade_succeeded"] = True
547 upgrade["use_impact_data"] = True
548
549 if upgrade["use_impact_data"]:
550 if upgrade["upgrade_succeeded"]:
551 upgrade = impact_data
552 upgrade["upgrade_succeeded"] = True
553 else:
554 upgrade = impact_data
555 upgrade["upgrade_succeeded"] = False
556
557 if not upgrade["upgrade_succeeded"]:
558 upgrade["error"] = True
559 return upgrade
560
561
562 def main():
563 argument_spec = dict(
564 system_image_file=dict(required=True),
565 kickstart_image_file=dict(required=False),
566 issu=dict(choices=["required", "desired", "no", "yes"], default="no"),
567 )
568
569 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
570
571 warnings = list()
572
573 # Get system_image_file(sif), kickstart_image_file(kif) and
574 # issu settings from module params.
575 sif = module.params["system_image_file"]
576 kif = module.params["kickstart_image_file"]
577 issu = module.params["issu"]
578
579 if re.search(r"(yes|required)", issu):
580 issu = "yes"
581
582 if kif == "null" or kif == "":
583 kif = None
584
585 install_result = do_install_all(module, issu, sif, kick=kif)
586 if install_result["error"]:
587 cmd = install_result["upgrade_cmd"]
588 msg = "Failed to upgrade device using command: %s" % cmd
589 module.fail_json(msg=msg, raw_data=install_result["list_data"])
590
591 state = install_result["processed"]
592 changed = install_result["upgrade_needed"]
593 module.exit_json(changed=changed, install_state=state, warnings=warnings)
594
595
596 if __name__ == "__main__":
597 main()