Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_config.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_config
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 author: Peter Sprygada (@privateip)
29 short_description: Manage Cisco NXOS configuration sections
30 description:
31 - Cisco NXOS configurations use a simple block indent file syntax for segmenting configuration
32 into sections. This module provides an implementation for working with NXOS configuration
33 sections in a deterministic way. This module works with either CLI or NXAPI transports.
34 version_added: 1.0.0
35 options:
36 lines:
37 description:
38 - The ordered set of commands that should be configured in the section. The commands
39 must be the exact same commands as found in the device running-config to ensure idempotency
40 and correct diff. Be sure to note the configuration command syntax as some commands are
41 automatically modified by the device config parser.
42 type: list
43 aliases:
44 - commands
45 elements: str
46 parents:
47 description:
48 - The ordered set of parents that uniquely identify the section or hierarchy the
49 commands should be checked against. If the parents argument is omitted, the
50 commands are checked against the set of top level or global commands.
51 type: list
52 elements: str
53 src:
54 description:
55 - Specifies the source path to the file that contains the configuration or configuration
56 template to load. The path to the source file can either be the full path on
57 the Ansible control host or a relative path from the playbook or role root directory. This
58 argument is mutually exclusive with I(lines), I(parents), I(replace_src), and I(content). The configuration lines in the
59 source file should be similar to how it will appear if present in the running-configuration
60 of the device including the indentation to ensure idempotency and correct diff.
61 - "NOTE: The I(src) parameter will no longer process Jinja2 templates starting in January 2028.
62 To use templated configurations, render the template using C(ansible.builtin.template) lookup
63 and pass the result to the I(content) parameter instead."
64 type: path
65 content:
66 description:
67 - Configuration content to apply to the device. This should be the rendered configuration
68 text, not a file path.
69 - This is the recommended way to provide templated configurations. Use C(ansible.builtin.template)
70 lookup to render your Jinja2 template and pass the output to this parameter.
71 - This argument is mutually exclusive with I(src), I(lines), I(parents), and I(replace_src).
72 - 'Example: C(content: "{{ lookup(''ansible.builtin.template'', ''config.j2'') }}")'
73 type: str
74 replace_src:
75 description:
76 - The I(replace_src) argument provides path to the configuration file to load
77 into the remote system. This argument is used to replace the entire config with
78 a flat-file. This is used with argument I(replace) with value I(config). This
79 is mutually exclusive with the I(lines) and I(src) arguments. This argument
80 will only work for NX-OS versions that support `config replace`. Use I(nxos_file_copy)
81 module to copy the flat file to remote device and then use the path with this argument.
82 The configuration lines in the file should be similar to how it
83 will appear if present in the running-configuration of the device including the indentation
84 to ensure idempotency and correct diff.
85 type: str
86 before:
87 description:
88 - The ordered set of commands to push on to the command stack if a change needs
89 to be made. This allows the playbook designer the opportunity to perform configuration
90 commands prior to pushing any changes without affecting how the set of commands
91 are matched against the system.
92 type: list
93 elements: str
94 after:
95 description:
96 - The ordered set of commands to append to the end of the command stack if a change
97 needs to be made. Just like with I(before) this allows the playbook designer
98 to append a set of commands to be executed after the command set.
99 type: list
100 elements: str
101 match:
102 description:
103 - Instructs the module on the way to perform the matching of the set of commands
104 against the current device config. If match is set to I(line), commands are
105 matched line by line. If match is set to I(strict), command lines are matched
106 with respect to position. If match is set to I(exact), command lines must be
107 an equal match. Finally, if match is set to I(none), the module will not attempt
108 to compare the source configuration with the running configuration on the remote
109 device.
110 default: line
111 choices:
112 - line
113 - strict
114 - exact
115 - none
116 type: str
117 replace:
118 description:
119 - Instructs the module on the way to perform the configuration on the device. If
120 the replace argument is set to I(line) then the modified lines are pushed to
121 the device in configuration mode. If the replace argument is set to I(block)
122 then the entire command block is pushed to the device in configuration mode
123 if any line is not correct. replace I(config) will only work for NX-OS versions
124 that support `config replace`.
125 default: line
126 choices:
127 - line
128 - block
129 - config
130 type: str
131 backup:
132 description:
133 - This argument will cause the module to create a full backup of the current C(running-config)
134 from the remote device before any changes are made. If the C(backup_options)
135 value is not given, the backup file is written to the C(backup) folder in the
136 playbook root directory or role root directory, if playbook is part of an ansible
137 role. If the directory does not exist, it is created.
138 type: bool
139 default: false
140 running_config:
141 description:
142 - The module, by default, will connect to the remote device and retrieve the current
143 running-config to use as a base for comparing against the contents of source. There
144 are times when it is not desirable to have the task get the current running-config
145 for every task in a playbook. The I(running_config) argument allows the implementer
146 to pass in the configuration to use as the base config for comparison.
147 The configuration lines for this option should be similar to how it will appear if present
148 in the running-configuration of the device including the indentation to ensure idempotency
149 and correct diff.
150 aliases:
151 - config
152 type: str
153 defaults:
154 description:
155 - The I(defaults) argument will influence how the running-config is collected
156 from the device. When the value is set to true, the command used to collect
157 the running-config is append with the all keyword. When the value is set to
158 false, the command is issued without the all keyword
159 type: bool
160 default: false
161 save_when:
162 description:
163 - When changes are made to the device running-configuration, the changes are not
164 copied to non-volatile storage by default. Using this argument will change
165 that before. If the argument is set to I(always), then the running-config will
166 always be copied to the startup-config and the I(modified) flag will always
167 be set to True. If the argument is set to I(modified), then the running-config
168 will only be copied to the startup-config if it has changed since the last save
169 to startup-config. If the argument is set to I(never), the running-config will
170 never be copied to the startup-config. If the argument is set to I(changed),
171 then the running-config will only be copied to the startup-config if the task
172 has made a change. I(changed) was added in Ansible 2.6.
173 default: never
174 choices:
175 - always
176 - never
177 - modified
178 - changed
179 type: str
180 diff_against:
181 description:
182 - When using the C(ansible-playbook --diff) command line argument the module can
183 generate diffs against different sources.
184 - When this option is configure as I(startup), the module will return the diff
185 of the running-config against the startup-config.
186 - When this option is configured as I(intended), the module will return the diff
187 of the running-config against the configuration provided in the C(intended_config)
188 argument.
189 - When this option is configured as I(running), the module will return the before
190 and after diff of the running-config with respect to any changes made to the
191 device configuration.
192 choices:
193 - startup
194 - intended
195 - running
196 type: str
197 diff_ignore_lines:
198 description:
199 - Use this argument to specify one or more lines that should be ignored during
200 the diff. This is used for lines in the configuration that are automatically
201 updated by the system. This argument takes a list of regular expressions or
202 exact line matches.
203 type: list
204 elements: str
205 intended_config:
206 description:
207 - The C(intended_config) provides the master configuration that the node should
208 conform to and is used to check the final running-config against. This argument
209 will not modify any settings on the remote device and is strictly used to check
210 the compliance of the current device's configuration against. When specifying
211 this argument, the task should also modify the C(diff_against) value and set
212 it to I(intended). The configuration lines for this value should be similar to how it
213 will appear if present in the running-configuration of the device including the indentation
214 to ensure correct diff.
215 type: str
216 backup_options:
217 description:
218 - This is a dict object containing configurable options related to backup file
219 path. The value of this option is read only when C(backup) is set to I(True),
220 if C(backup) is set to I(false) this option will be silently ignored.
221 suboptions:
222 filename:
223 description:
224 - The filename to be used to store the backup configuration. If the filename
225 is not given it will be generated based on the hostname, current time and
226 date in format defined by <hostname>_config.<current-date>@<current-time>
227 type: str
228 dir_path:
229 description:
230 - This option provides the path ending with directory name in which the backup
231 configuration file will be stored. If the directory does not exist it will
232 be created and the filename is either the value of C(filename) or default
233 filename as described in C(filename) options description. If the path value
234 is not given in that case a I(backup) directory will be created in the current
235 working directory and backup configuration will be copied in C(filename)
236 within I(backup) directory.
237 type: path
238 type: dict
239 notes:
240 - Tested against Cisco NXOS 9.3(x) on Nexus switches.
241 - Unsupported for Cisco MDS
242 - Abbreviated commands are NOT idempotent, see
243 U(https://docs.ansible.com/ansible/latest/network/user_guide/faq.html#why-do-the-config-modules-always-return-changed-true-with-abbreviated-commands).
244 - To ensure idempotency and correct diff the configuration lines in the relevant module options should be similar to how they
245 appear if present in the running configuration on device including the indentation.
246 - The recommended way to use templated configurations is to render the template using C(ansible.builtin.template)
247 lookup and pass the result to the I(content) parameter. Using I(src) with Jinja2 templates is deprecated.
248 """
249
250 EXAMPLES = """
251 - name: configure top level configuration and save it
252 cisco.nxos.nxos_config:
253 lines: hostname {{ inventory_hostname }}
254 save_when: modified
255
256 - name: diff the running-config against a provided config
257 cisco.nxos.nxos_config:
258 diff_against: intended
259 intended_config: "{{ lookup('file', 'master.cfg') }}"
260
261 - cisco.nxos.nxos_config:
262 lines:
263 - 10 permit ip 192.0.2.1/32 any log
264 - 20 permit ip 192.0.2.2/32 any log
265 - 30 permit ip 192.0.2.3/32 any log
266 - 40 permit ip 192.0.2.4/32 any log
267 - 50 permit ip 192.0.2.5/32 any log
268 parents: ip access-list test
269 before: no ip access-list test
270 match: exact
271
272 - cisco.nxos.nxos_config:
273 lines:
274 - 10 permit ip 192.0.2.1/32 any log
275 - 20 permit ip 192.0.2.2/32 any log
276 - 30 permit ip 192.0.2.3/32 any log
277 - 40 permit ip 192.0.2.4/32 any log
278 parents: ip access-list test
279 before: no ip access-list test
280 replace: block
281
282 - name: replace config with flat file
283 cisco.nxos.nxos_config:
284 replace_src: config.txt
285 replace: config
286
287 - name: for idempotency, use full-form commands
288 cisco.nxos.nxos_config:
289 lines:
290 # - shut
291 - shutdown
292 # parents: int eth1/1
293 parents: interface Ethernet1/1
294
295 - name: configurable backup path
296 cisco.nxos.nxos_config:
297 backup: true
298 backup_options:
299 filename: backup.cfg
300 dir_path: /home/user
301
302 - name: Render a Jinja2 template onto an NXOS device (DEPRECATED - use content parameter)
303 cisco.nxos.nxos_config:
304 backup: true
305 src: nxos_template.j2
306
307 - name: Apply templated configuration using content parameter (RECOMMENDED)
308 cisco.nxos.nxos_config:
309 content: "{{ lookup('ansible.builtin.template', 'nxos_template.j2') }}"
310 backup: true
311
312 - name: Apply templated configuration with backup options (RECOMMENDED)
313 cisco.nxos.nxos_config:
314 content: "{{ lookup('ansible.builtin.template', 'nxos_template.j2') }}"
315 backup: true
316 backup_options:
317 filename: backup.cfg
318 dir_path: /home/user
319
320 - name: Load configuration from pre-rendered template
321 cisco.nxos.nxos_config:
322 content: |
323 interface Ethernet1/1
324 description Uplink to Core
325 ip address 10.1.1.1/24
326 no shutdown
327 """
328
329 RETURN = """
330 commands:
331 description: The set of commands that will be pushed to the remote device
332 returned: always
333 type: list
334 sample: ['hostname foo', 'vlan 1', 'name default']
335 updates:
336 description: The set of commands that will be pushed to the remote device
337 returned: always
338 type: list
339 sample: ['hostname foo', 'vlan 1', 'name default']
340 backup_path:
341 description: The full path to the backup file
342 returned: when backup is yes
343 type: str
344 sample: /playbooks/ansible/backup/nxos_config.2016-07-16@22:28:34
345 filename:
346 description: The name of the backup file
347 returned: when backup is yes and filename is not specified in backup options
348 type: str
349 sample: nxos_config.2016-07-16@22:28:34
350 shortname:
351 description: The full path to the backup file excluding the timestamp
352 returned: when backup is yes and filename is not specified in backup options
353 type: str
354 sample: /playbooks/ansible/backup/nxos_config
355 date:
356 description: The date extracted from the backup file name
357 returned: when backup is yes
358 type: str
359 sample: "2016-07-16"
360 time:
361 description: The time extracted from the backup file name
362 returned: when backup is yes
363 type: str
364 sample: "22:28:34"
365 """
366 from ansible.module_utils._text import to_text
367 from ansible.module_utils.basic import AnsibleModule
368 from ansible.module_utils.connection import ConnectionError
369 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import (
370 NetworkConfig,
371 dumps,
372 )
373 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list
374
375 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
376 get_config,
377 get_connection,
378 load_config,
379 run_commands,
380 )
381
382
383 def get_running_config(module, config=None, flags=None):
384 contents = module.params["running_config"]
385 if not contents:
386 if config:
387 contents = config
388 else:
389 contents = get_config(module, flags=flags)
390 return contents
391
392
393 def get_candidate(module):
394 candidate = ""
395 if module.params["src"]:
396 if module.params["replace"] != "config":
397 candidate = module.params["src"]
398 elif module.params["content"]:
399 candidate = module.params["content"]
400 if module.params["replace"] == "config":
401 candidate = "config replace {0}".format(module.params["replace_src"])
402 elif module.params["lines"]:
403 candidate_obj = NetworkConfig(indent=2)
404 parents = module.params["parents"] or list()
405 candidate_obj.add(module.params["lines"], parents=parents)
406 candidate = dumps(candidate_obj, "raw")
407 return candidate
408
409
410 def execute_show_commands(module, commands, output="text"):
411 cmds = []
412 for command in to_list(commands):
413 cmd = {"command": command, "output": output}
414 cmds.append(cmd)
415 body = run_commands(module, cmds)
416 return body
417
418
419 def save_config(module, result):
420 result["changed"] = True
421 if not module.check_mode:
422 cmd = {
423 "command": "copy running-config startup-config",
424 "output": "text",
425 }
426 run_commands(module, [cmd])
427 else:
428 module.warn(
429 "Skipping command `copy running-config startup-config` "
430 "due to check_mode. Configuration not copied to "
431 "non-volatile storage",
432 )
433
434
435 def main():
436 """main entry point for module execution"""
437 backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
438 argument_spec = dict(
439 src=dict(type="path"),
440 content=dict(type="str"),
441 replace_src=dict(),
442 lines=dict(aliases=["commands"], type="list", elements="str"),
443 parents=dict(type="list", elements="str"),
444 before=dict(type="list", elements="str"),
445 after=dict(type="list", elements="str"),
446 match=dict(default="line", choices=["line", "strict", "exact", "none"]),
447 replace=dict(default="line", choices=["line", "block", "config"]),
448 running_config=dict(aliases=["config"]),
449 intended_config=dict(),
450 defaults=dict(type="bool", default=False),
451 backup=dict(type="bool", default=False),
452 backup_options=dict(type="dict", options=backup_spec),
453 save_when=dict(
454 choices=["always", "never", "modified", "changed"],
455 default="never",
456 ),
457 diff_against=dict(choices=["running", "startup", "intended"]),
458 diff_ignore_lines=dict(type="list", elements="str"),
459 )
460
461 mutually_exclusive = [("lines", "src", "replace_src", "content"), ("parents", "src", "content")]
462
463 required_if = [
464 ("match", "strict", ["lines", "src", "content"], True),
465 ("match", "exact", ["lines", "src", "content"], True),
466 ("replace", "block", ["lines", "src", "content"], True),
467 ("replace", "config", ["replace_src"]),
468 ("diff_against", "intended", ["intended_config"]),
469 ]
470
471 module = AnsibleModule(
472 argument_spec=argument_spec,
473 mutually_exclusive=mutually_exclusive,
474 required_if=required_if,
475 supports_check_mode=True,
476 )
477
478 warnings = list()
479
480 result = {"changed": False, "warnings": warnings}
481
482 config = None
483
484 diff_ignore_lines = module.params["diff_ignore_lines"]
485 path = module.params["parents"]
486 connection = get_connection(module)
487 contents = None
488 flags = ["all"] if module.params["defaults"] else []
489 replace_src = module.params["replace_src"]
490 if replace_src:
491 if module.params["replace"] != "config":
492 module.fail_json(msg="replace: config is required with replace_src")
493
494 if module.params["backup"] or (module._diff and module.params["diff_against"] == "running"):
495 contents = get_config(module, flags=flags)
496 config = NetworkConfig(indent=2, contents=contents)
497 if module.params["backup"]:
498 result["__backup__"] = contents
499
500 if any((module.params["src"], module.params["lines"], module.params["content"], replace_src)):
501 match = module.params["match"]
502 replace = module.params["replace"]
503
504 commit = not module.check_mode
505 candidate = get_candidate(module)
506 running = get_running_config(module, contents, flags=flags)
507 if replace_src:
508 commands = candidate.split("\n")
509 result["commands"] = result["updates"] = commands
510 if commit:
511 load_config(module, commands, replace=replace_src)
512
513 result["changed"] = True
514 else:
515 try:
516 response = connection.get_diff(
517 candidate=candidate,
518 running=running,
519 diff_match=match,
520 diff_ignore_lines=diff_ignore_lines,
521 path=path,
522 diff_replace=replace,
523 )
524 except ConnectionError as exc:
525 module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))
526
527 config_diff = response["config_diff"]
528 if config_diff:
529 commands = config_diff.split("\n")
530
531 if module.params["before"]:
532 commands[:0] = module.params["before"]
533
534 if module.params["after"]:
535 commands.extend(module.params["after"])
536
537 result["commands"] = commands
538 result["updates"] = commands
539
540 if commit:
541 load_config(module, commands, replace=replace_src)
542
543 result["changed"] = True
544
545 running_config = module.params["running_config"]
546 startup_config = None
547
548 if module.params["save_when"] == "always":
549 save_config(module, result)
550 elif module.params["save_when"] == "modified":
551 output = execute_show_commands(
552 module,
553 ["show running-config", "show startup-config"],
554 )
555
556 running_config = NetworkConfig(
557 indent=2,
558 contents=output[0],
559 ignore_lines=diff_ignore_lines,
560 )
561 startup_config = NetworkConfig(
562 indent=2,
563 contents=output[1],
564 ignore_lines=diff_ignore_lines,
565 )
566
567 if running_config.sha1 != startup_config.sha1:
568 save_config(module, result)
569 elif module.params["save_when"] == "changed" and result["changed"]:
570 save_config(module, result)
571
572 if module._diff:
573 if not running_config:
574 output = execute_show_commands(module, "show running-config")
575 contents = output[0]
576 else:
577 contents = running_config
578
579 # recreate the object in order to process diff_ignore_lines
580 running_config = NetworkConfig(
581 indent=2,
582 contents=contents,
583 ignore_lines=diff_ignore_lines,
584 )
585
586 if module.params["diff_against"] == "running":
587 if module.check_mode:
588 module.warn(
589 "unable to perform diff against running-config due to check mode",
590 )
591 contents = None
592 else:
593 contents = config.config_text
594
595 elif module.params["diff_against"] == "startup":
596 if not startup_config:
597 output = execute_show_commands(module, "show startup-config")
598 contents = output[0]
599 else:
600 contents = startup_config.config_text
601
602 elif module.params["diff_against"] == "intended":
603 contents = module.params["intended_config"]
604
605 if contents is not None:
606 base_config = NetworkConfig(
607 indent=2,
608 contents=contents,
609 ignore_lines=diff_ignore_lines,
610 )
611
612 if running_config.sha1 != base_config.sha1:
613 before = ""
614 after = ""
615 if module.params["diff_against"] == "intended":
616 before = running_config
617 after = base_config
618 elif module.params["diff_against"] in ("startup", "running"):
619 before = base_config
620 after = running_config
621
622 result.update(
623 {
624 "changed": True,
625 "diff": {"before": str(before), "after": str(after)},
626 },
627 )
628
629 if result.get("changed") and any(
630 (module.params["src"], module.params["lines"], module.params["content"]),
631 ):
632 msg = (
633 "To ensure idempotency and correct diff the input configuration lines should be"
634 " similar to how they appear if present in"
635 " the running configuration on device"
636 )
637 if module.params["src"] or module.params["content"]:
638 msg += " including the indentation"
639 if "warnings" in result:
640 result["warnings"].append(msg)
641 else:
642 result["warnings"] = msg
643
644 module.exit_json(**result)
645
646
647 if __name__ == "__main__":
648 main()