| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright: Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
|
| 12 |
DOCUMENTATION = """ |
| 13 |
module: iosxr_config |
| 14 |
author: Ricardo Carrillo Cruz (@rcarrillocruz) |
| 15 |
short_description: Module to manage configuration sections. |
| 16 |
description: |
| 17 |
- Cisco IOS XR configurations use a simple block indent file syntax for segmenting |
| 18 |
configuration into sections. This module provides an implementation for working |
| 19 |
with IOS XR configuration sections in a deterministic way. |
| 20 |
version_added: 1.0.0 |
| 21 |
extends_documentation_fragment: |
| 22 |
- cisco.iosxr.iosxr |
| 23 |
notes: |
| 24 |
- This module works with connection C(network_cli). |
| 25 |
See U(https://docs.ansible.com/ansible/latest/network/user_guide/platform_iosxr.html) |
| 26 |
- This module does not support C(netconf) connection |
| 27 |
- Abbreviated commands are NOT idempotent, see |
| 28 |
U(https://docs.ansible.com/ansible/latest/network/user_guide/faq.html#why-do-the-config-modules-always-return-changed-true-with-abbreviated-commands) |
| 29 |
- Avoid service disrupting changes (viz. Management IP) from config replace. |
| 30 |
- Do not use C(end) in the replace config file. |
| 31 |
- To ensure idempotency and correct diff the configuration lines in the relevant module options should be similar to how they |
| 32 |
appear if present in the running configuration on device including the indentation. |
| 33 |
options: |
| 34 |
lines: |
| 35 |
description: |
| 36 |
- The ordered set of commands that should be configured in the section. The commands |
| 37 |
must be the exact same commands as found in the device running-config as found in the |
| 38 |
device running-config to ensure idempotency and correct diff. Be sure to note the |
| 39 |
configuration command syntax as some commands are automatically modified by the |
| 40 |
device config parser. |
| 41 |
type: list |
| 42 |
elements: str |
| 43 |
aliases: |
| 44 |
- commands |
| 45 |
parents: |
| 46 |
description: |
| 47 |
- The ordered set of parents that uniquely identify the section or hierarchy the |
| 48 |
commands should be checked against. If the parents argument is omitted, the |
| 49 |
commands are checked against the set of top level or global commands. |
| 50 |
type: list |
| 51 |
elements: str |
| 52 |
src: |
| 53 |
description: |
| 54 |
- Specifies the source path to the file that contains the configuration or configuration |
| 55 |
template to load. The path to the source file can either be the full path on |
| 56 |
the Ansible control host or a relative path from the playbook or role root directory. This |
| 57 |
argument is mutually exclusive with I(lines), I(parents), and I(content). The configuration lines in the |
| 58 |
source file should be similar to how it will appear if present in the running-configuration |
| 59 |
of the device to ensure idempotency and correct diff. |
| 60 |
- "NOTE: The I(src) parameter will no longer process Jinja2 templates starting in January 2028. |
| 61 |
To use templated configurations, render the template using C(ansible.builtin.template) lookup |
| 62 |
and pass the result to the I(content) parameter instead." |
| 63 |
type: path |
| 64 |
content: |
| 65 |
description: |
| 66 |
- Configuration content to apply to the device. This should be the rendered configuration |
| 67 |
text, not a file path. |
| 68 |
- This is the recommended way to provide templated configurations. Use C(ansible.builtin.template) |
| 69 |
lookup to render your Jinja2 template and pass the output to this parameter. |
| 70 |
- This argument is mutually exclusive with I(src), I(lines), and I(parents). |
| 71 |
- 'Example: C(content: "{{ lookup(''ansible.builtin.template'', ''config.j2'') }}")' |
| 72 |
type: str |
| 73 |
before: |
| 74 |
description: |
| 75 |
- The ordered set of commands to push on to the command stack if a change needs |
| 76 |
to be made. This allows the playbook designer the opportunity to perform configuration |
| 77 |
commands prior to pushing any changes without affecting how the set of commands |
| 78 |
are matched against the system. |
| 79 |
type: list |
| 80 |
elements: str |
| 81 |
after: |
| 82 |
description: |
| 83 |
- The ordered set of commands to append to the end of the command stack if a change |
| 84 |
needs to be made. Just like with I(before) this allows the playbook designer |
| 85 |
to append a set of commands to be executed after the command set. |
| 86 |
type: list |
| 87 |
elements: str |
| 88 |
match: |
| 89 |
description: |
| 90 |
- Instructs the module on the way to perform the matching of the set of commands |
| 91 |
against the current device config. If match is set to I(line), commands are |
| 92 |
matched line by line. If match is set to I(strict), command lines are matched |
| 93 |
with respect to position. If match is set to I(exact), command lines must be |
| 94 |
an equal match. Finally, if match is set to I(none), the module will not attempt |
| 95 |
to compare the source configuration with the running configuration on the remote |
| 96 |
device. |
| 97 |
type: str |
| 98 |
default: line |
| 99 |
choices: |
| 100 |
- line |
| 101 |
- strict |
| 102 |
- exact |
| 103 |
- none |
| 104 |
replace: |
| 105 |
description: |
| 106 |
- Instructs the module on the way to perform the configuration on the device. If |
| 107 |
the replace argument is set to I(line) then the modified lines are pushed to |
| 108 |
the device in configuration mode. If the replace argument is set to I(block) |
| 109 |
then the entire command block is pushed to the device in configuration mode |
| 110 |
if any line is not correct. |
| 111 |
type: str |
| 112 |
default: line |
| 113 |
choices: |
| 114 |
- line |
| 115 |
- block |
| 116 |
- config |
| 117 |
force: |
| 118 |
description: |
| 119 |
- The force argument instructs the module to not consider the current devices |
| 120 |
running-config. When set to true, this will cause the module to push the contents |
| 121 |
of I(src) into the device without first checking if already configured. |
| 122 |
- Note this argument should be considered deprecated. To achieve the equivalent, |
| 123 |
set the C(match=none) which is idempotent. This argument will be removed in |
| 124 |
a future release. |
| 125 |
type: bool |
| 126 |
default: no |
| 127 |
config: |
| 128 |
description: |
| 129 |
- The module, by default, will connect to the remote device and retrieve the current |
| 130 |
running-config to use as a base for comparing against the contents of source. There |
| 131 |
are times when it is not desirable to have the task get the current running-config |
| 132 |
for every task in a playbook. The I(config) argument allows the implementer |
| 133 |
to pass in the configuration to use as the base config for comparison. |
| 134 |
The configuration lines for this option should be similar to how it will appear if present |
| 135 |
in the running-configuration of the device to ensure idempotency and correct diff. |
| 136 |
type: str |
| 137 |
backup: |
| 138 |
description: |
| 139 |
- This argument will cause the module to create a full backup of the current C(running-config) |
| 140 |
from the remote device before any changes are made. If the C(backup_options) |
| 141 |
value is not given, the backup file is written to the C(backup) folder in the |
| 142 |
playbook root directory or role root directory, if playbook is part of an ansible |
| 143 |
role. If the directory does not exist, it is created. |
| 144 |
type: bool |
| 145 |
default: no |
| 146 |
comment: |
| 147 |
description: |
| 148 |
- Allows a commit description to be specified to be included when the configuration |
| 149 |
is committed. If the configuration is not changed or committed, this argument |
| 150 |
is ignored. |
| 151 |
type: str |
| 152 |
default: configured by iosxr_config |
| 153 |
admin: |
| 154 |
description: |
| 155 |
- Enters into administration configuration mode for making config changes to the |
| 156 |
device. |
| 157 |
type: bool |
| 158 |
default: no |
| 159 |
label: |
| 160 |
description: |
| 161 |
- Allows a commit label to be specified to be included when the configuration |
| 162 |
is committed. A valid label must begin with an alphabet and not exceed 30 characters, |
| 163 |
only alphabets, digits, hyphens and underscores are allowed. If the configuration |
| 164 |
is not changed or committed, this argument is ignored. |
| 165 |
type: str |
| 166 |
backup_options: |
| 167 |
description: |
| 168 |
- This is a dict object containing configurable options related to backup file |
| 169 |
path. The value of this option is read only when C(backup) is set to I(yes), |
| 170 |
if C(backup) is set to I(no) this option will be silently ignored. |
| 171 |
suboptions: |
| 172 |
filename: |
| 173 |
description: |
| 174 |
- The filename to be used to store the backup configuration. If the filename |
| 175 |
is not given it will be generated based on the hostname, current time and |
| 176 |
date in format defined by <hostname>_config.<current-date>@<current-time> |
| 177 |
type: str |
| 178 |
dir_path: |
| 179 |
description: |
| 180 |
- This option provides the path ending with directory name in which the backup |
| 181 |
configuration file will be stored. If the directory does not exist it will |
| 182 |
be first created and the filename is either the value of C(filename) or |
| 183 |
default filename as described in C(filename) options description. If the |
| 184 |
path value is not given in that case a I(backup) directory will be created |
| 185 |
in the current working directory and backup configuration will be copied |
| 186 |
in C(filename) within I(backup) directory. |
| 187 |
type: path |
| 188 |
type: dict |
| 189 |
exclusive: |
| 190 |
description: |
| 191 |
- Enters into exclusive configuration mode that locks out all users from committing |
| 192 |
configuration changes until the exclusive session ends. |
| 193 |
type: bool |
| 194 |
default: false |
| 195 |
disable_default_comment: |
| 196 |
description: |
| 197 |
- disable default comment when set to True. |
| 198 |
type: bool |
| 199 |
default: false |
| 200 |
""" |
| 201 |
|
| 202 |
EXAMPLES = """ |
| 203 |
- name: configure top level configuration |
| 204 |
cisco.iosxr.iosxr_config: |
| 205 |
lines: hostname {{ inventory_hostname }} |
| 206 |
|
| 207 |
- name: configure interface settings |
| 208 |
cisco.iosxr.iosxr_config: |
| 209 |
lines: |
| 210 |
- description test interface |
| 211 |
- ip address 172.31.1.1 255.255.255.0 |
| 212 |
parents: interface GigabitEthernet0/0/0/0 |
| 213 |
|
| 214 |
- name: load a config from disk and replace the current config |
| 215 |
cisco.iosxr.iosxr_config: |
| 216 |
src: config.cfg |
| 217 |
replace: config |
| 218 |
backup: 'yes' |
| 219 |
|
| 220 |
- name: Render a Jinja2 template onto an IOS-XR device (DEPRECATED - use content parameter) |
| 221 |
cisco.iosxr.iosxr_config: |
| 222 |
backup: true |
| 223 |
src: iosxr_template.j2 |
| 224 |
|
| 225 |
- name: Apply templated configuration using content parameter (RECOMMENDED) |
| 226 |
cisco.iosxr.iosxr_config: |
| 227 |
content: "{{ lookup('ansible.builtin.template', 'iosxr_template.j2') }}" |
| 228 |
backup: true |
| 229 |
|
| 230 |
- name: Apply templated configuration with backup options (RECOMMENDED) |
| 231 |
cisco.iosxr.iosxr_config: |
| 232 |
content: "{{ lookup('ansible.builtin.template', 'iosxr_template.j2') }}" |
| 233 |
backup: true |
| 234 |
backup_options: |
| 235 |
filename: backup.cfg |
| 236 |
dir_path: /home/user |
| 237 |
|
| 238 |
- name: Load configuration from pre-rendered template |
| 239 |
cisco.iosxr.iosxr_config: |
| 240 |
content: | |
| 241 |
interface GigabitEthernet0/0/0/1 |
| 242 |
description Uplink to Core |
| 243 |
ipv4 address 10.1.1.1 255.255.255.0 |
| 244 |
no shutdown |
| 245 |
|
| 246 |
- name: 'for idempotency, use full-form commands' |
| 247 |
cisco.iosxr.iosxr_config: |
| 248 |
lines: |
| 249 |
- shutdown |
| 250 |
parents: interface GigabitEthernet0/0/0/1 |
| 251 |
|
| 252 |
- name: configurable backup path |
| 253 |
cisco.iosxr.iosxr_config: |
| 254 |
src: config.cfg |
| 255 |
backup: true |
| 256 |
backup_options: |
| 257 |
filename: backup.cfg |
| 258 |
dir_path: /home/user |
| 259 |
""" |
| 260 |
|
| 261 |
RETURN = """ |
| 262 |
commands: |
| 263 |
description: The set of commands that will be pushed to the remote device |
| 264 |
returned: If there are commands to run against the host |
| 265 |
type: list |
| 266 |
sample: ['hostname foo', 'router ospf 1', 'router-id 1.1.1.1'] |
| 267 |
updates: |
| 268 |
description: The set of commands that will be pushed to the remote device |
| 269 |
returned: If there are commands to run against the host |
| 270 |
type: list |
| 271 |
sample: ['hostname foo', 'router ospf 1', 'router-id 1.1.1.1'] |
| 272 |
backup_path: |
| 273 |
description: The full path to the backup file |
| 274 |
returned: when backup is yes |
| 275 |
type: str |
| 276 |
sample: /playbooks/ansible/backup/iosxr01_config.2016-07-16@22:28:34 |
| 277 |
filename: |
| 278 |
description: The name of the backup file |
| 279 |
returned: when backup is yes and filename is not specified in backup options |
| 280 |
type: str |
| 281 |
sample: iosxr01_config.2016-07-16@22:28:34 |
| 282 |
shortname: |
| 283 |
description: The full path to the backup file excluding the timestamp |
| 284 |
returned: when backup is yes and filename is not specified in backup options |
| 285 |
type: str |
| 286 |
sample: /playbooks/ansible/backup/iosxr01_config |
| 287 |
date: |
| 288 |
description: The date extracted from the backup file name |
| 289 |
returned: when backup is yes |
| 290 |
type: str |
| 291 |
sample: "2016-07-16" |
| 292 |
time: |
| 293 |
description: The time extracted from the backup file name |
| 294 |
returned: when backup is yes |
| 295 |
type: str |
| 296 |
sample: "22:28:34" |
| 297 |
""" |
| 298 |
import os |
| 299 |
import re |
| 300 |
import tempfile |
| 301 |
|
| 302 |
from ansible.module_utils._text import to_bytes, to_text |
| 303 |
from ansible.module_utils.basic import AnsibleModule |
| 304 |
from ansible.module_utils.connection import ConnectionError |
| 305 |
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import ( |
| 306 |
NetworkConfig, |
| 307 |
dumps, |
| 308 |
) |
| 309 |
|
| 310 |
from ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr import ( |
| 311 |
copy_file, |
| 312 |
get_config, |
| 313 |
get_connection, |
| 314 |
load_config, |
| 315 |
) |
| 316 |
|
| 317 |
|
| 318 |
DEFAULT_COMMIT_COMMENT = "configured by iosxr_config" |
| 319 |
|
| 320 |
|
| 321 |
def copy_file_to_node(module): |
| 322 |
"""Copy config file to IOS-XR node. We use SFTP because older IOS-XR versions don't handle SCP very well.""" |
| 323 |
file = tempfile.NamedTemporaryFile("wb", delete=False) |
| 324 |
src = os.path.realpath(file.name) |
| 325 |
file.write(to_bytes(module.params["src"], errors="surrogate_or_strict")) |
| 326 |
file.close() |
| 327 |
|
| 328 |
dst = "/harddisk:/ansible_config.txt" |
| 329 |
copy_file(module, src, dst, "sftp") |
| 330 |
|
| 331 |
os.remove(src) |
| 332 |
|
| 333 |
return True |
| 334 |
|
| 335 |
|
| 336 |
def check_args(module, warnings): |
| 337 |
if module.params["comment"]: |
| 338 |
if len(module.params["comment"]) > 60: |
| 339 |
module.fail_json(msg="comment argument cannot be more than 60 characters") |
| 340 |
if module.params["label"]: |
| 341 |
label = module.params["label"] |
| 342 |
if len(label) > 30: |
| 343 |
module.fail_json(msg="label argument cannot be more than 30 characters") |
| 344 |
if not label[0].isalpha(): |
| 345 |
module.fail_json(msg="label argument must begin with an alphabet") |
| 346 |
valid_chars = re.match(r"[\w-]*$", label) |
| 347 |
if not valid_chars: |
| 348 |
module.fail_json( |
| 349 |
msg="label argument must only contain alphabets," |
| 350 |
+ "digits, underscores or hyphens", |
| 351 |
) |
| 352 |
if module.params["force"]: |
| 353 |
warnings.append( |
| 354 |
"The force argument is deprecated, please use " |
| 355 |
"match=none instead. This argument will be " |
| 356 |
"removed in the future", |
| 357 |
) |
| 358 |
|
| 359 |
|
| 360 |
def get_running_config(module): |
| 361 |
contents = module.params["config"] |
| 362 |
if not contents: |
| 363 |
contents = get_config(module) |
| 364 |
return contents |
| 365 |
|
| 366 |
|
| 367 |
def get_candidate(module): |
| 368 |
candidate = "" |
| 369 |
if module.params["src"]: |
| 370 |
candidate = module.params["src"] |
| 371 |
elif module.params["content"]: |
| 372 |
candidate = module.params["content"] |
| 373 |
elif module.params["lines"]: |
| 374 |
candidate_obj = NetworkConfig(indent=1, comment_tokens=["!"]) |
| 375 |
parents = module.params["parents"] or list() |
| 376 |
candidate_obj.add(module.params["lines"], parents=parents) |
| 377 |
candidate = dumps(candidate_obj, "raw") |
| 378 |
return candidate |
| 379 |
|
| 380 |
|
| 381 |
def run(module, result): |
| 382 |
match = module.params["match"] |
| 383 |
replace = module.params["replace"] |
| 384 |
replace_config = replace == "config" |
| 385 |
path = module.params["parents"] |
| 386 |
comment = module.params["comment"] |
| 387 |
admin = module.params["admin"] |
| 388 |
exclusive = module.params["exclusive"] |
| 389 |
check_mode = module.check_mode |
| 390 |
label = module.params["label"] |
| 391 |
candidate_config = get_candidate(module) |
| 392 |
running_config = get_running_config(module) |
| 393 |
|
| 394 |
commands = None |
| 395 |
replace_file_path = None |
| 396 |
connection = get_connection(module) |
| 397 |
try: |
| 398 |
response = connection.get_diff( |
| 399 |
candidate=candidate_config, |
| 400 |
running=running_config, |
| 401 |
diff_match=match, |
| 402 |
path=path, |
| 403 |
diff_replace=replace, |
| 404 |
) |
| 405 |
except ConnectionError as exc: |
| 406 |
module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) |
| 407 |
|
| 408 |
config_diff = response.get("config_diff") |
| 409 |
|
| 410 |
if replace_config: |
| 411 |
running_base_diff_resp = connection.get_diff( |
| 412 |
candidate=running_config, |
| 413 |
running=candidate_config, |
| 414 |
diff_match=match, |
| 415 |
path=path, |
| 416 |
diff_replace=replace, |
| 417 |
) |
| 418 |
if config_diff or running_base_diff_resp["config_diff"]: |
| 419 |
ret = copy_file_to_node(module) |
| 420 |
if not ret: |
| 421 |
module.fail_json(msg="Copy of config file to the node failed") |
| 422 |
|
| 423 |
commands = ["load harddisk:/ansible_config.txt"] |
| 424 |
replace_file_path = "harddisk:/ansible_config.txt" |
| 425 |
|
| 426 |
if config_diff or commands: |
| 427 |
if not replace_config: |
| 428 |
commands = config_diff.split("\n") |
| 429 |
|
| 430 |
if any((module.params["lines"], module.params["src"], module.params["content"])): |
| 431 |
if module.params["before"]: |
| 432 |
commands[:0] = module.params["before"] |
| 433 |
|
| 434 |
if module.params["after"]: |
| 435 |
commands.extend(module.params["after"]) |
| 436 |
|
| 437 |
result["commands"] = commands |
| 438 |
result["updates"] = commands |
| 439 |
|
| 440 |
commit = not check_mode |
| 441 |
diff = load_config( |
| 442 |
module, |
| 443 |
commands, |
| 444 |
commit=commit, |
| 445 |
replace=replace_file_path, |
| 446 |
comment=comment, |
| 447 |
admin=admin, |
| 448 |
exclusive=exclusive, |
| 449 |
label=label, |
| 450 |
) |
| 451 |
if diff: |
| 452 |
result["diff"] = dict(prepared=diff) |
| 453 |
|
| 454 |
result["changed"] = True |
| 455 |
|
| 456 |
|
| 457 |
def main(): |
| 458 |
"""main entry point for module execution""" |
| 459 |
backup_spec = dict(filename=dict(), dir_path=dict(type="path")) |
| 460 |
argument_spec = dict( |
| 461 |
src=dict(type="path"), |
| 462 |
content=dict(type="str"), |
| 463 |
lines=dict(aliases=["commands"], type="list", elements="str"), |
| 464 |
parents=dict(type="list", elements="str"), |
| 465 |
before=dict(type="list", elements="str"), |
| 466 |
after=dict(type="list", elements="str"), |
| 467 |
match=dict(default="line", choices=["line", "strict", "exact", "none"]), |
| 468 |
replace=dict(default="line", choices=["line", "block", "config"]), |
| 469 |
# this argument is deprecated in favor of setting match: none |
| 470 |
# it will be removed in a future version |
| 471 |
force=dict(default=False, type="bool"), |
| 472 |
config=dict(), |
| 473 |
backup=dict(type="bool", default=False), |
| 474 |
backup_options=dict(type="dict", options=backup_spec), |
| 475 |
comment=dict(default=DEFAULT_COMMIT_COMMENT), |
| 476 |
admin=dict(type="bool", default=False), |
| 477 |
disable_default_comment=dict(type="bool", default=False), |
| 478 |
exclusive=dict(type="bool", default=False), |
| 479 |
label=dict(), |
| 480 |
) |
| 481 |
|
| 482 |
mutually_exclusive = [("lines", "src", "content"), ("parents", "src", "content")] |
| 483 |
|
| 484 |
required_if = [ |
| 485 |
("match", "strict", ["lines", "src", "content"], True), |
| 486 |
("match", "exact", ["lines", "src", "content"], True), |
| 487 |
("replace", "block", ["lines", "src", "content"], True), |
| 488 |
("replace", "config", ["src"]), |
| 489 |
] |
| 490 |
|
| 491 |
module = AnsibleModule( |
| 492 |
argument_spec=argument_spec, |
| 493 |
mutually_exclusive=mutually_exclusive, |
| 494 |
required_if=required_if, |
| 495 |
supports_check_mode=True, |
| 496 |
) |
| 497 |
|
| 498 |
if module.params["force"] is True: |
| 499 |
module.params["match"] = "none" |
| 500 |
if ( |
| 501 |
module.params["disable_default_comment"] is True |
| 502 |
and module.params["comment"] == DEFAULT_COMMIT_COMMENT |
| 503 |
): |
| 504 |
module.params["comment"] = None |
| 505 |
warnings = list() |
| 506 |
|
| 507 |
check_args(module, warnings) |
| 508 |
|
| 509 |
result = dict(changed=False, warnings=warnings) |
| 510 |
|
| 511 |
if module.params["backup"]: |
| 512 |
result["__backup__"] = get_config(module) |
| 513 |
|
| 514 |
if any((module.params["src"], module.params["lines"], module.params["content"])): |
| 515 |
run(module, result) |
| 516 |
|
| 517 |
if result.get("changed") and any( |
| 518 |
(module.params["src"], module.params["lines"], module.params["content"]), |
| 519 |
): |
| 520 |
msg = ( |
| 521 |
"To ensure idempotency and correct diff the input configuration lines should be" |
| 522 |
" similar to how they appear if present in" |
| 523 |
" the running configuration on device" |
| 524 |
) |
| 525 |
if module.params["src"] or module.params["content"]: |
| 526 |
msg += " including the indentation" |
| 527 |
if "warnings" in result: |
| 528 |
result["warnings"].append(msg) |
| 529 |
else: |
| 530 |
result["warnings"] = msg |
| 531 |
|
| 532 |
module.exit_json(**result) |
| 533 |
|
| 534 |
|
| 535 |
if __name__ == "__main__": |
| 536 |
main() |