Debian Codegraph @

ansible_collections/cisco/ios/plugins/modules/ios_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 DOCUMENTATION = """
24 module: ios_config
25 author: Peter Sprygada (@privateip)
26 short_description: Module to manage configuration sections.
27 description:
28 - Cisco IOS configurations use a simple block indent file syntax for segmenting configuration
29 into sections. This module provides an implementation for working with IOS configuration
30 sections in a deterministic way.
31 version_added: 1.0.0
32 extends_documentation_fragment:
33 - cisco.ios.ios
34 notes:
35 - Tested against Cisco IOSXE Version 17.3 on CML.
36 - Abbreviated commands are NOT idempotent, see
37 U(https://docs.ansible.com/ansible/latest/network/user_guide/faq.html#why-do-the-config-modules-always-return-changed-true-with-abbreviated-commands)
38 - To ensure idempotency and correct diff the configuration lines in the relevant module options should be similar to how they
39 appear if present in the running configuration on device including the indentation.
40 - This module works with connection C(network_cli).
41 See U(https://docs.ansible.com/ansible/latest/network/user_guide/platform_ios.html)
42 - The recommended way to use templated configurations is to render the template using C(ansible.builtin.template)
43 lookup and pass the result to the I(content) parameter. Using I(src) with Jinja2 templates is deprecated.
44 options:
45 lines:
46 description:
47 - The ordered set of commands that should be configured in the section. The commands
48 must be the exact same commands as found in the device running-config to ensure
49 idempotency and correct diff. Be sure to note the configuration command syntax as
50 some commands are automatically modified by the device config parser.
51 type: list
52 elements: raw
53 aliases:
54 - commands
55 suboptions:
56 config_line:
57 description: use to specify config lines when options are required to declare,works sames as lines
58 required: false
59 type: str
60 prompt:
61 description: prompt message to handle while editng configurations on device in configration mode
62 required: false
63 type: str
64 answer:
65 description: answer to send to device in order to handle prompt on device in configration mode
66 required: false
67 type: str
68 parents:
69 description:
70 - The ordered set of parents that uniquely identify the section or hierarchy the
71 commands should be checked against. If the parents argument is omitted, the
72 commands are checked against the set of top level or global commands.
73 type: list
74 elements: str
75 src:
76 description:
77 - Specifies the source path to the file that contains the configuration or configuration
78 template to load. The path to the source file can either be the full path on
79 the Ansible control host or a relative path from the playbook or role root directory. This
80 argument is mutually exclusive with I(lines), I(parents), and I(content). The configuration lines in the
81 source file should be similar to how it will appear if present in the running-configuration
82 of the device including the indentation to ensure idempotency and correct diff.
83 - "NOTE: The I(src) parameter will no longer process Jinja2 templates starting in January 2028.
84 To use templated configurations, render the template using C(ansible.builtin.template) lookup
85 and pass the result to the I(content) parameter instead."
86 type: str
87 content:
88 description:
89 - Configuration content to apply to the device. This should be the rendered configuration
90 text, not a file path.
91 - This is the recommended way to provide templated configurations. Use C(ansible.builtin.template)
92 lookup to render your Jinja2 template and pass the output to this parameter.
93 - This argument is mutually exclusive with I(src), I(lines), and I(parents).
94 - 'Example: C(content: "{{ lookup(''ansible.builtin.template'', ''config.j2'') }}")'
95 type: str
96 before:
97 description:
98 - The ordered set of commands to push on to the command stack if a change needs
99 to be made. This allows the playbook designer the opportunity to perform configuration
100 commands prior to pushing any changes without affecting how the set of commands
101 are matched against the system.
102 type: list
103 elements: str
104 after:
105 description:
106 - The ordered set of commands to append to the end of the command stack if a change
107 needs to be made. Just like with I(before) this allows the playbook designer
108 to append a set of commands to be executed after the command set.
109 type: list
110 elements: str
111 match:
112 description:
113 - Instructs the module on the way to perform the matching of the set of commands
114 against the current device config. If match is set to I(line), commands are
115 matched line by line. If match is set to I(strict), command lines are matched
116 with respect to position. If match is set to I(exact), command lines must be
117 an equal match. Finally, if match is set to I(none), the module will not attempt
118 to compare the source configuration with the running configuration on the remote
119 device.
120 choices:
121 - line
122 - strict
123 - exact
124 - none
125 type: str
126 default: line
127 replace:
128 description:
129 - Instructs the module on the way to perform the configuration on the device.
130 If the replace argument is set to I(line) then the modified lines are pushed
131 to the device in configuration mode. If the replace argument is set to I(block)
132 then the entire command block is pushed to the device in configuration mode
133 if any line is not correct.
134 default: line
135 choices:
136 - line
137 - block
138 type: str
139 multiline_delimiter:
140 description:
141 - This argument is used when pushing a multiline configuration element to the
142 IOS device. It specifies the character to use as the delimiting character. This
143 only applies to the configuration action.
144 default: "@"
145 type: str
146 backup:
147 description:
148 - This argument will cause the module to create a full backup of the current C(running-config)
149 from the remote device before any changes are made. If the C(backup_options)
150 value is not given, the backup file is written to the C(backup) folder in the
151 playbook root directory or role root directory, if playbook is part of an ansible
152 role. If the directory does not exist, it is created.
153 type: bool
154 default: false
155 running_config:
156 description:
157 - The module, by default, will connect to the remote device and retrieve the current
158 running-config to use as a base for comparing against the contents of source.
159 There are times when it is not desirable to have the task get the current running-config
160 for every task in a playbook. The I(running_config) argument allows the implementer
161 to pass in the configuration to use as the base config for comparison.
162 The configuration lines for this option should be similar to how it will appear if present
163 in the running-configuration of the device including the indentation to ensure idempotency
164 and correct diff.
165 type: str
166 aliases:
167 - config
168 defaults:
169 description:
170 - This argument specifies whether or not to collect all defaults when getting
171 the remote device running config. When enabled, the module will get the current
172 config by issuing the command C(show running-config all).
173 type: bool
174 default: false
175 save_when:
176 description:
177 - When changes are made to the device running-configuration, the changes are not
178 copied to non-volatile storage by default. Using this argument will change
179 that before. If the argument is set to I(always), then the running-config will
180 always be copied to the startup-config and the I(modified) flag will always
181 be set to True. If the argument is set to I(modified), then the running-config
182 will only be copied to the startup-config if it has changed since the last save
183 to startup-config. If the argument is set to I(never), the running-config will
184 never be copied to the startup-config. If the argument is set to I(changed),
185 then the running-config will only be copied to the startup-config if the task
186 has made a change. I(changed) was added in Ansible 2.5.
187 default: never
188 choices:
189 - always
190 - never
191 - modified
192 - changed
193 type: str
194 diff_against:
195 description:
196 - When using the C(ansible-playbook --diff) command line argument the module can
197 generate diffs against different sources.
198 - When this option is configure as I(startup), the module will return the diff
199 of the running-config against the startup-config.
200 - When this option is configured as I(intended), the module will return the diff
201 of the running-config against the configuration provided in the C(intended_config)
202 argument.
203 - When this option is configured as I(running), the module will return the before
204 and after diff of the running-config with respect to any changes made to the
205 device configuration.
206 type: str
207 choices:
208 - running
209 - startup
210 - intended
211 diff_ignore_lines:
212 description:
213 - Use this argument to specify one or more lines that should be ignored during
214 the diff. This is used for lines in the configuration that are automatically
215 updated by the system. This argument takes a list of regular expressions or
216 exact line matches.
217 type: list
218 elements: str
219 intended_config:
220 description:
221 - The C(intended_config) provides the master configuration that the node should
222 conform to and is used to check the final running-config against. This argument
223 will not modify any settings on the remote device and is strictly used to check
224 the compliance of the current device's configuration against. When specifying
225 this argument, the task should also modify the C(diff_against) value and set
226 it to I(intended). The configuration lines for this value should be similar to how it
227 will appear if present in the running-configuration of the device including the indentation
228 to ensure correct diff.
229 type: str
230 backup_options:
231 description:
232 - This is a dict object containing configurable options related to backup file
233 path. The value of this option is read only when C(backup) is set to I(yes),
234 if C(backup) is set to I(no) this option will be silently ignored.
235 suboptions:
236 filename:
237 description:
238 - The filename to be used to store the backup configuration. If the filename
239 is not given it will be generated based on the hostname, current time and
240 date in format defined by <hostname>_config.<current-date>@<current-time>
241 type: str
242 dir_path:
243 description:
244 - This option provides the path ending with directory name in which the backup
245 configuration file will be stored. If the directory does not exist it will
246 be first created and the filename is either the value of C(filename) or
247 default filename as described in C(filename) options description. If the
248 path value is not given in that case a I(backup) directory will be created
249 in the current working directory and backup configuration will be copied
250 in C(filename) within I(backup) directory.
251 type: path
252 type: dict
253 """
254
255 EXAMPLES = """
256 - name: Configure top level configuration
257 cisco.ios.ios_config:
258 lines: hostname {{ inventory_hostname }}
259
260 - name: Configure interface settings
261 cisco.ios.ios_config:
262 lines:
263 - description test interface
264 - ip address 172.31.1.1 255.255.255.0
265 parents: interface Ethernet1
266
267 - name: Configure ip helpers on multiple interfaces
268 cisco.ios.ios_config:
269 lines:
270 - ip helper-address 172.26.1.10
271 - ip helper-address 172.26.3.8
272 parents: "{{ item }}"
273 with_items:
274 - interface Ethernet1
275 - interface Ethernet2
276 - interface GigabitEthernet1
277
278 - name: Configure policer in Scavenger class
279 cisco.ios.ios_config:
280 lines:
281 - conform-action transmit
282 - exceed-action drop
283 parents:
284 - policy-map Foo
285 - class Scavenger
286 - police cir 64000
287
288 - name: Load new acl into device
289 cisco.ios.ios_config:
290 lines:
291 - 10 permit ip host 192.0.2.1 any log
292 - 20 permit ip host 192.0.2.2 any log
293 - 30 permit ip host 192.0.2.3 any log
294 - 40 permit ip host 192.0.2.4 any log
295 - 50 permit ip host 192.0.2.5 any log
296 parents: ip access-list extended test
297 before: no ip access-list extended test
298 match: exact
299
300 - name: Check the running-config against master config
301 cisco.ios.ios_config:
302 diff_against: intended
303 intended_config: "{{ lookup('file', 'master.cfg') }}"
304
305 - name: Check the startup-config against the running-config
306 cisco.ios.ios_config:
307 diff_against: startup
308 diff_ignore_lines:
309 - ntp clock .*
310
311 - name: Save running to startup when modified
312 cisco.ios.ios_config:
313 save_when: modified
314
315 - name: For idempotency, use full-form commands
316 cisco.ios.ios_config:
317 lines:
318 # - shut
319 - shutdown
320 # parents: int gig1/0/11
321 parents: interface GigabitEthernet1/0/11
322
323 # Set boot image based on comparison to a group_var (version) and the version
324 # that is returned from the `ios_facts` module
325 - name: Setting boot image
326 cisco.ios.ios_config:
327 lines:
328 - no boot system
329 - boot system flash bootflash:{{new_image}}
330 host: "{{ inventory_hostname }}"
331 when: ansible_net_version != version
332
333 - name: Render a Jinja2 template onto an IOS device (DEPRECATED - use content parameter)
334 cisco.ios.ios_config:
335 backup: true
336 src: ios_template.j2
337
338 - name: Configurable backup path
339 cisco.ios.ios_config:
340 src: ios_template.j2
341 backup: true
342 backup_options:
343 filename: backup.cfg
344 dir_path: /home/user
345
346 - name: Apply templated configuration using content parameter (RECOMMENDED)
347 cisco.ios.ios_config:
348 content: "{{ lookup('ansible.builtin.template', 'ios_template.j2') }}"
349 backup: true
350
351 - name: Apply templated configuration with backup options (RECOMMENDED)
352 cisco.ios.ios_config:
353 content: "{{ lookup('ansible.builtin.template', 'ios_template.j2') }}"
354 backup: true
355 backup_options:
356 filename: backup.cfg
357 dir_path: /home/user
358
359 - name: Load configuration from pre-rendered template
360 cisco.ios.ios_config:
361 content: |
362 interface GigabitEthernet0/1
363 description Uplink to Core
364 ip address 10.1.1.1 255.255.255.0
365 no shutdown
366
367 - name: Configure Access Session Attributes while handlening prompt
368 cisco.ios.ios_config:
369 lines:
370 - config_line: access-session authentication attributes filter-spec include list test_filter
371 - config_line: access-session accounting attributes filter-spec include list test_filter
372 prompt: "Do you wish to continue? [yes]:"
373 answer: "yes"
374 save_when: "changed"
375
376 # Task Output :
377 # --------
378 #
379 # banners: {}
380 # commands:
381 # - access-session authentication attributes filter-spec include list mylist
382 # - access-session accounting attributes filter-spec include list mylist
383 # invocation:
384 # module_args:
385 # after: null
386 # backup: false
387 # backup_options: null
388 # before: null
389 # defaults: false
390 # diff_against: null
391 # diff_ignore_lines: null
392 # intended_config: null
393 # lines:
394 # - config_line: access-session authentication attributes filter-spec include list mylist
395 # - answer: "yes"
396 # config_line: access-session accounting attributes filter-spec include list mylist
397 # prompt: "Do you wish to continue? [yes]:"
398 # match: line
399 # multiline_delimiter: '@'
400 # parents: null
401 # replace: line
402 # running_config: null
403 # save_when: changed
404 # src: null
405 # updates:
406 # - access-session authentication attributes filter-spec include list mylist
407 # - access-session accounting attributes filter-spec include list mylist
408
409
410 # Example ios_template.j2
411 # ip access-list extended test
412 # permit ip host 192.0.2.1 any log
413 # permit ip host 192.0.2.2 any log
414 # permit ip host 192.0.2.3 any log
415 # permit ip host 192.0.2.4 any log
416 """
417
418 RETURN = """
419 updates:
420 description: The set of commands that will be pushed to the remote device
421 returned: always
422 type: list
423 sample: ['hostname foo', 'router ospf 1', 'router-id 192.0.2.1']
424 commands:
425 description: The set of commands that will be pushed to the remote device
426 returned: always
427 type: list
428 sample: ['hostname foo', 'router ospf 1', 'router-id 192.0.2.1']
429 backup_path:
430 description: The full path to the backup file
431 returned: when backup is yes
432 type: str
433 sample: /playbooks/ansible/backup/ios_config.2016-07-16@22:28:34
434 filename:
435 description: The name of the backup file
436 returned: when backup is yes and filename is not specified in backup options
437 type: str
438 sample: ios_config.2016-07-16@22:28:34
439 shortname:
440 description: The full path to the backup file excluding the timestamp
441 returned: when backup is yes and filename is not specified in backup options
442 type: str
443 sample: /playbooks/ansible/backup/ios_config
444 date:
445 description: The date extracted from the backup file name
446 returned: when backup is yes
447 type: str
448 sample: "2016-07-16"
449 time:
450 description: The time extracted from the backup file name
451 returned: when backup is yes
452 type: str
453 sample: "22:28:34"
454 """
455 import json
456 import re
457
458 from ansible.module_utils._text import to_text
459 from ansible.module_utils.basic import AnsibleModule
460 from ansible.module_utils.connection import ConnectionError
461 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import (
462 NetworkConfig,
463 dumps,
464 )
465
466 from ansible_collections.cisco.ios.plugins.module_utils.network.ios.ios import (
467 get_config,
468 get_connection,
469 get_defaults_flag,
470 run_commands,
471 )
472
473
474 def check_args(module, warnings):
475 if module.params["multiline_delimiter"]:
476 if len(module.params["multiline_delimiter"]) != 1:
477 module.fail_json(msg="multiline_delimiter value can only be a single character")
478
479
480 def edit_config_or_macro(connection, commands, config_prompt_lines):
481
482 if commands[0].startswith("macro name"):
483 connection.edit_macro(candidate=commands)
484 else:
485 if config_prompt_lines:
486 connection.edit_config_with_prompt(candidate=config_prompt_lines)
487 else:
488 connection.edit_config(candidate=commands)
489
490
491 INTERFACE_RANGE_RE = re.compile(r"^interface\s+range\s+(.+)$", re.I)
492 INTERFACE_TOKEN_RE = re.compile(r"^([A-Za-z][A-Za-z\d.-]*)\s*(\d.*)$")
493 IDENTIFIER_SUFFIX_RE = re.compile(r"^(.*?)(\d+)$")
494
495
496 def normalize_parents(parents):
497 """Normalize `parents` so split multi-range interface parents are recombined into one command."""
498 parents = parents or []
499 if len(parents) <= 1:
500 return parents
501
502 first_parent = parents[0].strip()
503 first_match = INTERFACE_RANGE_RE.match(first_parent)
504 if not first_match:
505 return parents
506
507 range_tokens = [first_match.group(1).strip()]
508 range_tokens.extend(str(parent).strip() for parent in parents[1:] if str(parent).strip())
509 return ["interface range {0}".format(", ".join(range_tokens))]
510
511
512 def extract_lines(module):
513 """Return the effective list of config lines from `module.params['lines']` (supporting both raw strings and dict items)."""
514 lines = []
515 for item in module.params["lines"] or []:
516 if isinstance(item, dict):
517 if item.get("config_line"):
518 lines.append(item.get("config_line"))
519 else:
520 lines.append(item)
521 return lines
522
523
524 def get_candidate_config(module, parents=None, lines=None):
525 candidate = ""
526 if module.params["content"]:
527
528 candidate = module.params["content"]
529 elif module.params["src"]:
530 candidate = module.params["src"]
531 elif module.params["lines"]:
532 candidate_lines = lines if lines is not None else extract_lines(module)
533 candidate_obj = NetworkConfig(indent=1)
534 candidate_obj.add(
535 lines=candidate_lines,
536 parents=parents if parents is not None else (module.params["parents"] or []),
537 )
538 candidate = dumps(candidate_obj, "raw")
539 return candidate
540
541
542 def _expand_range_identifier(identifier):
543 """Expand a numeric suffix range (e.g. `1/0/1-3`) into identifiers `1/0/1..1/0/3`."""
544 if "-" not in identifier:
545 return [identifier]
546
547 start, end = identifier.split("-", 1)
548 start = start.strip()
549 end = end.strip()
550 if not start or not end:
551 return []
552
553 start_match = IDENTIFIER_SUFFIX_RE.match(start)
554 if not start_match:
555 return []
556 start_prefix, start_num = start_match.groups()
557
558 if "/" in end or "." in end or ":" in end:
559 end_match = IDENTIFIER_SUFFIX_RE.match(end)
560 if not end_match:
561 return []
562 end_prefix, end_num = end_match.groups()
563 else:
564 end_prefix, end_num = start_prefix, end
565
566 if start_prefix != end_prefix:
567 return []
568
569 start_idx = int(start_num)
570 end_idx = int(end_num)
571 if end_idx < start_idx:
572 return []
573
574 return ["{0}{1}".format(start_prefix, idx) for idx in range(start_idx, end_idx + 1)]
575
576
577 def expand_interface_range_parent(parent):
578 """Expand an IOS `interface range ...` parent into individual `interface ...` parents for idempotency checks."""
579 if not parent:
580 return []
581 match = INTERFACE_RANGE_RE.match(parent.strip())
582 if not match:
583 return []
584
585 expanded_interfaces = []
586 for token in match.group(1).split(","):
587 token = token.strip()
588 if not token:
589 continue
590 token_match = INTERFACE_TOKEN_RE.match(token)
591 if not token_match:
592 return []
593 interface_type, identifier = token_match.groups()
594 expanded_identifiers = _expand_range_identifier(identifier.strip())
595 if not expanded_identifiers:
596 return []
597 for expanded_identifier in expanded_identifiers:
598 expanded_interfaces.append(
599 "interface {0}{1}".format(interface_type.strip(), expanded_identifier),
600 )
601
602 return expanded_interfaces
603
604
605 def build_expanded_range_candidate(expanded_parents, lines):
606 """Build a candidate config that applies `lines` under each expanded `interface ...` parent (for idempotency only)."""
607 candidate_obj = NetworkConfig(indent=1)
608 for parent in expanded_parents:
609 candidate_obj.add(lines=lines, parents=[parent])
610 return dumps(candidate_obj, "raw")
611
612
613 def get_running_config(module, current_config=None, flags=None):
614 """Return running-config text from params, cached content, or live device (optionally with `flags`)."""
615 running = module.params["running_config"]
616 if not running:
617 if not module.params["defaults"] and current_config:
618 running = current_config
619 else:
620 running = get_config(module, flags=flags)
621 return running
622
623
624 def save_config(module, result):
625 result["changed"] = True
626 if not module.check_mode:
627 run_commands(module, "copy running-config startup-config\r")
628 else:
629 module.warn(
630 "Skipping command `copy running-config startup-config` due to check_mode. Configuration not copied to non-volatile storage",
631 )
632
633
634 def main():
635 """main entry point for module execution"""
636 backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
637 line_spec = dict(
638 config_line=dict(type="str", required=False),
639 prompt=dict(type="str", required=False),
640 answer=dict(type="str", required=False),
641 )
642 argument_spec = dict(
643 src=dict(type="str"),
644 content=dict(type="str"),
645 lines=dict(aliases=["commands"], type="list", elements="raw", options=line_spec),
646 parents=dict(type="list", elements="str"),
647 before=dict(type="list", elements="str"),
648 after=dict(type="list", elements="str"),
649 match=dict(default="line", choices=["line", "strict", "exact", "none"]),
650 replace=dict(default="line", choices=["line", "block"]),
651 multiline_delimiter=dict(default="@"),
652 running_config=dict(aliases=["config"]),
653 intended_config=dict(),
654 defaults=dict(type="bool", default=False),
655 backup=dict(type="bool", default=False),
656 backup_options=dict(type="dict", options=backup_spec),
657 save_when=dict(choices=["always", "never", "modified", "changed"], default="never"),
658 diff_against=dict(choices=["startup", "intended", "running"]),
659 diff_ignore_lines=dict(type="list", elements="str"),
660 )
661 mutually_exclusive = [
662 ("lines", "src"),
663 ("lines", "content"),
664 ("parents", "src"),
665 ("parents", "content"),
666 ("src", "content"),
667 ]
668 required_if = [
669 ("match", "strict", ["lines", "src", "content"], True),
670 ("match", "exact", ["lines", "src", "content"], True),
671 ("replace", "block", ["lines", "src", "content"], True),
672 ("diff_against", "intended", ["intended_config"]),
673 ]
674 module = AnsibleModule(
675 argument_spec=argument_spec,
676 mutually_exclusive=mutually_exclusive,
677 required_if=required_if,
678 supports_check_mode=True,
679 )
680 result = {"changed": False}
681 warnings = list()
682 check_args(module, warnings)
683 result["warnings"] = warnings
684 diff_ignore_lines = module.params["diff_ignore_lines"]
685 config = None
686 contents = None
687 flags = get_defaults_flag(module) if module.params["defaults"] else []
688 connection = get_connection(module)
689 if module.params["backup"] or module._diff and module.params["diff_against"] == "running":
690 contents = get_config(module, flags=flags)
691 config = NetworkConfig(indent=1, contents=contents)
692 if module.params["backup"]:
693 result["__backup__"] = contents
694 if any((module.params["lines"], module.params["src"], module.params["content"])):
695 match = module.params["match"]
696 replace = module.params["replace"]
697 path = normalize_parents(module.params["parents"])
698 lines = extract_lines(module)
699 candidate = get_candidate_config(module, parents=path, lines=lines)
700 running = get_running_config(module, contents, flags=flags)
701 expanded_range_parents = []
702 use_expanded_idempotency = False
703 if (
704 module.params["lines"]
705 and len(path) == 1
706 and "interface range" in path[0].lower()
707 and match == "line"
708 ):
709 expanded_range_parents = expand_interface_range_parent(path[0])
710 use_expanded_idempotency = bool(expanded_range_parents)
711 diff_candidate = (
712 build_expanded_range_candidate(expanded_range_parents, lines)
713 if use_expanded_idempotency
714 else candidate
715 )
716 try:
717 response = connection.get_diff(
718 candidate=diff_candidate,
719 running=running,
720 diff_match=match,
721 diff_ignore_lines=diff_ignore_lines,
722 path=path,
723 diff_replace=replace,
724 )
725 except ConnectionError as exc:
726 module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))
727 config_diff = response["config_diff"]
728 banner_diff = response["banner_diff"]
729 if use_expanded_idempotency and config_diff:
730 config_diff = candidate
731 if config_diff or banner_diff:
732 commands = [line.strip() for line in config_diff.split("\n") if line.strip()]
733 if module.params["before"]:
734 commands[:0] = module.params["before"]
735 if module.params["after"]:
736 commands.extend(module.params["after"])
737 result["commands"] = commands
738 result["updates"] = commands
739 result["banners"] = banner_diff
740
741 if not module.check_mode:
742 if commands:
743 configs = []
744 if module.params["lines"]:
745 has_prompt_dicts = any(
746 isinstance(item, dict) for item in module.params["lines"]
747 )
748 if has_prompt_dicts:
749 for item in module.params["lines"]:
750 if isinstance(item, dict):
751 for command in commands:
752 if (
753 module.params["before"]
754 and command in module.params["before"]
755 ):
756 configs[:0].append({"config_line": command})
757 if (
758 module.params["parents"]
759 and command in module.params["parents"]
760 ):
761 configs.append({"config_line": command})
762 if command == item.get("config_line"):
763 configs.append(item)
764 if (
765 module.params["after"]
766 and command in module.params["after"]
767 ):
768 configs.append({"config_line": command})
769 edit_config_or_macro(connection, commands, configs)
770 else:
771 edit_config_or_macro(connection, commands, None)
772 elif module.params["src"] or module.params["content"]:
773 edit_config_or_macro(connection, commands, None)
774 if banner_diff:
775 connection.edit_banner(
776 candidate=json.dumps(banner_diff),
777 multiline_delimiter=module.params["multiline_delimiter"],
778 )
779 result["changed"] = True
780 running_config = module.params["running_config"]
781 startup_config = None
782 if module.params["save_when"] == "always":
783 save_config(module, result)
784 elif module.params["save_when"] == "modified":
785 output = run_commands(module, ["show running-config", "show startup-config"])
786 running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines)
787 startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines)
788 if running_config.sha1 != startup_config.sha1:
789 save_config(module, result)
790 elif module.params["save_when"] == "changed" and result["changed"]:
791 save_config(module, result)
792 if module._diff:
793 if not running_config:
794 output = run_commands(module, "show running-config")
795 contents = output[0]
796 else:
797 contents = running_config
798
799 running_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines)
800 if module.params["diff_against"] == "running":
801 if module.check_mode:
802 module.warn("unable to perform diff against running-config due to check mode")
803 contents = None
804 else:
805 contents = config.config_text
806 elif module.params["diff_against"] == "startup":
807 if not startup_config:
808 output = run_commands(module, "show startup-config")
809 contents = output[0]
810 else:
811 contents = startup_config.config_text
812 elif module.params["diff_against"] == "intended":
813 contents = module.params["intended_config"]
814 if contents is not None:
815 base_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines)
816 if running_config.sha1 != base_config.sha1:
817 before, after = "", ""
818 if module.params["diff_against"] == "intended":
819 before = running_config
820 after = base_config
821 elif module.params["diff_against"] in ("startup", "running"):
822 before = base_config
823 after = running_config
824 result.update(
825 {"changed": True, "diff": {"before": str(before), "after": str(after)}},
826 )
827
828 if result.get("changed") and any(
829 (module.params["src"], module.params["lines"], module.params["content"]),
830 ):
831 msg = (
832 "To ensure idempotency and correct diff the input configuration lines should be"
833 " similar to how they appear if present in"
834 " the running configuration on device"
835 )
836 if module.params["src"] or module.params["content"]:
837 msg += " including the indentation"
838 if "warnings" in result:
839 result["warnings"].append(msg)
840 else:
841 result["warnings"] = msg
842
843 module.exit_json(**result)
844
845
846 if __name__ == "__main__":
847 main()