From af236181937e38e17173eb22646eacc1d702de43 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Sun, 8 May 2022 05:44:01 -0700 Subject: [PATCH 01/19] Init --- .github/workflows/integration.yml | 17 +++++++++++++++++ .gitignore | 6 ++++++ pyproject.toml | 9 +++++++++ 3 files changed, 32 insertions(+) create mode 100644 .github/workflows/integration.yml create mode 100644 pyproject.toml diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml new file mode 100644 index 000000000..50494f0ae --- /dev/null +++ b/.github/workflows/integration.yml @@ -0,0 +1,17 @@ +name: Integration +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +jobs: + integration: + uses: ansible-network/github_actions/.github/workflows/integration.yml@main + with: + network_os: cisco.nxos.nxos + secrets: + cml_ssh_password: ${{ secrets.cml_ssh_password }} + virl_host: ${{ secrets.virl_host }} + virl_password: ${{ secrets.virl_password }} diff --git a/.gitignore b/.gitignore index 45d94ba47..7116e16dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,9 @@ +# Linked collection directory +collections/ + +# Any virl residue +.virl + # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..6f2bd08a3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,9 @@ +[tool.black] +line-length = 79 + +[tool.pytest.ini_options] +testpaths = ["tests"] +filterwarnings = [ + 'ignore:AnsibleCollectionFinder has already been configured', + 'ignore:_AnsibleCollectionFinder.find_spec().*', +] From 378151619737a59b3c1c5ffe8c91f75201749e84 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Sun, 8 May 2022 06:03:35 -0700 Subject: [PATCH 02/19] Test file --- tests/__init__.py | 0 tests/integration/__init__.py | 0 tests/integration/labs/single.yaml | 80 +++++++++++++++++++++++++++ tests/integration/test_integration.py | 35 ++++++++++++ 4 files changed, 115 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/labs/single.yaml create mode 100644 tests/integration/test_integration.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/integration/labs/single.yaml b/tests/integration/labs/single.yaml new file mode 100644 index 000000000..1e30db32f --- /dev/null +++ b/tests/integration/labs/single.yaml @@ -0,0 +1,80 @@ +lab: + description: "" + notes: "" + timestamp: 1651582103.0855575 + title: nxos test + version: 0.0.4 +nodes: + - id: n0 + label: nxos9000-0 + node_definition: nxosv9000 + x: -1750 + y: -250 + configuration: |- + # workaround for booting to loader> prompt + echo 'from cli import cli' > set_boot.py + echo 'import json' >> set_boot.py + echo 'import os' >> set_boot.py + echo 'import time' >> set_boot.py + echo 'bootimage = json.loads(cli("show version | json"))["kick_file_name"]' >> set_boot.py + echo 'set_boot = cli("conf t ; boot nxos {} ; no event manager applet BOOTCONFIG".format(bootimage))' >> set_boot.py + echo 'i = 0' >> set_boot.py + echo 'while i < 10:' >> set_boot.py + echo ' try:' >> set_boot.py + echo ' save_config = cli("copy running-config startup-config")' >> set_boot.py + echo ' break' >> set_boot.py + echo ' except Exception:' >> set_boot.py + echo ' i += 1' >> set_boot.py + echo ' time.sleep(1)' >> set_boot.py + echo 'os.remove("/bootflash/set_boot.py")' >> set_boot.py + event manager applet BOOTCONFIG + event syslog pattern "Configured from vty" + action 1.0 cli python bootflash:set_boot.py + # minimum needed config to login + no password strength-check + username admin role network-admin + username admin password cisco role network-admin + username ansible role network-admin + username ansible password ansible role network-admin + interface mgmt0 + ip address dhcp + image_definition: nxosv9300-9-3-8 + tags: [] + interfaces: + - id: i0 + label: Loopback0 + type: loopback + - id: i1 + slot: 0 + label: mgmt0 + type: physical + - id: i2 + slot: 1 + label: Ethernet1/1 + type: physical + - id: i3 + slot: 2 + label: Ethernet1/2 + type: physical + - id: i4 + slot: 3 + label: Ethernet1/3 + type: physical + - id: n1 + label: ext-conn-0 + node_definition: external_connector + x: -2250 + y: -250 + configuration: virbr0 + tags: [] + interfaces: + - id: i0 + slot: 0 + label: port + type: physical +links: + - id: l0 + i1: i1 + n1: n0 + i2: i0 + n2: n1 diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py new file mode 100644 index 000000000..48b50877e --- /dev/null +++ b/tests/integration/test_integration.py @@ -0,0 +1,35 @@ +import os +import subprocess + +import logging +import pytest + + +def test_integration(ansible_project, environment): + args = [ + "ansible-navigator", + "run", + str(ansible_project.playbook), + "-i", + str(ansible_project.inventory), + "--ee", + "false", + "--mode", + "stdout", + "--pas", + str(ansible_project.playbook_artifact), + "--ll", + "debug", + "--lf", + str(ansible_project.log_file), + "--skip-tags", + "local,nxapi", + ] + logging.info(" ".join(args)) + try: + subprocess.check_call( + args, + env=environment, + ) + except subprocess.CalledProcessError as exc: + pytest.fail(msg=f"Integration test failed: {ansible_project.role}") From b7545692e97fb714e6ca5f35ec6f8d270b41e690 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 10 May 2022 22:32:14 +0000 Subject: [PATCH 03/19] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6f2bd08a3..c547b3fd7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,6 +4,6 @@ line-length = 79 [tool.pytest.ini_options] testpaths = ["tests"] filterwarnings = [ - 'ignore:AnsibleCollectionFinder has already been configured', - 'ignore:_AnsibleCollectionFinder.find_spec().*', + 'ignore:AnsibleCollectionFinder has already been configured', + 'ignore:_AnsibleCollectionFinder.find_spec().*', ] From 52fd09bea0ebfaba0b29d65917d7b6f5b5e0292e Mon Sep 17 00:00:00 2001 From: cidrblock Date: Wed, 11 May 2022 07:04:11 -0700 Subject: [PATCH 04/19] Skip snmp_server --- .github/workflows/integration.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 50494f0ae..548bcca2e 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -11,6 +11,8 @@ jobs: uses: ansible-network/github_actions/.github/workflows/integration.yml@main with: network_os: cisco.nxos.nxos + pytest_addopts: "--role-excludes=snmp_server" + secrets: cml_ssh_password: ${{ secrets.cml_ssh_password }} virl_host: ${{ secrets.virl_host }} From 87381f80e9bc57fe43e03e64b98d1537c911b787 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Wed, 11 May 2022 09:22:08 -0700 Subject: [PATCH 05/19] Address pytest.fail msg deprecation message --- tests/integration/test_integration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 48b50877e..379d73afc 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -32,4 +32,4 @@ def test_integration(ansible_project, environment): env=environment, ) except subprocess.CalledProcessError as exc: - pytest.fail(msg=f"Integration test failed: {ansible_project.role}") + pytest.fail(reason=f"Integration test failed: {ansible_project.role}") From 77edfe97aaf27c21a72ac21de8bc3e38ca6a0b9e Mon Sep 17 00:00:00 2001 From: cidrblock Date: Wed, 11 May 2022 13:36:22 -0700 Subject: [PATCH 06/19] empty From 332e0c8fc14792dc6547d4334439e69e92a27763 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Wed, 11 May 2022 15:32:46 -0700 Subject: [PATCH 07/19] Try more --- .github/workflows/integration.yml | 2 +- clean.py | 417 ++++++++++++++++++++++++++++++ 2 files changed, 418 insertions(+), 1 deletion(-) create mode 100644 clean.py diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 548bcca2e..1caf24a85 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -11,7 +11,7 @@ jobs: uses: ansible-network/github_actions/.github/workflows/integration.yml@main with: network_os: cisco.nxos.nxos - pytest_addopts: "--role-excludes=snmp_server" + pytest_addopts: "-d --tx '10*popen//python=python --role-excludes=snmp_server" secrets: cml_ssh_password: ${{ secrets.cml_ssh_password }} diff --git a/clean.py b/clean.py new file mode 100644 index 000000000..ef2c82d6f --- /dev/null +++ b/clean.py @@ -0,0 +1,417 @@ +# cspell:ignore dpkg, getent, lineinfile, nxapi, nxos, rglob, ruamel, sysvinit +"""A test files updater.""" + +import logging +from pyrsistent import v +import ruamel.yaml + +from pathlib import Path +from typing import OrderedDict + +from ansiblelint.yaml_utils import FormattedYAML +from ruamel.yaml import CommentedSeq +from ruamel.yaml.comments import CommentedMap +from ruamel.yaml.tokens import CommentToken +from ruamel.yaml.error import CommentMark + +logging.basicConfig(level=logging.INFO) +LOGGER = logging.getLogger(__name__) + + +BUILTINS = ( + "add_host", + "apt", + "apt_key", + "apt_repository", + "assemble", + "assert", + "async_status", + "blockinfile", + "command", + "copy", + "cron", + "debconf", + "debug", + "dnf", + "dpkg_selections", + "expect", + "fail", + "fetch", + "file", + "find", + "gather_facts", + "get_url", + "getent", + "git", + "group", + "group_by", + "hostname", + "import_playbook", + "import_role", + "import_tasks", + "include", + "include_role", + "include_tasks", + "include_vars", + "iptables", + "known_hosts", + "lineinfile", + "meta", + "package", + "package_facts", + "pause", + "ping", + "pip", + "raw", + "reboot", + "replace", + "rpm_key", + "script", + "service", + "service_facts", + "set_fact", + "set_stats", + "setup", + "shell", + "slurp", + "stat", + "subversion", + "systemd", + "sysvinit", + "tempfile", + "template", + "unarchive", + "uri", + "user", + "validate_argument_spec", + "wait_for", + "wait_for_connection", + "yum", + "yum_repository", +) + + +def change_key(task: CommentedMap, old: str, new: str) -> None: + """Change a key in a task. + + :param task: The task to change + :param old: The old key + :param new: The new key + """ + if old in task.ca.items: + task.ca.items[new] = task.ca.items.pop(old) + + for _ in range(len(task)): + key, value = task.popitem(False) + task[new if old == key else key] = value + + +def update_include_cli(data: CommentedSeq) -> bool: + """Update the include_cli task. + + :param data: The task list + :return: Whether the include_cli task was updated + """ + match = [idx for idx, item in enumerate(data) if item.get("include") == "cli.yaml"] + if not match: + return False + + name = "Include the CLI tasks" + for entry in match: + data[entry]["name"] = name + data[entry].move_to_end("name", last=False) + change_key(data[entry], "include", "ansible.builtin.include_tasks") + return True + + +def update_include_nxapi(data: CommentedSeq) -> bool: + """Update the include_nxapi task. + + :param data: The task list + :return: Whether the include_nxapi task was updated + """ + match = [ + idx for idx, item in enumerate(data) if item.get("include") == "nxapi.yaml" + ] + if not match: + return False + + name = "Include the NX-API tasks" + for entry in match: + data[entry]["name"] = name + data[entry].move_to_end("name", last=False) + change_key(data[entry], "include", "ansible.builtin.include_tasks") + return True + + +def update_builtins(data: CommentedSeq) -> bool: + """Update the builtins. + + :param data: The task list + :return: Whether the builtins were updated + """ + updated = False + for task in data: + for plugin in BUILTINS: + if task.get(plugin): + new_name = f"ansible.builtin.{plugin}" + change_key(task, plugin, new_name) + updated = True + return updated + + +def capitalize_names(data: CommentedSeq) -> bool: + """Capitalize the names of tasks. + + :param data: The task list + :return: Whether the names were capitalized + """ + updated = False + for task in data: + if task.get("name"): + if task["name"].capitalize() != task["name"]: + task["name"] = task["name"].capitalize() + task.move_to_end("name", last=False) + updated = True + return updated + + +def update_include_test_case(list_of_tasks) -> bool: + """Update the include_test_case task. + + :param list_of_tasks: The task list + :return: Whether the include_test_case task was updated + """ + match = [ + idx + for idx, item in enumerate(list_of_tasks) + if item.get("include", "").startswith("{{ test_case_to_run }}") + or item.get("ansible.builtin.include_tasks", "").startswith( + "{{ test_case_to_run }}" + ) + ] + if not match: + return False + for entry in match: + change_key(list_of_tasks[entry], "include", "ansible.builtin.include_tasks") + values = ( + list_of_tasks[entry] + .get("ansible.builtin.include_tasks") + .replace("{{ ", "{{") + .replace(" }}", "}}") + ) + first, var_pairs = values.split(" ", 1) + list_of_tasks[entry]["ansible.builtin.include_tasks"] = first.replace( + "{{", "{{ " + ).replace("}}", " }}") + list_of_tasks[entry]["vars"] = {} + for var_pair in var_pairs.split(" "): + key, value = var_pair.split("=") + list_of_tasks[entry]["vars"][key] = value.replace("{{", "{{ ").replace( + "}}", " }}" + ) + + return True + + +def undo_set_fact_equal(list_of_tasks) -> bool: + """Undo the debug: msg=equal task. + + :param list_of_tasks: The task list + :return: Whether the debug: msg=equal task was undone + """ + match = [] + for idx, task in enumerate(list_of_tasks): + if task.get("set_fact"): + if not isinstance(task["set_fact"], str): + continue + match.append(idx) + + if not match: + return False + ct = CommentToken("\n\n", CommentMark(0), None) + + for entry in match: + clean_value = ( + list_of_tasks[entry]["set_fact"] + .replace("{{ ", "{{") + .replace(" }}", "}}") + .replace(" | ", "|") + ) + clean_values = clean_value.split() + list_of_tasks[entry]["set_fact"] = CommentedMap() + + last_key = "" + error = False + for clean_value in clean_values: + new_value = None + key, value = clean_value.split("=", maxsplit=1) + # might be a number + if value.strip("'").strip('"') == value: + try: + new_value = int(value) + except ValueError: + try: + new_value = float(value) + except ValueError: + pass + if new_value is None: + if value.strip("'").strip('"') in ["True", "true", "yes", "Yes"]: + new_value = True + elif value.strip("'").strip('"') in ["False", "false", "no", "No"]: + new_value = False + else: + new_value = ( + value.strip('"') + .strip("'") + .replace("{{", "{{ ") + .replace("}}", " }}") + .replace("|", " | ") + ) + list_of_tasks[entry]["set_fact"][key] = new_value + last_key = key + + commented = False + if "set_fact" in list_of_tasks[entry].ca.items: + list_of_tasks[entry].ca.items.pop("set_fact") + commented = True + + change_key(list_of_tasks[entry], "set_fact", "ansible.builtin.set_fact") + + if commented: + list_of_tasks[entry]["ansible.builtin.set_fact"].ca.items[last_key] = [ + None, + None, + ct, + None, + ] + + return True + + +def undo_debug_equal(list_of_tasks) -> bool: + """Undo the debug: msg=equal task. + + :param list_of_tasks: The task list + :return: Whether the debug: msg=equal task was undone + """ + match = [] + for idx, task in enumerate(list_of_tasks): + if task.get("debug"): + if not isinstance(task["debug"], str): + continue + match.append(idx) + + if not match: + return False + ct = CommentToken("\n\n", CommentMark(0), None) + + for entry in match: + keyword, value = list_of_tasks[entry]["debug"].split("=", maxsplit=1) + list_of_tasks[entry]["debug"] = CommentedMap() + list_of_tasks[entry]["debug"][keyword] = value.strip('"').strip("'") + + debug_commented = False + if "debug" in list_of_tasks[entry].ca.items: + list_of_tasks[entry].ca.items.pop("debug") + debug_commented = True + + change_key(list_of_tasks[entry], "debug", "ansible.builtin.debug") + + if debug_commented: + list_of_tasks[entry]["ansible.builtin.debug"].ca.items[keyword] = [ + None, + None, + ct, + None, + ] + + return True + + +def set_style(doc: CommentedSeq, flow: bool) -> None: + """Set the style of a YAML document. + + :param d: The document to set the style on + :param flow: Whether to use flow style or not + """ + if isinstance(doc, CommentedMap): + if flow: + doc.fa.set_flow_style() + else: + doc.fa.set_block_style() + for key in doc: + set_style(doc[key], flow) + elif isinstance(doc, CommentedSeq): + if flow: + doc.fa.set_flow_style() + else: + doc.fa.set_block_style() + for item in doc: + set_style(item, flow) + + +def update_list_of_tasks(list_of_tasks) -> bool: + """Update the list of tasks. + + :param list_of_tasks: The list of tasks + :return: Whether the list of tasks was updated + """ + updated = [] + # updated.append(update_include_cli(list_of_tasks)) + # updated.append(update_include_nxapi(list_of_tasks)) + # updated.append(update_builtins(list_of_tasks)) + # updated.append(capitalize_names(list_of_tasks)) + # updated.append(update_include_test_case(list_of_tasks)) + # updated.append(undo_debug_equal(list_of_tasks)) + updated.append(undo_set_fact_equal(list_of_tasks)) + return any(updated) + + +def update(file_path: Path) -> None: + """Update the tasks in a file. + + :param file_path: The path to the file + """ + + yaml = FormattedYAML() + yaml.preserve_quotes = True + + data = yaml.load(file_path) + if not isinstance(data, CommentedSeq): + LOGGER.info("Skipping: %s", file_path) + return + + LOGGER.info("Updating: %s", file_path) + updated = update_list_of_tasks(data) + + for block_part in ["block", "rescue", "always"]: + ids = [idx for idx, entry in enumerate(data) if entry.get(block_part)] + for block_id in ids: + # Remove blank line comments from the block + updates = update_list_of_tasks(data[block_id][block_part]) + if updates: + updated = True + + if not updated: + LOGGER.info("No updates: %s", file_path) + return + + set_style(data, flow=False) + + LOGGER.info("Writing: %s", file_path) + + with file_path.open(mode="w") as fh: + yaml.dump(data, fh) + + +def main(): + """Main entry point.""" + path = Path("tests") + for file_path in sorted(path.rglob("*")): + if file_path.suffix in [".yaml", ".yml"]: + update(file_path) + + +if __name__ == "__main__": + main() From 02378393e611200c95127fed25275cdb77ef1bd7 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Wed, 11 May 2022 15:35:50 -0700 Subject: [PATCH 08/19] Try more --- .github/workflows/integration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 1caf24a85..0b0ce9e48 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -11,7 +11,7 @@ jobs: uses: ansible-network/github_actions/.github/workflows/integration.yml@main with: network_os: cisco.nxos.nxos - pytest_addopts: "-d --tx '10*popen//python=python --role-excludes=snmp_server" + pytest_addopts: "-d --tx 10*popen//python=python --role-excludes=snmp_server" secrets: cml_ssh_password: ${{ secrets.cml_ssh_password }} From 7ffa19f62aa96034203d8a136910bc05c5cc7697 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Wed, 11 May 2022 15:44:38 -0700 Subject: [PATCH 09/19] Try more --- .github/workflows/integration.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 0b0ce9e48..2f37726b4 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -11,7 +11,7 @@ jobs: uses: ansible-network/github_actions/.github/workflows/integration.yml@main with: network_os: cisco.nxos.nxos - pytest_addopts: "-d --tx 10*popen//python=python --role-excludes=snmp_server" + pytest_addopts: "-n auto --role-excludes=snmp_server" secrets: cml_ssh_password: ${{ secrets.cml_ssh_password }} From 2dc4db7c14e39c3629ada33c9b346be5c8c5d3c0 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Thu, 12 May 2022 07:01:00 -0700 Subject: [PATCH 10/19] Update --- .github/workflows/integration.yml | 2 +- clean.py | 43 ++++++++++++++++++++------- tests/integration/test_integration.py | 26 +++++++++++----- 3 files changed, 51 insertions(+), 20 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 2f37726b4..a17155983 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -11,7 +11,7 @@ jobs: uses: ansible-network/github_actions/.github/workflows/integration.yml@main with: network_os: cisco.nxos.nxos - pytest_addopts: "-n auto --role-excludes=snmp_server" + pytest_addopts: "-n 2 --log-level WARNING -vvv --role-excludes=snmp_server" secrets: cml_ssh_password: ${{ secrets.cml_ssh_password }} diff --git a/clean.py b/clean.py index ef2c82d6f..df6a53572 100644 --- a/clean.py +++ b/clean.py @@ -2,7 +2,6 @@ """A test files updater.""" import logging -from pyrsistent import v import ruamel.yaml from pathlib import Path @@ -112,7 +111,11 @@ def update_include_cli(data: CommentedSeq) -> bool: :param data: The task list :return: Whether the include_cli task was updated """ - match = [idx for idx, item in enumerate(data) if item.get("include") == "cli.yaml"] + match = [ + idx + for idx, item in enumerate(data) + if item.get("include") == "cli.yaml" + ] if not match: return False @@ -131,7 +134,9 @@ def update_include_nxapi(data: CommentedSeq) -> bool: :return: Whether the include_nxapi task was updated """ match = [ - idx for idx, item in enumerate(data) if item.get("include") == "nxapi.yaml" + idx + for idx, item in enumerate(data) + if item.get("include") == "nxapi.yaml" ] if not match: return False @@ -193,7 +198,9 @@ def update_include_test_case(list_of_tasks) -> bool: if not match: return False for entry in match: - change_key(list_of_tasks[entry], "include", "ansible.builtin.include_tasks") + change_key( + list_of_tasks[entry], "include", "ansible.builtin.include_tasks" + ) values = ( list_of_tasks[entry] .get("ansible.builtin.include_tasks") @@ -207,9 +214,9 @@ def update_include_test_case(list_of_tasks) -> bool: list_of_tasks[entry]["vars"] = {} for var_pair in var_pairs.split(" "): key, value = var_pair.split("=") - list_of_tasks[entry]["vars"][key] = value.replace("{{", "{{ ").replace( - "}}", " }}" - ) + list_of_tasks[entry]["vars"][key] = value.replace( + "{{", "{{ " + ).replace("}}", " }}") return True @@ -256,9 +263,19 @@ def undo_set_fact_equal(list_of_tasks) -> bool: except ValueError: pass if new_value is None: - if value.strip("'").strip('"') in ["True", "true", "yes", "Yes"]: + if value.strip("'").strip('"') in [ + "True", + "true", + "yes", + "Yes", + ]: new_value = True - elif value.strip("'").strip('"') in ["False", "false", "no", "No"]: + elif value.strip("'").strip('"') in [ + "False", + "false", + "no", + "No", + ]: new_value = False else: new_value = ( @@ -276,10 +293,14 @@ def undo_set_fact_equal(list_of_tasks) -> bool: list_of_tasks[entry].ca.items.pop("set_fact") commented = True - change_key(list_of_tasks[entry], "set_fact", "ansible.builtin.set_fact") + change_key( + list_of_tasks[entry], "set_fact", "ansible.builtin.set_fact" + ) if commented: - list_of_tasks[entry]["ansible.builtin.set_fact"].ca.items[last_key] = [ + list_of_tasks[entry]["ansible.builtin.set_fact"].ca.items[ + last_key + ] = [ None, None, ct, diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 379d73afc..48c9a4df1 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -5,7 +5,8 @@ import pytest -def test_integration(ansible_project, environment): +def run(ansible_project, environment): + __tracebackhide__ = True args = [ "ansible-navigator", "run", @@ -25,11 +26,20 @@ def test_integration(ansible_project, environment): "--skip-tags", "local,nxapi", ] - logging.info(" ".join(args)) - try: - subprocess.check_call( - args, - env=environment, - ) - except subprocess.CalledProcessError as exc: + process = subprocess.run( + args=args, + env=environment, + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + check=False, + shell=False, + ) + if process.returncode: + print(process.stdout.decode("utf-8")) + print(process.stderr.decode("utf-8")) + pytest.fail(reason=f"Integration test failed: {ansible_project.role}") + + +def test_integration(ansible_project, environment): + run(ansible_project, environment) From 220af1eb900808bb01af015264dd4e7e0cfd8ed5 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Thu, 12 May 2022 09:08:14 -0700 Subject: [PATCH 11/19] Add color opt --- .github/workflows/integration.yml | 2 +- .../appliance_config.2022-05-12@07:12:57 | 178 ++++++++++++++++++ .../targets/nxos_config/backup/backup.cfg | 178 ++++++++++++++++++ .../appliance_config.2022-05-12@07:13:06 | 178 ++++++++++++++++++ .../backup_test_dir/appliance/backup.cfg | 178 ++++++++++++++++++ .../appliance/backup_with_alias.cfg | 178 ++++++++++++++++++ 6 files changed, 891 insertions(+), 1 deletion(-) create mode 100644 tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 create mode 100644 tests/integration/targets/nxos_config/backup/backup.cfg create mode 100644 tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 create mode 100644 tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg create mode 100644 tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index a17155983..efc04c15a 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -11,7 +11,7 @@ jobs: uses: ansible-network/github_actions/.github/workflows/integration.yml@main with: network_os: cisco.nxos.nxos - pytest_addopts: "-n 2 --log-level WARNING -vvv --role-excludes=snmp_server" + pytest_addopts: "--color=yes -n 2 --log-level WARNING -vvv --role-excludes=snmp_server" secrets: cml_ssh_password: ${{ secrets.cml_ssh_password }} diff --git a/tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 b/tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 new file mode 100644 index 000000000..151f0f6d5 --- /dev/null +++ b/tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 @@ -0,0 +1,178 @@ +!Command: show running-config +!Running configuration last done at: Thu May 12 14:12:45 2022 +!Time: Thu May 12 14:12:52 2022 + +version 9.3(8) Bios:version +hostname switch +vdc switch id 1 + limit-resource vlan minimum 16 maximum 4094 + limit-resource vrf minimum 2 maximum 4096 + limit-resource port-channel minimum 0 maximum 511 + limit-resource u4route-mem minimum 248 maximum 248 + limit-resource u6route-mem minimum 96 maximum 96 + limit-resource m4route-mem minimum 58 maximum 58 + limit-resource m6route-mem minimum 8 maximum 8 + +no password strength-check +username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin +username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin +username ansible passphrase lifetime 99999 warntime 14 gracetime 3 +ip domain-lookup +ip name-server 192.168.255.1 use-vrf management +snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key +snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key +rmon event 1 log trap public description FATAL(1) owner PMON@FATAL +rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL +rmon event 3 log trap public description ERROR(3) owner PMON@ERROR +rmon event 4 log trap public description WARNING(4) owner PMON@WARNING +rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO + +vlan 1 + +vrf context management + ip route 0.0.0.0/0 192.168.255.1 + +interface Ethernet1/1 + description this is a test + shutdown + switchport access vlan 3333 + spanning-tree port type edge + +interface Ethernet1/2 + +interface Ethernet1/3 + +interface Ethernet1/4 + +interface Ethernet1/5 + +interface Ethernet1/6 + +interface Ethernet1/7 + +interface Ethernet1/8 + +interface Ethernet1/9 + +interface Ethernet1/10 + +interface Ethernet1/11 + +interface Ethernet1/12 + +interface Ethernet1/13 + +interface Ethernet1/14 + +interface Ethernet1/15 + +interface Ethernet1/16 + +interface Ethernet1/17 + +interface Ethernet1/18 + +interface Ethernet1/19 + +interface Ethernet1/20 + +interface Ethernet1/21 + +interface Ethernet1/22 + +interface Ethernet1/23 + +interface Ethernet1/24 + +interface Ethernet1/25 + +interface Ethernet1/26 + +interface Ethernet1/27 + +interface Ethernet1/28 + +interface Ethernet1/29 + +interface Ethernet1/30 + +interface Ethernet1/31 + +interface Ethernet1/32 + +interface Ethernet1/33 + +interface Ethernet1/34 + +interface Ethernet1/35 + +interface Ethernet1/36 + +interface Ethernet1/37 + +interface Ethernet1/38 + +interface Ethernet1/39 + +interface Ethernet1/40 + +interface Ethernet1/41 + +interface Ethernet1/42 + +interface Ethernet1/43 + +interface Ethernet1/44 + +interface Ethernet1/45 + +interface Ethernet1/46 + +interface Ethernet1/47 + +interface Ethernet1/48 + +interface Ethernet1/49 + +interface Ethernet1/50 + +interface Ethernet1/51 + +interface Ethernet1/52 + +interface Ethernet1/53 + +interface Ethernet1/54 + +interface Ethernet1/55 + +interface Ethernet1/56 + +interface Ethernet1/57 + +interface Ethernet1/58 + +interface Ethernet1/59 + +interface Ethernet1/60 + +interface Ethernet1/61 + +interface Ethernet1/62 + +interface Ethernet1/63 + +interface Ethernet1/64 + +interface mgmt0 + ip address dhcp + vrf member management + +interface loopback1 + description this is a test + shutdown +icam monitor scale + +line console +line vty +boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup/backup.cfg b/tests/integration/targets/nxos_config/backup/backup.cfg new file mode 100644 index 000000000..3794d8d9e --- /dev/null +++ b/tests/integration/targets/nxos_config/backup/backup.cfg @@ -0,0 +1,178 @@ +!Command: show running-config +!Running configuration last done at: Thu May 12 14:12:45 2022 +!Time: Thu May 12 14:12:58 2022 + +version 9.3(8) Bios:version +hostname switch +vdc switch id 1 + limit-resource vlan minimum 16 maximum 4094 + limit-resource vrf minimum 2 maximum 4096 + limit-resource port-channel minimum 0 maximum 511 + limit-resource u4route-mem minimum 248 maximum 248 + limit-resource u6route-mem minimum 96 maximum 96 + limit-resource m4route-mem minimum 58 maximum 58 + limit-resource m6route-mem minimum 8 maximum 8 + +no password strength-check +username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin +username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin +username ansible passphrase lifetime 99999 warntime 14 gracetime 3 +ip domain-lookup +ip name-server 192.168.255.1 use-vrf management +snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key +snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key +rmon event 1 log trap public description FATAL(1) owner PMON@FATAL +rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL +rmon event 3 log trap public description ERROR(3) owner PMON@ERROR +rmon event 4 log trap public description WARNING(4) owner PMON@WARNING +rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO + +vlan 1 + +vrf context management + ip route 0.0.0.0/0 192.168.255.1 + +interface Ethernet1/1 + description this is a test + shutdown + switchport access vlan 3333 + spanning-tree port type edge + +interface Ethernet1/2 + +interface Ethernet1/3 + +interface Ethernet1/4 + +interface Ethernet1/5 + +interface Ethernet1/6 + +interface Ethernet1/7 + +interface Ethernet1/8 + +interface Ethernet1/9 + +interface Ethernet1/10 + +interface Ethernet1/11 + +interface Ethernet1/12 + +interface Ethernet1/13 + +interface Ethernet1/14 + +interface Ethernet1/15 + +interface Ethernet1/16 + +interface Ethernet1/17 + +interface Ethernet1/18 + +interface Ethernet1/19 + +interface Ethernet1/20 + +interface Ethernet1/21 + +interface Ethernet1/22 + +interface Ethernet1/23 + +interface Ethernet1/24 + +interface Ethernet1/25 + +interface Ethernet1/26 + +interface Ethernet1/27 + +interface Ethernet1/28 + +interface Ethernet1/29 + +interface Ethernet1/30 + +interface Ethernet1/31 + +interface Ethernet1/32 + +interface Ethernet1/33 + +interface Ethernet1/34 + +interface Ethernet1/35 + +interface Ethernet1/36 + +interface Ethernet1/37 + +interface Ethernet1/38 + +interface Ethernet1/39 + +interface Ethernet1/40 + +interface Ethernet1/41 + +interface Ethernet1/42 + +interface Ethernet1/43 + +interface Ethernet1/44 + +interface Ethernet1/45 + +interface Ethernet1/46 + +interface Ethernet1/47 + +interface Ethernet1/48 + +interface Ethernet1/49 + +interface Ethernet1/50 + +interface Ethernet1/51 + +interface Ethernet1/52 + +interface Ethernet1/53 + +interface Ethernet1/54 + +interface Ethernet1/55 + +interface Ethernet1/56 + +interface Ethernet1/57 + +interface Ethernet1/58 + +interface Ethernet1/59 + +interface Ethernet1/60 + +interface Ethernet1/61 + +interface Ethernet1/62 + +interface Ethernet1/63 + +interface Ethernet1/64 + +interface mgmt0 + ip address dhcp + vrf member management + +interface loopback1 + description this is a test + shutdown +icam monitor scale + +line console +line vty +boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 b/tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 new file mode 100644 index 000000000..ab59d8a84 --- /dev/null +++ b/tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 @@ -0,0 +1,178 @@ +!Command: show running-config +!Running configuration last done at: Thu May 12 14:12:45 2022 +!Time: Thu May 12 14:13:01 2022 + +version 9.3(8) Bios:version +hostname switch +vdc switch id 1 + limit-resource vlan minimum 16 maximum 4094 + limit-resource vrf minimum 2 maximum 4096 + limit-resource port-channel minimum 0 maximum 511 + limit-resource u4route-mem minimum 248 maximum 248 + limit-resource u6route-mem minimum 96 maximum 96 + limit-resource m4route-mem minimum 58 maximum 58 + limit-resource m6route-mem minimum 8 maximum 8 + +no password strength-check +username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin +username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin +username ansible passphrase lifetime 99999 warntime 14 gracetime 3 +ip domain-lookup +ip name-server 192.168.255.1 use-vrf management +snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key +snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key +rmon event 1 log trap public description FATAL(1) owner PMON@FATAL +rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL +rmon event 3 log trap public description ERROR(3) owner PMON@ERROR +rmon event 4 log trap public description WARNING(4) owner PMON@WARNING +rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO + +vlan 1 + +vrf context management + ip route 0.0.0.0/0 192.168.255.1 + +interface Ethernet1/1 + description this is a test + shutdown + switchport access vlan 3333 + spanning-tree port type edge + +interface Ethernet1/2 + +interface Ethernet1/3 + +interface Ethernet1/4 + +interface Ethernet1/5 + +interface Ethernet1/6 + +interface Ethernet1/7 + +interface Ethernet1/8 + +interface Ethernet1/9 + +interface Ethernet1/10 + +interface Ethernet1/11 + +interface Ethernet1/12 + +interface Ethernet1/13 + +interface Ethernet1/14 + +interface Ethernet1/15 + +interface Ethernet1/16 + +interface Ethernet1/17 + +interface Ethernet1/18 + +interface Ethernet1/19 + +interface Ethernet1/20 + +interface Ethernet1/21 + +interface Ethernet1/22 + +interface Ethernet1/23 + +interface Ethernet1/24 + +interface Ethernet1/25 + +interface Ethernet1/26 + +interface Ethernet1/27 + +interface Ethernet1/28 + +interface Ethernet1/29 + +interface Ethernet1/30 + +interface Ethernet1/31 + +interface Ethernet1/32 + +interface Ethernet1/33 + +interface Ethernet1/34 + +interface Ethernet1/35 + +interface Ethernet1/36 + +interface Ethernet1/37 + +interface Ethernet1/38 + +interface Ethernet1/39 + +interface Ethernet1/40 + +interface Ethernet1/41 + +interface Ethernet1/42 + +interface Ethernet1/43 + +interface Ethernet1/44 + +interface Ethernet1/45 + +interface Ethernet1/46 + +interface Ethernet1/47 + +interface Ethernet1/48 + +interface Ethernet1/49 + +interface Ethernet1/50 + +interface Ethernet1/51 + +interface Ethernet1/52 + +interface Ethernet1/53 + +interface Ethernet1/54 + +interface Ethernet1/55 + +interface Ethernet1/56 + +interface Ethernet1/57 + +interface Ethernet1/58 + +interface Ethernet1/59 + +interface Ethernet1/60 + +interface Ethernet1/61 + +interface Ethernet1/62 + +interface Ethernet1/63 + +interface Ethernet1/64 + +interface mgmt0 + ip address dhcp + vrf member management + +interface loopback1 + description this is a test + shutdown +icam monitor scale + +line console +line vty +boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg b/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg new file mode 100644 index 000000000..99a81b538 --- /dev/null +++ b/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg @@ -0,0 +1,178 @@ +!Command: show running-config +!Running configuration last done at: Thu May 12 14:12:45 2022 +!Time: Thu May 12 14:12:54 2022 + +version 9.3(8) Bios:version +hostname switch +vdc switch id 1 + limit-resource vlan minimum 16 maximum 4094 + limit-resource vrf minimum 2 maximum 4096 + limit-resource port-channel minimum 0 maximum 511 + limit-resource u4route-mem minimum 248 maximum 248 + limit-resource u6route-mem minimum 96 maximum 96 + limit-resource m4route-mem minimum 58 maximum 58 + limit-resource m6route-mem minimum 8 maximum 8 + +no password strength-check +username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin +username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin +username ansible passphrase lifetime 99999 warntime 14 gracetime 3 +ip domain-lookup +ip name-server 192.168.255.1 use-vrf management +snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key +snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key +rmon event 1 log trap public description FATAL(1) owner PMON@FATAL +rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL +rmon event 3 log trap public description ERROR(3) owner PMON@ERROR +rmon event 4 log trap public description WARNING(4) owner PMON@WARNING +rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO + +vlan 1 + +vrf context management + ip route 0.0.0.0/0 192.168.255.1 + +interface Ethernet1/1 + description this is a test + shutdown + switchport access vlan 3333 + spanning-tree port type edge + +interface Ethernet1/2 + +interface Ethernet1/3 + +interface Ethernet1/4 + +interface Ethernet1/5 + +interface Ethernet1/6 + +interface Ethernet1/7 + +interface Ethernet1/8 + +interface Ethernet1/9 + +interface Ethernet1/10 + +interface Ethernet1/11 + +interface Ethernet1/12 + +interface Ethernet1/13 + +interface Ethernet1/14 + +interface Ethernet1/15 + +interface Ethernet1/16 + +interface Ethernet1/17 + +interface Ethernet1/18 + +interface Ethernet1/19 + +interface Ethernet1/20 + +interface Ethernet1/21 + +interface Ethernet1/22 + +interface Ethernet1/23 + +interface Ethernet1/24 + +interface Ethernet1/25 + +interface Ethernet1/26 + +interface Ethernet1/27 + +interface Ethernet1/28 + +interface Ethernet1/29 + +interface Ethernet1/30 + +interface Ethernet1/31 + +interface Ethernet1/32 + +interface Ethernet1/33 + +interface Ethernet1/34 + +interface Ethernet1/35 + +interface Ethernet1/36 + +interface Ethernet1/37 + +interface Ethernet1/38 + +interface Ethernet1/39 + +interface Ethernet1/40 + +interface Ethernet1/41 + +interface Ethernet1/42 + +interface Ethernet1/43 + +interface Ethernet1/44 + +interface Ethernet1/45 + +interface Ethernet1/46 + +interface Ethernet1/47 + +interface Ethernet1/48 + +interface Ethernet1/49 + +interface Ethernet1/50 + +interface Ethernet1/51 + +interface Ethernet1/52 + +interface Ethernet1/53 + +interface Ethernet1/54 + +interface Ethernet1/55 + +interface Ethernet1/56 + +interface Ethernet1/57 + +interface Ethernet1/58 + +interface Ethernet1/59 + +interface Ethernet1/60 + +interface Ethernet1/61 + +interface Ethernet1/62 + +interface Ethernet1/63 + +interface Ethernet1/64 + +interface mgmt0 + ip address dhcp + vrf member management + +interface loopback1 + description this is a test + shutdown +icam monitor scale + +line console +line vty +boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg b/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg new file mode 100644 index 000000000..ae144d7c8 --- /dev/null +++ b/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg @@ -0,0 +1,178 @@ +!Command: show running-config +!Running configuration last done at: Thu May 12 14:13:57 2022 +!Time: Thu May 12 14:14:00 2022 + +version 9.3(8) Bios:version +hostname switch +vdc switch id 1 + limit-resource vlan minimum 16 maximum 4094 + limit-resource vrf minimum 2 maximum 4096 + limit-resource port-channel minimum 0 maximum 511 + limit-resource u4route-mem minimum 248 maximum 248 + limit-resource u6route-mem minimum 96 maximum 96 + limit-resource m4route-mem minimum 58 maximum 58 + limit-resource m6route-mem minimum 8 maximum 8 + +no password strength-check +username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin +username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin +username ansible passphrase lifetime 99999 warntime 14 gracetime 3 +ip domain-lookup +ip name-server 192.168.255.1 use-vrf management +snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key +snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key +rmon event 1 log trap public description FATAL(1) owner PMON@FATAL +rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL +rmon event 3 log trap public description ERROR(3) owner PMON@ERROR +rmon event 4 log trap public description WARNING(4) owner PMON@WARNING +rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO + +vlan 1 + +vrf context management + ip route 0.0.0.0/0 192.168.255.1 + +interface Ethernet1/1 + description this is a test + shutdown + switchport access vlan 3333 + spanning-tree port type edge + +interface Ethernet1/2 + +interface Ethernet1/3 + +interface Ethernet1/4 + +interface Ethernet1/5 + +interface Ethernet1/6 + +interface Ethernet1/7 + +interface Ethernet1/8 + +interface Ethernet1/9 + +interface Ethernet1/10 + +interface Ethernet1/11 + +interface Ethernet1/12 + +interface Ethernet1/13 + +interface Ethernet1/14 + +interface Ethernet1/15 + +interface Ethernet1/16 + +interface Ethernet1/17 + +interface Ethernet1/18 + +interface Ethernet1/19 + +interface Ethernet1/20 + +interface Ethernet1/21 + +interface Ethernet1/22 + +interface Ethernet1/23 + +interface Ethernet1/24 + +interface Ethernet1/25 + +interface Ethernet1/26 + +interface Ethernet1/27 + +interface Ethernet1/28 + +interface Ethernet1/29 + +interface Ethernet1/30 + +interface Ethernet1/31 + +interface Ethernet1/32 + +interface Ethernet1/33 + +interface Ethernet1/34 + +interface Ethernet1/35 + +interface Ethernet1/36 + +interface Ethernet1/37 + +interface Ethernet1/38 + +interface Ethernet1/39 + +interface Ethernet1/40 + +interface Ethernet1/41 + +interface Ethernet1/42 + +interface Ethernet1/43 + +interface Ethernet1/44 + +interface Ethernet1/45 + +interface Ethernet1/46 + +interface Ethernet1/47 + +interface Ethernet1/48 + +interface Ethernet1/49 + +interface Ethernet1/50 + +interface Ethernet1/51 + +interface Ethernet1/52 + +interface Ethernet1/53 + +interface Ethernet1/54 + +interface Ethernet1/55 + +interface Ethernet1/56 + +interface Ethernet1/57 + +interface Ethernet1/58 + +interface Ethernet1/59 + +interface Ethernet1/60 + +interface Ethernet1/61 + +interface Ethernet1/62 + +interface Ethernet1/63 + +interface Ethernet1/64 + +interface mgmt0 + ip address dhcp + vrf member management + +interface loopback1 + description this is a test + shutdown +icam monitor scale + +line console +line vty +boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file From 457915e3fb23edfeb4409eebbe9f4f31e513e864 Mon Sep 17 00:00:00 2001 From: cidrblock Date: Thu, 12 May 2022 09:11:46 -0700 Subject: [PATCH 12/19] Rm backup files --- .../appliance_config.2022-05-12@07:12:57 | 178 ------------------ .../targets/nxos_config/backup/backup.cfg | 178 ------------------ .../appliance_config.2022-05-12@07:13:06 | 178 ------------------ .../backup_test_dir/appliance/backup.cfg | 178 ------------------ .../appliance/backup_with_alias.cfg | 178 ------------------ 5 files changed, 890 deletions(-) delete mode 100644 tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 delete mode 100644 tests/integration/targets/nxos_config/backup/backup.cfg delete mode 100644 tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 delete mode 100644 tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg delete mode 100644 tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg diff --git a/tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 b/tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 deleted file mode 100644 index 151f0f6d5..000000000 --- a/tests/integration/targets/nxos_config/backup/appliance_config.2022-05-12@07:12:57 +++ /dev/null @@ -1,178 +0,0 @@ -!Command: show running-config -!Running configuration last done at: Thu May 12 14:12:45 2022 -!Time: Thu May 12 14:12:52 2022 - -version 9.3(8) Bios:version -hostname switch -vdc switch id 1 - limit-resource vlan minimum 16 maximum 4094 - limit-resource vrf minimum 2 maximum 4096 - limit-resource port-channel minimum 0 maximum 511 - limit-resource u4route-mem minimum 248 maximum 248 - limit-resource u6route-mem minimum 96 maximum 96 - limit-resource m4route-mem minimum 58 maximum 58 - limit-resource m6route-mem minimum 8 maximum 8 - -no password strength-check -username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin -username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin -username ansible passphrase lifetime 99999 warntime 14 gracetime 3 -ip domain-lookup -ip name-server 192.168.255.1 use-vrf management -snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key -snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key -rmon event 1 log trap public description FATAL(1) owner PMON@FATAL -rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL -rmon event 3 log trap public description ERROR(3) owner PMON@ERROR -rmon event 4 log trap public description WARNING(4) owner PMON@WARNING -rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO - -vlan 1 - -vrf context management - ip route 0.0.0.0/0 192.168.255.1 - -interface Ethernet1/1 - description this is a test - shutdown - switchport access vlan 3333 - spanning-tree port type edge - -interface Ethernet1/2 - -interface Ethernet1/3 - -interface Ethernet1/4 - -interface Ethernet1/5 - -interface Ethernet1/6 - -interface Ethernet1/7 - -interface Ethernet1/8 - -interface Ethernet1/9 - -interface Ethernet1/10 - -interface Ethernet1/11 - -interface Ethernet1/12 - -interface Ethernet1/13 - -interface Ethernet1/14 - -interface Ethernet1/15 - -interface Ethernet1/16 - -interface Ethernet1/17 - -interface Ethernet1/18 - -interface Ethernet1/19 - -interface Ethernet1/20 - -interface Ethernet1/21 - -interface Ethernet1/22 - -interface Ethernet1/23 - -interface Ethernet1/24 - -interface Ethernet1/25 - -interface Ethernet1/26 - -interface Ethernet1/27 - -interface Ethernet1/28 - -interface Ethernet1/29 - -interface Ethernet1/30 - -interface Ethernet1/31 - -interface Ethernet1/32 - -interface Ethernet1/33 - -interface Ethernet1/34 - -interface Ethernet1/35 - -interface Ethernet1/36 - -interface Ethernet1/37 - -interface Ethernet1/38 - -interface Ethernet1/39 - -interface Ethernet1/40 - -interface Ethernet1/41 - -interface Ethernet1/42 - -interface Ethernet1/43 - -interface Ethernet1/44 - -interface Ethernet1/45 - -interface Ethernet1/46 - -interface Ethernet1/47 - -interface Ethernet1/48 - -interface Ethernet1/49 - -interface Ethernet1/50 - -interface Ethernet1/51 - -interface Ethernet1/52 - -interface Ethernet1/53 - -interface Ethernet1/54 - -interface Ethernet1/55 - -interface Ethernet1/56 - -interface Ethernet1/57 - -interface Ethernet1/58 - -interface Ethernet1/59 - -interface Ethernet1/60 - -interface Ethernet1/61 - -interface Ethernet1/62 - -interface Ethernet1/63 - -interface Ethernet1/64 - -interface mgmt0 - ip address dhcp - vrf member management - -interface loopback1 - description this is a test - shutdown -icam monitor scale - -line console -line vty -boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup/backup.cfg b/tests/integration/targets/nxos_config/backup/backup.cfg deleted file mode 100644 index 3794d8d9e..000000000 --- a/tests/integration/targets/nxos_config/backup/backup.cfg +++ /dev/null @@ -1,178 +0,0 @@ -!Command: show running-config -!Running configuration last done at: Thu May 12 14:12:45 2022 -!Time: Thu May 12 14:12:58 2022 - -version 9.3(8) Bios:version -hostname switch -vdc switch id 1 - limit-resource vlan minimum 16 maximum 4094 - limit-resource vrf minimum 2 maximum 4096 - limit-resource port-channel minimum 0 maximum 511 - limit-resource u4route-mem minimum 248 maximum 248 - limit-resource u6route-mem minimum 96 maximum 96 - limit-resource m4route-mem minimum 58 maximum 58 - limit-resource m6route-mem minimum 8 maximum 8 - -no password strength-check -username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin -username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin -username ansible passphrase lifetime 99999 warntime 14 gracetime 3 -ip domain-lookup -ip name-server 192.168.255.1 use-vrf management -snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key -snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key -rmon event 1 log trap public description FATAL(1) owner PMON@FATAL -rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL -rmon event 3 log trap public description ERROR(3) owner PMON@ERROR -rmon event 4 log trap public description WARNING(4) owner PMON@WARNING -rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO - -vlan 1 - -vrf context management - ip route 0.0.0.0/0 192.168.255.1 - -interface Ethernet1/1 - description this is a test - shutdown - switchport access vlan 3333 - spanning-tree port type edge - -interface Ethernet1/2 - -interface Ethernet1/3 - -interface Ethernet1/4 - -interface Ethernet1/5 - -interface Ethernet1/6 - -interface Ethernet1/7 - -interface Ethernet1/8 - -interface Ethernet1/9 - -interface Ethernet1/10 - -interface Ethernet1/11 - -interface Ethernet1/12 - -interface Ethernet1/13 - -interface Ethernet1/14 - -interface Ethernet1/15 - -interface Ethernet1/16 - -interface Ethernet1/17 - -interface Ethernet1/18 - -interface Ethernet1/19 - -interface Ethernet1/20 - -interface Ethernet1/21 - -interface Ethernet1/22 - -interface Ethernet1/23 - -interface Ethernet1/24 - -interface Ethernet1/25 - -interface Ethernet1/26 - -interface Ethernet1/27 - -interface Ethernet1/28 - -interface Ethernet1/29 - -interface Ethernet1/30 - -interface Ethernet1/31 - -interface Ethernet1/32 - -interface Ethernet1/33 - -interface Ethernet1/34 - -interface Ethernet1/35 - -interface Ethernet1/36 - -interface Ethernet1/37 - -interface Ethernet1/38 - -interface Ethernet1/39 - -interface Ethernet1/40 - -interface Ethernet1/41 - -interface Ethernet1/42 - -interface Ethernet1/43 - -interface Ethernet1/44 - -interface Ethernet1/45 - -interface Ethernet1/46 - -interface Ethernet1/47 - -interface Ethernet1/48 - -interface Ethernet1/49 - -interface Ethernet1/50 - -interface Ethernet1/51 - -interface Ethernet1/52 - -interface Ethernet1/53 - -interface Ethernet1/54 - -interface Ethernet1/55 - -interface Ethernet1/56 - -interface Ethernet1/57 - -interface Ethernet1/58 - -interface Ethernet1/59 - -interface Ethernet1/60 - -interface Ethernet1/61 - -interface Ethernet1/62 - -interface Ethernet1/63 - -interface Ethernet1/64 - -interface mgmt0 - ip address dhcp - vrf member management - -interface loopback1 - description this is a test - shutdown -icam monitor scale - -line console -line vty -boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 b/tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 deleted file mode 100644 index ab59d8a84..000000000 --- a/tests/integration/targets/nxos_config/backup_test_dir/appliance/appliance_config.2022-05-12@07:13:06 +++ /dev/null @@ -1,178 +0,0 @@ -!Command: show running-config -!Running configuration last done at: Thu May 12 14:12:45 2022 -!Time: Thu May 12 14:13:01 2022 - -version 9.3(8) Bios:version -hostname switch -vdc switch id 1 - limit-resource vlan minimum 16 maximum 4094 - limit-resource vrf minimum 2 maximum 4096 - limit-resource port-channel minimum 0 maximum 511 - limit-resource u4route-mem minimum 248 maximum 248 - limit-resource u6route-mem minimum 96 maximum 96 - limit-resource m4route-mem minimum 58 maximum 58 - limit-resource m6route-mem minimum 8 maximum 8 - -no password strength-check -username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin -username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin -username ansible passphrase lifetime 99999 warntime 14 gracetime 3 -ip domain-lookup -ip name-server 192.168.255.1 use-vrf management -snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key -snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key -rmon event 1 log trap public description FATAL(1) owner PMON@FATAL -rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL -rmon event 3 log trap public description ERROR(3) owner PMON@ERROR -rmon event 4 log trap public description WARNING(4) owner PMON@WARNING -rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO - -vlan 1 - -vrf context management - ip route 0.0.0.0/0 192.168.255.1 - -interface Ethernet1/1 - description this is a test - shutdown - switchport access vlan 3333 - spanning-tree port type edge - -interface Ethernet1/2 - -interface Ethernet1/3 - -interface Ethernet1/4 - -interface Ethernet1/5 - -interface Ethernet1/6 - -interface Ethernet1/7 - -interface Ethernet1/8 - -interface Ethernet1/9 - -interface Ethernet1/10 - -interface Ethernet1/11 - -interface Ethernet1/12 - -interface Ethernet1/13 - -interface Ethernet1/14 - -interface Ethernet1/15 - -interface Ethernet1/16 - -interface Ethernet1/17 - -interface Ethernet1/18 - -interface Ethernet1/19 - -interface Ethernet1/20 - -interface Ethernet1/21 - -interface Ethernet1/22 - -interface Ethernet1/23 - -interface Ethernet1/24 - -interface Ethernet1/25 - -interface Ethernet1/26 - -interface Ethernet1/27 - -interface Ethernet1/28 - -interface Ethernet1/29 - -interface Ethernet1/30 - -interface Ethernet1/31 - -interface Ethernet1/32 - -interface Ethernet1/33 - -interface Ethernet1/34 - -interface Ethernet1/35 - -interface Ethernet1/36 - -interface Ethernet1/37 - -interface Ethernet1/38 - -interface Ethernet1/39 - -interface Ethernet1/40 - -interface Ethernet1/41 - -interface Ethernet1/42 - -interface Ethernet1/43 - -interface Ethernet1/44 - -interface Ethernet1/45 - -interface Ethernet1/46 - -interface Ethernet1/47 - -interface Ethernet1/48 - -interface Ethernet1/49 - -interface Ethernet1/50 - -interface Ethernet1/51 - -interface Ethernet1/52 - -interface Ethernet1/53 - -interface Ethernet1/54 - -interface Ethernet1/55 - -interface Ethernet1/56 - -interface Ethernet1/57 - -interface Ethernet1/58 - -interface Ethernet1/59 - -interface Ethernet1/60 - -interface Ethernet1/61 - -interface Ethernet1/62 - -interface Ethernet1/63 - -interface Ethernet1/64 - -interface mgmt0 - ip address dhcp - vrf member management - -interface loopback1 - description this is a test - shutdown -icam monitor scale - -line console -line vty -boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg b/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg deleted file mode 100644 index 99a81b538..000000000 --- a/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup.cfg +++ /dev/null @@ -1,178 +0,0 @@ -!Command: show running-config -!Running configuration last done at: Thu May 12 14:12:45 2022 -!Time: Thu May 12 14:12:54 2022 - -version 9.3(8) Bios:version -hostname switch -vdc switch id 1 - limit-resource vlan minimum 16 maximum 4094 - limit-resource vrf minimum 2 maximum 4096 - limit-resource port-channel minimum 0 maximum 511 - limit-resource u4route-mem minimum 248 maximum 248 - limit-resource u6route-mem minimum 96 maximum 96 - limit-resource m4route-mem minimum 58 maximum 58 - limit-resource m6route-mem minimum 8 maximum 8 - -no password strength-check -username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin -username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin -username ansible passphrase lifetime 99999 warntime 14 gracetime 3 -ip domain-lookup -ip name-server 192.168.255.1 use-vrf management -snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key -snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key -rmon event 1 log trap public description FATAL(1) owner PMON@FATAL -rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL -rmon event 3 log trap public description ERROR(3) owner PMON@ERROR -rmon event 4 log trap public description WARNING(4) owner PMON@WARNING -rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO - -vlan 1 - -vrf context management - ip route 0.0.0.0/0 192.168.255.1 - -interface Ethernet1/1 - description this is a test - shutdown - switchport access vlan 3333 - spanning-tree port type edge - -interface Ethernet1/2 - -interface Ethernet1/3 - -interface Ethernet1/4 - -interface Ethernet1/5 - -interface Ethernet1/6 - -interface Ethernet1/7 - -interface Ethernet1/8 - -interface Ethernet1/9 - -interface Ethernet1/10 - -interface Ethernet1/11 - -interface Ethernet1/12 - -interface Ethernet1/13 - -interface Ethernet1/14 - -interface Ethernet1/15 - -interface Ethernet1/16 - -interface Ethernet1/17 - -interface Ethernet1/18 - -interface Ethernet1/19 - -interface Ethernet1/20 - -interface Ethernet1/21 - -interface Ethernet1/22 - -interface Ethernet1/23 - -interface Ethernet1/24 - -interface Ethernet1/25 - -interface Ethernet1/26 - -interface Ethernet1/27 - -interface Ethernet1/28 - -interface Ethernet1/29 - -interface Ethernet1/30 - -interface Ethernet1/31 - -interface Ethernet1/32 - -interface Ethernet1/33 - -interface Ethernet1/34 - -interface Ethernet1/35 - -interface Ethernet1/36 - -interface Ethernet1/37 - -interface Ethernet1/38 - -interface Ethernet1/39 - -interface Ethernet1/40 - -interface Ethernet1/41 - -interface Ethernet1/42 - -interface Ethernet1/43 - -interface Ethernet1/44 - -interface Ethernet1/45 - -interface Ethernet1/46 - -interface Ethernet1/47 - -interface Ethernet1/48 - -interface Ethernet1/49 - -interface Ethernet1/50 - -interface Ethernet1/51 - -interface Ethernet1/52 - -interface Ethernet1/53 - -interface Ethernet1/54 - -interface Ethernet1/55 - -interface Ethernet1/56 - -interface Ethernet1/57 - -interface Ethernet1/58 - -interface Ethernet1/59 - -interface Ethernet1/60 - -interface Ethernet1/61 - -interface Ethernet1/62 - -interface Ethernet1/63 - -interface Ethernet1/64 - -interface mgmt0 - ip address dhcp - vrf member management - -interface loopback1 - description this is a test - shutdown -icam monitor scale - -line console -line vty -boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file diff --git a/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg b/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg deleted file mode 100644 index ae144d7c8..000000000 --- a/tests/integration/targets/nxos_config/backup_test_dir/appliance/backup_with_alias.cfg +++ /dev/null @@ -1,178 +0,0 @@ -!Command: show running-config -!Running configuration last done at: Thu May 12 14:13:57 2022 -!Time: Thu May 12 14:14:00 2022 - -version 9.3(8) Bios:version -hostname switch -vdc switch id 1 - limit-resource vlan minimum 16 maximum 4094 - limit-resource vrf minimum 2 maximum 4096 - limit-resource port-channel minimum 0 maximum 511 - limit-resource u4route-mem minimum 248 maximum 248 - limit-resource u6route-mem minimum 96 maximum 96 - limit-resource m4route-mem minimum 58 maximum 58 - limit-resource m6route-mem minimum 8 maximum 8 - -no password strength-check -username admin password 5 $5$MBLHBL$DfCPugh1wDgMfrNE4252uU6fVNJXSfacshXXYYaoXw4 role network-admin -username ansible password 5 $5$DNIIFL$aOVntCd1VxhDfuTBObkjlEzn38x/pRYu1RA9okx17D4 role network-admin -username ansible passphrase lifetime 99999 warntime 14 gracetime 3 -ip domain-lookup -ip name-server 192.168.255.1 use-vrf management -snmp-server user admin network-admin auth md5 37669EB8281AAACE7E50FFA0EB8CCD2B14B7 priv 364ED7E83B6EE7876E58A2B0FE89922565C4 localizedV2key -snmp-server user ansible network-admin auth md5 5232B86362E7C6412C90123D5F6AC91AE059 priv 042E985857D6BF592D893070473A884CA345 localizedV2key -rmon event 1 log trap public description FATAL(1) owner PMON@FATAL -rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL -rmon event 3 log trap public description ERROR(3) owner PMON@ERROR -rmon event 4 log trap public description WARNING(4) owner PMON@WARNING -rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO - -vlan 1 - -vrf context management - ip route 0.0.0.0/0 192.168.255.1 - -interface Ethernet1/1 - description this is a test - shutdown - switchport access vlan 3333 - spanning-tree port type edge - -interface Ethernet1/2 - -interface Ethernet1/3 - -interface Ethernet1/4 - -interface Ethernet1/5 - -interface Ethernet1/6 - -interface Ethernet1/7 - -interface Ethernet1/8 - -interface Ethernet1/9 - -interface Ethernet1/10 - -interface Ethernet1/11 - -interface Ethernet1/12 - -interface Ethernet1/13 - -interface Ethernet1/14 - -interface Ethernet1/15 - -interface Ethernet1/16 - -interface Ethernet1/17 - -interface Ethernet1/18 - -interface Ethernet1/19 - -interface Ethernet1/20 - -interface Ethernet1/21 - -interface Ethernet1/22 - -interface Ethernet1/23 - -interface Ethernet1/24 - -interface Ethernet1/25 - -interface Ethernet1/26 - -interface Ethernet1/27 - -interface Ethernet1/28 - -interface Ethernet1/29 - -interface Ethernet1/30 - -interface Ethernet1/31 - -interface Ethernet1/32 - -interface Ethernet1/33 - -interface Ethernet1/34 - -interface Ethernet1/35 - -interface Ethernet1/36 - -interface Ethernet1/37 - -interface Ethernet1/38 - -interface Ethernet1/39 - -interface Ethernet1/40 - -interface Ethernet1/41 - -interface Ethernet1/42 - -interface Ethernet1/43 - -interface Ethernet1/44 - -interface Ethernet1/45 - -interface Ethernet1/46 - -interface Ethernet1/47 - -interface Ethernet1/48 - -interface Ethernet1/49 - -interface Ethernet1/50 - -interface Ethernet1/51 - -interface Ethernet1/52 - -interface Ethernet1/53 - -interface Ethernet1/54 - -interface Ethernet1/55 - -interface Ethernet1/56 - -interface Ethernet1/57 - -interface Ethernet1/58 - -interface Ethernet1/59 - -interface Ethernet1/60 - -interface Ethernet1/61 - -interface Ethernet1/62 - -interface Ethernet1/63 - -interface Ethernet1/64 - -interface mgmt0 - ip address dhcp - vrf member management - -interface loopback1 - description this is a test - shutdown -icam monitor scale - -line console -line vty -boot nxos bootflash:/nxos.9.3.8.bin sup-1 \ No newline at end of file From 8ac62ec4af304a3f3e33f743e292644a1907ca52 Mon Sep 17 00:00:00 2001 From: Ashwini Mhatre Date: Wed, 7 Feb 2024 17:47:56 +0530 Subject: [PATCH 13/19] Update lab file as per new CML conventions --- tests/integration/labs/single.yaml | 62 ++++++++++++++++++------------ 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/tests/integration/labs/single.yaml b/tests/integration/labs/single.yaml index 1e30db32f..4ddecf528 100644 --- a/tests/integration/labs/single.yaml +++ b/tests/integration/labs/single.yaml @@ -1,15 +1,17 @@ lab: - description: "" - notes: "" - timestamp: 1651582103.0855575 + description: '' + notes: '' title: nxos test - version: 0.0.4 + version: 0.2.0 +links: + - id: l0 + n1: n0 + n2: n1 + i1: i1 + i2: i0 + label: nxos9000-0-mgmt0<->ext-conn-0-port nodes: - - id: n0 - label: nxos9000-0 - node_definition: nxosv9000 - x: -1750 - y: -250 + - boot_disk_size: null configuration: |- # workaround for booting to loader> prompt echo 'from cli import cli' > set_boot.py @@ -38,43 +40,55 @@ nodes: username ansible password ansible role network-admin interface mgmt0 ip address dhcp - image_definition: nxosv9300-9-3-8 + cpu_limit: null + cpus: null + data_volume: null + hide_links: false + id: n0 + image_definition: null + label: nxos9000-0 + node_definition: nxosv9000 + ram: null tags: [] + x: -1750 + y: -250 interfaces: - id: i0 label: Loopback0 type: loopback - id: i1 - slot: 0 label: mgmt0 + slot: 0 type: physical - id: i2 - slot: 1 label: Ethernet1/1 + slot: 1 type: physical - id: i3 - slot: 2 label: Ethernet1/2 + slot: 2 type: physical - id: i4 - slot: 3 label: Ethernet1/3 + slot: 3 type: physical - - id: n1 + - boot_disk_size: null + configuration: virbr0 + cpu_limit: null + cpus: null + data_volume: null + hide_links: false + id: n1 + image_definition: null label: ext-conn-0 node_definition: external_connector + ram: null + tags: [] x: -2250 y: -250 - configuration: virbr0 - tags: [] interfaces: - id: i0 - slot: 0 label: port + slot: 0 type: physical -links: - - id: l0 - i1: i1 - n1: n0 - i2: i0 - n2: n1 +annotations: [] \ No newline at end of file From af66a03da4245033a6787d8d672cd6c3aa9d4350 Mon Sep 17 00:00:00 2001 From: Ashwini Mhatre Date: Mon, 12 Feb 2024 12:45:49 +0530 Subject: [PATCH 14/19] Update single.yaml --- tests/integration/labs/single.yaml | 199 +++++++++++++++++++++++++---- 1 file changed, 173 insertions(+), 26 deletions(-) diff --git a/tests/integration/labs/single.yaml b/tests/integration/labs/single.yaml index 4ddecf528..753abacaf 100644 --- a/tests/integration/labs/single.yaml +++ b/tests/integration/labs/single.yaml @@ -12,34 +12,181 @@ links: label: nxos9000-0-mgmt0<->ext-conn-0-port nodes: - boot_disk_size: null - configuration: |- - # workaround for booting to loader> prompt - echo 'from cli import cli' > set_boot.py - echo 'import json' >> set_boot.py - echo 'import os' >> set_boot.py - echo 'import time' >> set_boot.py - echo 'bootimage = json.loads(cli("show version | json"))["kick_file_name"]' >> set_boot.py - echo 'set_boot = cli("conf t ; boot nxos {} ; no event manager applet BOOTCONFIG".format(bootimage))' >> set_boot.py - echo 'i = 0' >> set_boot.py - echo 'while i < 10:' >> set_boot.py - echo ' try:' >> set_boot.py - echo ' save_config = cli("copy running-config startup-config")' >> set_boot.py - echo ' break' >> set_boot.py - echo ' except Exception:' >> set_boot.py - echo ' i += 1' >> set_boot.py - echo ' time.sleep(1)' >> set_boot.py - echo 'os.remove("/bootflash/set_boot.py")' >> set_boot.py - event manager applet BOOTCONFIG - event syslog pattern "Configured from vty" - action 1.0 cli python bootflash:set_boot.py - # minimum needed config to login + configuration: |2- + + !Command: show running-config + !Running configuration last done at: Mon Feb 12 07:11:33 2024 + !Time: Mon Feb 12 07:11:33 2024 + + version 10.3(1) Bios:version + hostname R1 + vdc R1 id 1 + limit-resource vlan minimum 16 maximum 4094 + limit-resource vrf minimum 2 maximum 4096 + limit-resource port-channel minimum 0 maximum 511 + limit-resource m4route-mem minimum 58 maximum 58 + limit-resource m6route-mem minimum 8 maximum 8 + no password strength-check - username admin role network-admin - username admin password cisco role network-admin - username ansible role network-admin - username ansible password ansible role network-admin + username admin password 5 $5$AADOBF$GVXUV2cvmlZH42xDu6wnqfBpV9gXF61WGVNrGF5Gk6C role network-admin + username ansible password 5 $5$GHBNKA$8ccD8KWjmP6NzxzkIRufl7giaUWjrhAn4SRrVWYZ4R1 role network-admin + username ansible passphrase lifetime 99999 warntime 14 gracetime 3 + ssh key rsa 2048 + ip domain-lookup + snmp-server user admin network-admin auth md5 040F90283AEB9A92CCAF81F5CDA2639FFFCD priv aes-128 006084272498F8CD8F98DE888DEC6899C6D0 localizedV2key + snmp-server user ansible network-admin auth md5 5207BA419F48B4EB39149FDC00BE411BC828 priv aes-128 041EED4A876CACFD7656EA885CE15D3CE108 localizedV2key + rmon event 1 log trap public description FATAL(1) owner PMON@FATAL + rmon event 2 log trap public description CRITICAL(2) owner PMON@CRITICAL + rmon event 3 log trap public description ERROR(3) owner PMON@ERROR + rmon event 4 log trap public description WARNING(4) owner PMON@WARNING + rmon event 5 log trap public description INFORMATION(5) owner PMON@INFO + + vlan 1 + + vrf context management + ip name-server 192.168.255.1 + ip route 0.0.0.0/0 192.168.255.1 + + interface Ethernet1/1 + + interface Ethernet1/2 + + interface Ethernet1/3 + + interface Ethernet1/4 + + interface Ethernet1/5 + + interface Ethernet1/6 + + interface Ethernet1/7 + + interface Ethernet1/8 + + interface Ethernet1/9 + + interface Ethernet1/10 + + interface Ethernet1/11 + + interface Ethernet1/12 + + interface Ethernet1/13 + + interface Ethernet1/14 + + interface Ethernet1/15 + + interface Ethernet1/16 + + interface Ethernet1/17 + + interface Ethernet1/18 + + interface Ethernet1/19 + + interface Ethernet1/20 + + interface Ethernet1/21 + + interface Ethernet1/22 + + interface Ethernet1/23 + + interface Ethernet1/24 + + interface Ethernet1/25 + + interface Ethernet1/26 + + interface Ethernet1/27 + + interface Ethernet1/28 + + interface Ethernet1/29 + + interface Ethernet1/30 + + interface Ethernet1/31 + + interface Ethernet1/32 + + interface Ethernet1/33 + + interface Ethernet1/34 + + interface Ethernet1/35 + + interface Ethernet1/36 + + interface Ethernet1/37 + + interface Ethernet1/38 + + interface Ethernet1/39 + + interface Ethernet1/40 + + interface Ethernet1/41 + + interface Ethernet1/42 + + interface Ethernet1/43 + + interface Ethernet1/44 + + interface Ethernet1/45 + + interface Ethernet1/46 + + interface Ethernet1/47 + + interface Ethernet1/48 + + interface Ethernet1/49 + + interface Ethernet1/50 + + interface Ethernet1/51 + + interface Ethernet1/52 + + interface Ethernet1/53 + + interface Ethernet1/54 + + interface Ethernet1/55 + + interface Ethernet1/56 + + interface Ethernet1/57 + + interface Ethernet1/58 + + interface Ethernet1/59 + + interface Ethernet1/60 + + interface Ethernet1/61 + + interface Ethernet1/62 + + interface Ethernet1/63 + + interface Ethernet1/64 + interface mgmt0 - ip address dhcp + ip address dhcp + vrf member management + icam monitor scale + + line console + exec-timeout 0 + line vty + exec-timeout 0 + boot nxos bootflash:/nxos64-cs.10.3.1.F.bin + + no logging console cpu_limit: null cpus: null data_volume: null From b34cfbc366d33b3e4569d171fe01554810b1a147 Mon Sep 17 00:00:00 2001 From: Ashwini Mhatre Date: Thu, 7 Mar 2024 15:25:45 +0530 Subject: [PATCH 15/19] Fix requirement --- test-requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/test-requirements.txt b/test-requirements.txt index 67655f3da..b8d422aab 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -5,3 +5,4 @@ pexpect pytest-xdist yamllint coverage==4.5.4 +virl2-client==2.6.1 From c70e1b2b833f1982563c39bc1e7273a1be955fcf Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 7 Mar 2024 10:01:31 +0000 Subject: [PATCH 16/19] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- clean.py | 22 +- plugins/action/nxos.py | 21 +- plugins/cliconf/nxos.py | 114 ++++++--- plugins/httpapi/nxos.py | 20 +- .../network/nxos/argspec/acls/acls.py | 240 +++++++++++++----- .../bgp_address_family/bgp_address_family.py | 16 +- .../nxos/argspec/bgp_global/bgp_global.py | 32 ++- .../bgp_neighbor_address_family.py | 48 +++- .../argspec/bgp_templates/bgp_templates.py | 36 ++- .../argspec/fc_interfaces/fc_interfaces.py | 5 +- .../argspec/l2_interfaces/l2_interfaces.py | 8 +- .../argspec/logging_global/logging_global.py | 4 +- .../ospf_interfaces/ospf_interfaces.py | 4 +- .../network/nxos/argspec/ospfv2/ospfv2.py | 144 ++++++++--- .../network/nxos/argspec/ospfv3/ospfv3.py | 120 ++++++--- .../nxos/argspec/route_maps/route_maps.py | 92 +++++-- .../nxos/argspec/snmp_server/snmp_server.py | 28 +- .../argspec/static_routes/static_routes.py | 4 +- .../config/acl_interfaces/acl_interfaces.py | 59 ++++- .../network/nxos/config/acls/acls.py | 188 ++++++++++---- .../config/bfd_interfaces/bfd_interfaces.py | 37 ++- .../bgp_address_family/bgp_address_family.py | 34 ++- .../nxos/config/bgp_global/bgp_global.py | 35 ++- .../bgp_neighbor_address_family.py | 23 +- .../config/bgp_templates/bgp_templates.py | 26 +- .../config/fc_interfaces/fc_interfaces.py | 33 ++- .../network/nxos/config/hostname/hostname.py | 4 +- .../config/hsrp_interfaces/hsrp_interfaces.py | 31 ++- .../nxos/config/interfaces/interfaces.py | 32 ++- .../config/l2_interfaces/l2_interfaces.py | 45 +++- .../config/l3_interfaces/l3_interfaces.py | 77 ++++-- .../network/nxos/config/lacp/lacp.py | 8 +- .../config/lacp_interfaces/lacp_interfaces.py | 33 ++- .../config/lag_interfaces/lag_interfaces.py | 41 ++- .../nxos/config/lldp_global/lldp_global.py | 22 +- .../config/lldp_interfaces/lldp_interfaces.py | 33 ++- .../config/logging_global/logging_global.py | 4 +- .../nxos/config/ntp_global/ntp_global.py | 8 +- .../config/ospf_interfaces/ospf_interfaces.py | 47 +++- .../network/nxos/config/ospfv2/ospfv2.py | 44 +++- .../network/nxos/config/ospfv3/ospfv3.py | 45 +++- .../nxos/config/prefix_lists/prefix_lists.py | 28 +- .../nxos/config/route_maps/route_maps.py | 72 ++++-- .../nxos/config/snmp_server/snmp_server.py | 12 +- .../config/static_routes/static_routes.py | 33 ++- .../nxos/config/telemetry/telemetry.py | 170 +++++++++---- .../network/nxos/config/vlans/vlans.py | 13 +- .../facts/acl_interfaces/acl_interfaces.py | 12 +- .../network/nxos/facts/acls/acls.py | 37 ++- .../facts/bfd_interfaces/bfd_interfaces.py | 22 +- .../bgp_address_family/bgp_address_family.py | 20 +- .../nxos/facts/bgp_global/bgp_global.py | 16 +- .../bgp_neighbor_address_family.py | 20 +- .../nxos/facts/bgp_templates/bgp_templates.py | 24 +- .../module_utils/network/nxos/facts/facts.py | 12 +- .../nxos/facts/fc_interfaces/fc_interfaces.py | 18 +- .../network/nxos/facts/hostname/hostname.py | 12 +- .../facts/hsrp_interfaces/hsrp_interfaces.py | 12 +- .../nxos/facts/interfaces/interfaces.py | 20 +- .../nxos/facts/l2_interfaces/l2_interfaces.py | 16 +- .../nxos/facts/l3_interfaces/l3_interfaces.py | 28 +- .../network/nxos/facts/lacp/lacp.py | 12 +- .../facts/lacp_interfaces/lacp_interfaces.py | 12 +- .../facts/lag_interfaces/lag_interfaces.py | 12 +- .../network/nxos/facts/legacy/base.py | 87 +++++-- .../nxos/facts/lldp_global/lldp_global.py | 16 +- .../facts/lldp_interfaces/lldp_interfaces.py | 8 +- .../facts/logging_global/logging_global.py | 8 +- .../nxos/facts/ntp_global/ntp_global.py | 12 +- .../facts/ospf_interfaces/ospf_interfaces.py | 11 +- .../network/nxos/facts/ospfv2/ospfv2.py | 8 +- .../network/nxos/facts/ospfv3/ospfv3.py | 4 +- .../nxos/facts/prefix_lists/prefix_lists.py | 20 +- .../nxos/facts/route_maps/route_maps.py | 12 +- .../nxos/facts/snmp_server/snmp_server.py | 16 +- .../nxos/facts/static_routes/static_routes.py | 36 ++- .../network/nxos/facts/telemetry/telemetry.py | 55 ++-- .../network/nxos/facts/vlans/vlans.py | 24 +- plugins/module_utils/network/nxos/nxos.py | 124 ++++++--- .../nxos/rm_templates/bgp_address_family.py | 4 +- .../network/nxos/rm_templates/bgp_global.py | 4 +- .../bgp_neighbor_address_family.py | 4 +- .../nxos/rm_templates/bgp_templates.py | 4 +- .../nxos/rm_templates/fc_interfaces.py | 8 +- .../network/nxos/rm_templates/hostname.py | 4 +- .../nxos/rm_templates/logging_global.py | 8 +- .../network/nxos/rm_templates/ntp_global.py | 4 +- .../nxos/rm_templates/ospf_interfaces.py | 4 +- .../network/nxos/rm_templates/ospfv2.py | 9 +- .../network/nxos/rm_templates/ospfv3.py | 16 +- .../network/nxos/rm_templates/prefix_lists.py | 4 +- .../network/nxos/rm_templates/route_maps.py | 4 +- .../network/nxos/rm_templates/snmp_server.py | 4 +- .../nxos/rm_templates/static_routes.py | 4 +- .../network/nxos/utils/telemetry/telemetry.py | 36 ++- .../module_utils/network/nxos/utils/utils.py | 4 +- plugins/modules/nxos_aaa_server.py | 50 +++- plugins/modules/nxos_aaa_server_host.py | 23 +- plugins/modules/nxos_acls.py | 8 +- plugins/modules/nxos_banner.py | 5 +- plugins/modules/nxos_bfd_global.py | 4 +- plugins/modules/nxos_command.py | 12 +- plugins/modules/nxos_config.py | 24 +- plugins/modules/nxos_devicealias.py | 58 ++++- plugins/modules/nxos_evpn_global.py | 8 +- plugins/modules/nxos_evpn_vni.py | 16 +- plugins/modules/nxos_facts.py | 12 +- plugins/modules/nxos_feature.py | 9 +- plugins/modules/nxos_file_copy.py | 58 ++++- plugins/modules/nxos_gir.py | 51 +++- .../modules/nxos_gir_profile_management.py | 4 +- plugins/modules/nxos_hsrp.py | 61 +++-- plugins/modules/nxos_igmp.py | 8 +- plugins/modules/nxos_igmp_interface.py | 59 +++-- plugins/modules/nxos_igmp_snooping.py | 20 +- plugins/modules/nxos_install_os.py | 18 +- plugins/modules/nxos_lacp.py | 4 +- plugins/modules/nxos_logging.py | 86 +++++-- plugins/modules/nxos_ntp.py | 34 ++- plugins/modules/nxos_ntp_auth.py | 28 +- plugins/modules/nxos_ntp_options.py | 4 +- plugins/modules/nxos_nxapi.py | 32 ++- plugins/modules/nxos_overlay_global.py | 20 +- plugins/modules/nxos_pim.py | 8 +- plugins/modules/nxos_pim_interface.py | 77 ++++-- plugins/modules/nxos_pim_rp_address.py | 12 +- plugins/modules/nxos_ping.py | 16 +- plugins/modules/nxos_reboot.py | 8 +- plugins/modules/nxos_rollback.py | 8 +- plugins/modules/nxos_rpm.py | 45 +++- plugins/modules/nxos_snapshot.py | 22 +- plugins/modules/nxos_snmp_community.py | 4 +- plugins/modules/nxos_snmp_contact.py | 4 +- plugins/modules/nxos_snmp_host.py | 31 ++- plugins/modules/nxos_snmp_location.py | 4 +- plugins/modules/nxos_snmp_traps.py | 24 +- plugins/modules/nxos_snmp_user.py | 7 +- plugins/modules/nxos_system.py | 4 +- plugins/modules/nxos_telemetry.py | 4 +- plugins/modules/nxos_udld.py | 18 +- plugins/modules/nxos_udld_interface.py | 24 +- plugins/modules/nxos_user.py | 23 +- plugins/modules/nxos_vlans.py | 4 +- plugins/modules/nxos_vpc.py | 22 +- plugins/modules/nxos_vpc_interface.py | 19 +- plugins/modules/nxos_vrf.py | 39 ++- plugins/modules/nxos_vrf_af.py | 20 +- plugins/modules/nxos_vrf_interface.py | 12 +- plugins/modules/nxos_vrrp.py | 14 +- plugins/modules/nxos_vsan.py | 42 ++- plugins/modules/nxos_vtp_domain.py | 4 +- plugins/modules/nxos_vtp_password.py | 13 +- plugins/modules/nxos_vtp_version.py | 8 +- plugins/modules/nxos_vxlan_vtep.py | 55 +++- plugins/modules/nxos_vxlan_vtep_vni.py | 58 ++++- plugins/modules/nxos_zone_zoneset.py | 132 ++++++++-- plugins/netconf/nxos.py | 4 +- plugins/terminal/nxos.py | 19 +- pyproject.toml | 2 +- test-requirements.txt | 2 +- tests/integration/labs/single.yaml | 6 +- tests/integration/test_integration.py | 2 +- tests/unit/compat/mock.py | 4 +- tests/unit/mock/path.py | 4 +- tests/unit/mock/vault_helper.py | 4 +- tests/unit/mock/yaml_helper.py | 33 ++- tests/unit/modules/conftest.py | 17 +- .../unit/modules/network/nxos/nxos_module.py | 12 +- tests/unit/modules/network/nxos/test_nxos.py | 8 +- .../network/nxos/test_nxos_acl_interfaces.py | 32 ++- .../modules/network/nxos/test_nxos_acls.py | 48 +++- .../network/nxos/test_nxos_bfd_global.py | 16 +- .../network/nxos/test_nxos_bfd_interfaces.py | 32 ++- .../nxos/test_nxos_bgp_address_family.py | 106 ++++++-- .../network/nxos/test_nxos_bgp_global.py | 20 +- .../test_nxos_bgp_neighbor_address_family.py | 112 ++++++-- .../network/nxos/test_nxos_bgp_templates.py | 14 +- .../modules/network/nxos/test_nxos_command.py | 16 +- .../modules/network/nxos/test_nxos_config.py | 57 ++++- .../network/nxos/test_nxos_devicealias.py | 136 +++++++--- .../network/nxos/test_nxos_evpn_global.py | 8 +- .../network/nxos/test_nxos_evpn_vni.py | 8 +- .../network/nxos/test_nxos_fc_interfaces.py | 57 ++++- .../modules/network/nxos/test_nxos_feature.py | 16 +- .../network/nxos/test_nxos_hostname.py | 8 +- .../network/nxos/test_nxos_hsrp_interfaces.py | 32 ++- .../network/nxos/test_nxos_interfaces.py | 48 +++- .../network/nxos/test_nxos_l3_interfaces.py | 87 +++++-- .../network/nxos/test_nxos_lacp_interfaces.py | 12 +- .../network/nxos/test_nxos_lldp_interfaces.py | 24 +- .../network/nxos/test_nxos_logging_global.py | 42 ++- .../network/nxos/test_nxos_ntp_global.py | 20 +- .../modules/network/nxos/test_nxos_nxapi.py | 4 +- .../network/nxos/test_nxos_ospf_interfaces.py | 120 ++++++--- .../modules/network/nxos/test_nxos_ospfv2.py | 50 +++- .../modules/network/nxos/test_nxos_ospfv3.py | 86 +++++-- .../network/nxos/test_nxos_overlay_global.py | 4 +- .../modules/network/nxos/test_nxos_pim.py | 12 +- .../network/nxos/test_nxos_pim_interface.py | 11 +- .../network/nxos/test_nxos_pim_rp_address.py | 12 +- .../modules/network/nxos/test_nxos_ping.py | 24 +- .../network/nxos/test_nxos_prefix_lists.py | 16 +- .../network/nxos/test_nxos_route_maps.py | 82 ++++-- .../network/nxos/test_nxos_snmp_server.py | 112 ++++++-- .../network/nxos/test_nxos_static_routes.py | 107 ++++++-- .../modules/network/nxos/test_nxos_system.py | 8 +- .../network/nxos/test_nxos_telemetry.py | 149 ++++++++--- .../modules/network/nxos/test_nxos_user.py | 8 +- .../modules/network/nxos/test_nxos_vlans.py | 12 +- .../modules/network/nxos/test_nxos_vpc.py | 40 ++- .../network/nxos/test_nxos_vpc_interface.py | 8 +- .../modules/network/nxos/test_nxos_vrf.py | 12 +- .../modules/network/nxos/test_nxos_vrf_af.py | 32 ++- .../modules/network/nxos/test_nxos_vsan.py | 88 +++++-- .../network/nxos/test_nxos_vxlan_vtep.py | 8 +- .../network/nxos/test_nxos_vxlan_vtep_vni.py | 12 +- .../network/nxos/test_nxos_zone_zoneset.py | 64 +++-- 217 files changed, 5072 insertions(+), 1644 deletions(-) diff --git a/clean.py b/clean.py index df6a53572..184f51efe 100644 --- a/clean.py +++ b/clean.py @@ -2,16 +2,18 @@ """A test files updater.""" import logging -import ruamel.yaml from pathlib import Path from typing import OrderedDict +import ruamel.yaml + from ansiblelint.yaml_utils import FormattedYAML from ruamel.yaml import CommentedSeq from ruamel.yaml.comments import CommentedMap -from ruamel.yaml.tokens import CommentToken from ruamel.yaml.error import CommentMark +from ruamel.yaml.tokens import CommentToken + logging.basicConfig(level=logging.INFO) LOGGER = logging.getLogger(__name__) @@ -192,14 +194,16 @@ def update_include_test_case(list_of_tasks) -> bool: for idx, item in enumerate(list_of_tasks) if item.get("include", "").startswith("{{ test_case_to_run }}") or item.get("ansible.builtin.include_tasks", "").startswith( - "{{ test_case_to_run }}" + "{{ test_case_to_run }}", ) ] if not match: return False for entry in match: change_key( - list_of_tasks[entry], "include", "ansible.builtin.include_tasks" + list_of_tasks[entry], + "include", + "ansible.builtin.include_tasks", ) values = ( list_of_tasks[entry] @@ -209,13 +213,15 @@ def update_include_test_case(list_of_tasks) -> bool: ) first, var_pairs = values.split(" ", 1) list_of_tasks[entry]["ansible.builtin.include_tasks"] = first.replace( - "{{", "{{ " + "{{", + "{{ ", ).replace("}}", " }}") list_of_tasks[entry]["vars"] = {} for var_pair in var_pairs.split(" "): key, value = var_pair.split("=") list_of_tasks[entry]["vars"][key] = value.replace( - "{{", "{{ " + "{{", + "{{ ", ).replace("}}", " }}") return True @@ -294,7 +300,9 @@ def undo_set_fact_equal(list_of_tasks) -> bool: commented = True change_key( - list_of_tasks[entry], "set_fact", "ansible.builtin.set_fact" + list_of_tasks[entry], + "set_fact", + "ansible.builtin.set_fact", ) if commented: diff --git a/plugins/action/nxos.py b/plugins/action/nxos.py index e57c08aeb..79a3fce5f 100644 --- a/plugins/action/nxos.py +++ b/plugins/action/nxos.py @@ -36,7 +36,9 @@ def run(self, tmp=None, task_vars=None): del tmp # tmp no longer has any effect module_name = self._task.action.split(".")[-1] - self._config_module = True if module_name in ["nxos_config", "config"] else False + self._config_module = ( + True if module_name in ["nxos_config", "config"] else False + ) persistent_connection = self._play_context.connection.split(".")[-1] warnings = [] @@ -65,7 +67,9 @@ def run(self, tmp=None, task_vars=None): } conn = Connection(self._connection.socket_path) - persistent_command_timeout = conn.get_option("persistent_command_timeout") + persistent_command_timeout = conn.get_option( + "persistent_command_timeout" + ) file_pull = self._task.args.get("file_pull", False) file_pull_timeout = self._task.args.get("file_pull_timeout") connect_ssh_port = self._task.args.get("connect_ssh_port", 22) @@ -73,7 +77,9 @@ def run(self, tmp=None, task_vars=None): if file_pull: # if file_pull_timeout is explicitly set, use that if file_pull_timeout: - conn.set_option("persistent_command_timeout", file_pull_timeout) + conn.set_option( + "persistent_command_timeout", file_pull_timeout + ) # if file_pull_timeout is not set and command_timeout < 300s, bump to 300s. elif persistent_command_timeout < 300: conn.set_option("persistent_command_timeout", 300) @@ -96,8 +102,13 @@ def run(self, tmp=None, task_vars=None): f"PERSISTENT_CONNECT_TIMEOUT is %s {persistent_connect_timeout}", self._play_context.remote_addr, ) - if persistent_command_timeout < 600 or persistent_connect_timeout < 600: - msg = "PERSISTENT_COMMAND_TIMEOUT and PERSISTENT_CONNECT_TIMEOUT" + if ( + persistent_command_timeout < 600 + or persistent_connect_timeout < 600 + ): + msg = ( + "PERSISTENT_COMMAND_TIMEOUT and PERSISTENT_CONNECT_TIMEOUT" + ) msg += " must be set to 600 seconds or higher when using nxos_install_os module." msg += " Current persistent_command_timeout setting:" + str( persistent_command_timeout, diff --git a/plugins/cliconf/nxos.py b/plugins/cliconf/nxos.py index 4f6393858..860537f8e 100644 --- a/plugins/cliconf/nxos.py +++ b/plugins/cliconf/nxos.py @@ -55,8 +55,12 @@ NetworkConfig, dumps, ) -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list -from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import CliconfBase +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, +) +from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import ( + CliconfBase, +) class Cliconf(CliconfBase): @@ -84,28 +88,42 @@ def get_device_info(self): reply = self.get("show version") platform_reply = self.get("show inventory") - match_sys_ver = re.search(r"\s+system:\s+version\s*(\S+)", reply, re.M) + match_sys_ver = re.search( + r"\s+system:\s+version\s*(\S+)", reply, re.M + ) if match_sys_ver: device_info["network_os_version"] = match_sys_ver.group(1) else: - match_kick_ver = re.search(r"\s+kickstart:\s+version\s*(\S+)", reply, re.M) + match_kick_ver = re.search( + r"\s+kickstart:\s+version\s*(\S+)", reply, re.M + ) if match_kick_ver: device_info["network_os_version"] = match_kick_ver.group(1) if "network_os_version" not in device_info: - match_sys_ver = re.search(r"\s+NXOS:\s+version\s*(\S+)", reply, re.M) + match_sys_ver = re.search( + r"\s+NXOS:\s+version\s*(\S+)", reply, re.M + ) if match_sys_ver: device_info["network_os_version"] = match_sys_ver.group(1) - match_chassis_id = re.search(r"Hardware\n\s+cisco(.+)$", reply, re.M) + match_chassis_id = re.search( + r"Hardware\n\s+cisco(.+)$", reply, re.M + ) if match_chassis_id: - device_info["network_os_model"] = match_chassis_id.group(1).strip() + device_info["network_os_model"] = match_chassis_id.group( + 1 + ).strip() - match_host_name = re.search(r"\s+Device name:\s*(\S+)", reply, re.M) + match_host_name = re.search( + r"\s+Device name:\s*(\S+)", reply, re.M + ) if match_host_name: device_info["network_os_hostname"] = match_host_name.group(1) - match_isan_file_name = re.search(r"\s+system image file is:\s*(\S+)", reply, re.M) + match_isan_file_name = re.search( + r"\s+system image file is:\s*(\S+)", reply, re.M + ) if match_isan_file_name: device_info["network_os_image"] = match_isan_file_name.group(1) else: @@ -115,12 +133,18 @@ def get_device_info(self): re.M, ) if match_kick_file_name: - device_info["network_os_image"] = match_kick_file_name.group(1) + device_info[ + "network_os_image" + ] = match_kick_file_name.group(1) if "network_os_image" not in device_info: - match_isan_file_name = re.search(r"\s+NXOS image file is:\s*(\S+)", reply, re.M) + match_isan_file_name = re.search( + r"\s+NXOS image file is:\s*(\S+)", reply, re.M + ) if match_isan_file_name: - device_info["network_os_image"] = match_isan_file_name.group(1) + device_info[ + "network_os_image" + ] = match_isan_file_name.group(1) match_os_platform = re.search( r'NAME: "Chassis",\s*DESCR:.*\nPID:\s*(\S+)', @@ -148,7 +172,9 @@ def get_diff( option_values = self.get_option_values() if candidate is None and device_operations["supports_generate_diff"]: - raise ValueError("candidate configuration is required to generate diff") + raise ValueError( + "candidate configuration is required to generate diff" + ) if diff_match not in option_values["diff_match"]: raise ValueError( @@ -168,7 +194,9 @@ def get_diff( if running and diff_match != "none" and diff_replace != "config": # running configuration - running_obj = NetworkConfig(indent=2, contents=running, ignore_lines=diff_ignore_lines) + running_obj = NetworkConfig( + indent=2, contents=running, ignore_lines=diff_ignore_lines + ) configdiffobjs = candidate_obj.difference( running_obj, path=path, @@ -179,7 +207,9 @@ def get_diff( else: configdiffobjs = candidate_obj.items - diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else "" + diff["config_diff"] = ( + dumps(configdiffobjs, "commands") if configdiffobjs else "" + ) return diff def get_config(self, source="running", flags=None, format="text"): @@ -192,7 +222,9 @@ def get_config(self, source="running", flags=None, format="text"): lookup = {"running": "running-config", "startup": "startup-config"} if source not in lookup: - raise ValueError("fetching configuration from %s is not supported" % source) + raise ValueError( + "fetching configuration from %s is not supported" % source + ) cmd = "show {0} ".format(lookup[source]) if format and format != "text": @@ -204,10 +236,14 @@ def get_config(self, source="running", flags=None, format="text"): return self.send_command(cmd) - def edit_config(self, candidate=None, commit=True, replace=None, comment=None): + def edit_config( + self, candidate=None, commit=True, replace=None, comment=None + ): resp = {} operations = self.get_device_operations() - self.check_edit_config_capability(operations, candidate, commit, replace, comment) + self.check_edit_config_capability( + operations, candidate, commit, replace, comment + ) results = [] requests = [] @@ -269,7 +305,9 @@ def run_commands(self, commands=None, check_rc=True): output = cmd.pop("output", None) if output: - cmd["command"] = self._get_command_with_output(cmd["command"], output) + cmd["command"] = self._get_command_with_output( + cmd["command"], output + ) try: out = self.send_command(**cmd) @@ -283,7 +321,8 @@ def run_commands(self, commands=None, check_rc=True): out = to_text(out, errors="surrogate_or_strict").strip() except UnicodeError: raise ConnectionError( - message="Failed to decode output from %s: %s" % (cmd, to_text(out)), + message="Failed to decode output from %s: %s" + % (cmd, to_text(out)), ) try: @@ -336,11 +375,15 @@ def pull_file(self, command, remotepassword=None): re.compile(rb"(?i)Could not resolve hostname"), re.compile(rb"(?i)Too many authentication failures"), re.compile(rb"Access Denied"), - re.compile(rb"(?i)Copying to\/from this server name is not permitted"), + re.compile( + rb"(?i)Copying to\/from this server name is not permitted" + ), ] # set error regex for copy command - current_stderr_re = self._connection._get_terminal_std_re("terminal_stderr_re") + current_stderr_re = self._connection._get_terminal_std_re( + "terminal_stderr_re" + ) current_stderr_re.extend(possible_errors_re) # do not change the ordering of this list @@ -352,7 +395,9 @@ def pull_file(self, command, remotepassword=None): # set stdout regex for copy command to handle optional user prompts # based on different match conditions - current_stdout_re = self._connection._get_terminal_std_re("terminal_stdout_re") + current_stdout_re = self._connection._get_terminal_std_re( + "terminal_stdout_re" + ) current_stdout_re.extend(possible_prompts_re) retry = 1 @@ -367,10 +412,14 @@ def pull_file(self, command, remotepassword=None): output = self.send_command(command="y", strip_prompt=False) if possible_prompts_re[1].search(to_bytes(output)): - output = self.send_command(command="yes", strip_prompt=False) + output = self.send_command( + command="yes", strip_prompt=False + ) if possible_prompts_re[2].search(to_bytes(output)): - output = self.send_command(command=remotepassword, strip_prompt=False) + output = self.send_command( + command=remotepassword, strip_prompt=False + ) if "Copy complete" in output: file_pulled = True return file_pulled @@ -391,13 +440,18 @@ def set_cli_prompt_context(self): if out is None: raise AnsibleConnectionFailure( message="cli prompt is not identified from the last received" - " response window: %s" % self._connection._last_recv_window, + " response window: %s" + % self._connection._last_recv_window, ) # Match prompts ending in )# except those with (maint-mode)# config_prompt = re.compile(r"^.*\((?!maint-mode).*\)#$") - while config_prompt.match(to_text(out, errors="surrogate_then_replace").strip()): - self._connection.queue_message("vvvv", "wrong context, sending exit to device") + while config_prompt.match( + to_text(out, errors="surrogate_then_replace").strip() + ): + self._connection.queue_message( + "vvvv", "wrong context, sending exit to device" + ) self._connection.send_command("exit") out = self._connection.get_prompt() @@ -410,7 +464,9 @@ def _get_command_with_output(self, command, output): % (output, ",".join(options_values["output"])), ) - if output in ["json", "json-pretty"] and not re.search(output_re, command): + if output in ["json", "json-pretty"] and not re.search( + output_re, command + ): device_info = self.get_device_info() model = device_info.get("network_os_model", "") platform = device_info.get("network_os_platform", "") diff --git a/plugins/httpapi/nxos.py b/plugins/httpapi/nxos.py index 57421e835..aaf82f6bf 100644 --- a/plugins/httpapi/nxos.py +++ b/plugins/httpapi/nxos.py @@ -22,8 +22,12 @@ from ansible.module_utils._text import to_text from ansible.module_utils.connection import ConnectionError -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list -from ansible_collections.ansible.netcommon.plugins.plugin_utils.httpapi_base import HttpApiBase +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, +) +from ansible_collections.ansible.netcommon.plugins.plugin_utils.httpapi_base import ( + HttpApiBase, +) OPTIONS = { @@ -105,7 +109,9 @@ def _run_queue(self, queue, output): response_data = json.loads(to_text(response_data.getvalue())) except ValueError: raise ConnectionError( - "Response was not valid JSON, got {0}".format(to_text(response_data.getvalue())), + "Response was not valid JSON, got {0}".format( + to_text(response_data.getvalue()) + ), ) results = handle_response(response_data) @@ -118,7 +124,9 @@ def get_device_info(self): device_info = {} device_info["network_os"] = "nxos" - reply, platform_reply = self.send_request(["show version", "show inventory"]) + reply, platform_reply = self.send_request( + ["show version", "show inventory"] + ) find_os_version = [ r"\s+system:\s+version\s*(\S+)", @@ -131,7 +139,9 @@ def get_device_info(self): device_info["network_os_version"] = match_ver.group(1) break - match_chassis_id = re.search(r"Hardware\n\s+cisco\s*(\S+\s+\S+)", reply, re.M) + match_chassis_id = re.search( + r"Hardware\n\s+cisco\s*(\S+\s+\S+)", reply, re.M + ) if match_chassis_id: device_info["network_os_model"] = match_chassis_id.group(1) diff --git a/plugins/module_utils/network/nxos/argspec/acls/acls.py b/plugins/module_utils/network/nxos/argspec/acls/acls.py index 3618248b7..297072f23 100644 --- a/plugins/module_utils/network/nxos/argspec/acls/acls.py +++ b/plugins/module_utils/network/nxos/argspec/acls/acls.py @@ -76,9 +76,13 @@ class AclsArgs(object): # pylint: disable=R0903 "range": { "options": { "end": {"type": "str"}, - "start": {"type": "str"}, + "start": { + "type": "str" + }, }, - "required_together": [["start", "end"]], + "required_together": [ + ["start", "end"] + ], "type": "dict", }, }, @@ -87,7 +91,9 @@ class AclsArgs(object): # pylint: disable=R0903 "prefix": {"type": "str"}, "wildcard_bits": {"type": "str"}, }, - "required_together": [["address", "wildcard_bits"]], + "required_together": [ + ["address", "wildcard_bits"] + ], "type": "dict", }, "dscp": {"type": "str"}, @@ -100,82 +106,178 @@ class AclsArgs(object): # pylint: disable=R0903 "precedence": {"type": "str"}, "protocol": {"type": "str"}, "protocol_options": { - "mutually_exclusive": [["icmp", "igmp", "tcp"]], + "mutually_exclusive": [ + ["icmp", "igmp", "tcp"] + ], "options": { "icmp": { "options": { - "administratively_prohibited": {"type": "bool"}, - "alternate_address": {"type": "bool"}, - "conversion_error": {"type": "bool"}, - "dod_host_prohibited": {"type": "bool"}, - "dod_net_prohibited": {"type": "bool"}, + "administratively_prohibited": { + "type": "bool" + }, + "alternate_address": { + "type": "bool" + }, + "conversion_error": { + "type": "bool" + }, + "dod_host_prohibited": { + "type": "bool" + }, + "dod_net_prohibited": { + "type": "bool" + }, "echo": {"type": "bool"}, "echo_reply": {"type": "bool"}, - "echo_request": {"type": "bool"}, - "general_parameter_problem": {"type": "bool"}, - "host_isolated": {"type": "bool"}, - "host_precedence_unreachable": {"type": "bool"}, - "host_redirect": {"type": "bool"}, - "host_tos_redirect": {"type": "bool"}, - "host_tos_unreachable": {"type": "bool"}, - "host_unknown": {"type": "bool"}, - "host_unreachable": {"type": "bool"}, - "information_reply": {"type": "bool"}, - "information_request": {"type": "bool"}, + "echo_request": { + "type": "bool" + }, + "general_parameter_problem": { + "type": "bool" + }, + "host_isolated": { + "type": "bool" + }, + "host_precedence_unreachable": { + "type": "bool" + }, + "host_redirect": { + "type": "bool" + }, + "host_tos_redirect": { + "type": "bool" + }, + "host_tos_unreachable": { + "type": "bool" + }, + "host_unknown": { + "type": "bool" + }, + "host_unreachable": { + "type": "bool" + }, + "information_reply": { + "type": "bool" + }, + "information_request": { + "type": "bool" + }, "mask_reply": {"type": "bool"}, - "mask_request": {"type": "bool"}, - "message_code": {"type": "int"}, - "message_type": {"type": "int"}, - "mobile_redirect": {"type": "bool"}, - "net_redirect": {"type": "bool"}, - "net_tos_redirect": {"type": "bool"}, - "net_tos_unreachable": {"type": "bool"}, - "net_unreachable": {"type": "bool"}, - "network_unknown": {"type": "bool"}, - "no_room_for_option": {"type": "bool"}, - "option_missing": {"type": "bool"}, - "packet_too_big": {"type": "bool"}, - "parameter_problem": {"type": "bool"}, - "port_unreachable": {"type": "bool"}, - "precedence_unreachable": {"type": "bool"}, - "protocol_unreachable": {"type": "bool"}, - "reassembly_timeout": {"type": "bool"}, + "mask_request": { + "type": "bool" + }, + "message_code": { + "type": "int" + }, + "message_type": { + "type": "int" + }, + "mobile_redirect": { + "type": "bool" + }, + "net_redirect": { + "type": "bool" + }, + "net_tos_redirect": { + "type": "bool" + }, + "net_tos_unreachable": { + "type": "bool" + }, + "net_unreachable": { + "type": "bool" + }, + "network_unknown": { + "type": "bool" + }, + "no_room_for_option": { + "type": "bool" + }, + "option_missing": { + "type": "bool" + }, + "packet_too_big": { + "type": "bool" + }, + "parameter_problem": { + "type": "bool" + }, + "port_unreachable": { + "type": "bool" + }, + "precedence_unreachable": { + "type": "bool" + }, + "protocol_unreachable": { + "type": "bool" + }, + "reassembly_timeout": { + "type": "bool" + }, "redirect": {"type": "bool"}, - "router_advertisement": {"type": "bool"}, - "router_solicitation": {"type": "bool"}, - "source_quench": {"type": "bool"}, - "source_route_failed": {"type": "bool"}, - "time_exceeded": {"type": "bool"}, - "timestamp_reply": {"type": "bool"}, - "timestamp_request": {"type": "bool"}, + "router_advertisement": { + "type": "bool" + }, + "router_solicitation": { + "type": "bool" + }, + "source_quench": { + "type": "bool" + }, + "source_route_failed": { + "type": "bool" + }, + "time_exceeded": { + "type": "bool" + }, + "timestamp_reply": { + "type": "bool" + }, + "timestamp_request": { + "type": "bool" + }, "traceroute": {"type": "bool"}, - "ttl_exceeded": {"type": "bool"}, - "unreachable": {"type": "bool"}, + "ttl_exceeded": { + "type": "bool" + }, + "unreachable": { + "type": "bool" + }, }, "type": "dict", }, "icmpv6": { "type": "dict", "options": { - "beyond_scope": {"type": "bool"}, + "beyond_scope": { + "type": "bool" + }, "destination_unreachable": { "type": "bool", }, "echo_reply": {"type": "bool"}, - "echo_request": {"type": "bool"}, + "echo_request": { + "type": "bool" + }, "fragments": {"type": "bool"}, "header": {"type": "bool"}, "hop_limit": {"type": "bool"}, "mld_query": {"type": "bool"}, - "mld_reduction": {"type": "bool"}, + "mld_reduction": { + "type": "bool" + }, "mld_report": {"type": "bool"}, "mldv2": {"type": "bool"}, "nd_na": {"type": "bool"}, "nd_ns": {"type": "bool"}, - "next_header": {"type": "bool"}, + "next_header": { + "type": "bool" + }, "no_admin": {"type": "bool"}, "no_route": {"type": "bool"}, - "packet_too_big": {"type": "bool"}, + "packet_too_big": { + "type": "bool" + }, "parameter_option": { "type": "bool", }, @@ -188,8 +290,12 @@ class AclsArgs(object): # pylint: disable=R0903 "reassembly_timeout": { "type": "bool", }, - "renum_command": {"type": "bool"}, - "renum_result": {"type": "bool"}, + "renum_command": { + "type": "bool" + }, + "renum_result": { + "type": "bool" + }, "renum_seq_number": { "type": "bool", }, @@ -202,9 +308,15 @@ class AclsArgs(object): # pylint: disable=R0903 "router_solicitation": { "type": "bool", }, - "time_exceeded": {"type": "bool"}, - "unreachable": {"type": "bool"}, - "telemetry_path": {"type": "bool"}, + "time_exceeded": { + "type": "bool" + }, + "unreachable": { + "type": "bool" + }, + "telemetry_path": { + "type": "bool" + }, "telemetry_queue": { "type": "bool", }, @@ -221,14 +333,18 @@ class AclsArgs(object): # pylint: disable=R0903 "options": { "dvmrp": {"type": "bool"}, "host_query": {"type": "bool"}, - "host_report": {"type": "bool"}, + "host_report": { + "type": "bool" + }, }, "type": "dict", }, "tcp": { "options": { "ack": {"type": "bool"}, - "established": {"type": "bool"}, + "established": { + "type": "bool" + }, "fin": {"type": "bool"}, "psh": {"type": "bool"}, "rst": {"type": "bool"}, @@ -269,7 +385,9 @@ class AclsArgs(object): # pylint: disable=R0903 "range": { "options": { "end": {"type": "str"}, - "start": {"type": "str"}, + "start": { + "type": "str" + }, }, "type": "dict", }, @@ -279,7 +397,9 @@ class AclsArgs(object): # pylint: disable=R0903 "prefix": {"type": "str"}, "wildcard_bits": {"type": "str"}, }, - "required_together": [["address", "wildcard_bits"]], + "required_together": [ + ["address", "wildcard_bits"] + ], "type": "dict", }, }, diff --git a/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py b/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py index f77843d79..f8e5b7188 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py @@ -135,19 +135,27 @@ class Bgp_address_familyArgs(object): # pylint: disable=R0903 "parallel_paths": {"type": "int"}, "ibgp": { "type": "dict", - "options": {"parallel_paths": {"type": "int"}}, + "options": { + "parallel_paths": {"type": "int"} + }, }, "eibgp": { "type": "dict", - "options": {"parallel_paths": {"type": "int"}}, + "options": { + "parallel_paths": {"type": "int"} + }, }, "local": { "type": "dict", - "options": {"parallel_paths": {"type": "int"}}, + "options": { + "parallel_paths": {"type": "int"} + }, }, "mixed": { "type": "dict", - "options": {"parallel_paths": {"type": "int"}}, + "options": { + "parallel_paths": {"type": "int"} + }, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py b/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py index 3f17ccebc..041965148 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py @@ -144,7 +144,9 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "tx_interval": {"type": "int"}, - "min_rx_interval": {"type": "int"}, + "min_rx_interval": { + "type": "int" + }, "multiplier": {"type": "int"}, }, }, @@ -159,7 +161,9 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "bmp_activate_server": {"type": "int"}, "capability": { "type": "dict", - "options": {"suppress_4_byte_as": {"type": "bool"}}, + "options": { + "suppress_4_byte_as": {"type": "bool"} + }, }, "description": {"type": "str"}, "disable_connected_check": {"type": "bool"}, @@ -274,7 +278,9 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 }, "nexthop": { "type": "dict", - "options": {"suppress_default_resolution": {"type": "bool"}}, + "options": { + "suppress_default_resolution": {"type": "bool"} + }, }, "rd": { "type": "dict", @@ -379,9 +385,15 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "interval": { "type": "dict", "options": { - "tx_interval": {"type": "int"}, - "min_rx_interval": {"type": "int"}, - "multiplier": {"type": "int"}, + "tx_interval": { + "type": "int" + }, + "min_rx_interval": { + "type": "int" + }, + "multiplier": { + "type": "int" + }, }, }, }, @@ -395,7 +407,9 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "bmp_activate_server": {"type": "int"}, "capability": { "type": "dict", - "options": {"suppress_4_byte_as": {"type": "bool"}}, + "options": { + "suppress_4_byte_as": {"type": "bool"} + }, }, "description": {"type": "str"}, "disable_connected_check": {"type": "bool"}, @@ -493,7 +507,9 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "options": { "connection_mode": { "type": "dict", - "options": {"passive": {"type": "bool"}}, + "options": { + "passive": {"type": "bool"} + }, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py index 397acb1f4..f1a91cc5a 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py @@ -137,7 +137,9 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "max_prefix_limit": {"type": "int"}, - "generate_warning_threshold": {"type": "int"}, + "generate_warning_threshold": { + "type": "int" + }, "restart_interval": {"type": "int"}, "warning_only": {"type": "bool"}, }, @@ -243,15 +245,21 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "required": True, }, "exist_map": {"type": "str"}, - "non_exist_map": {"type": "str"}, + "non_exist_map": { + "type": "str" + }, }, }, - "advertisement_interval": {"type": "int"}, + "advertisement_interval": { + "type": "int" + }, "allowas_in": { "type": "dict", "options": { "set": {"type": "bool"}, - "max_occurences": {"type": "int"}, + "max_occurences": { + "type": "int" + }, }, }, "as_override": {"type": "bool"}, @@ -286,7 +294,9 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "route_map": {"type": "str"}, }, }, - "disable_peer_as_check": {"type": "bool"}, + "disable_peer_as_check": { + "type": "bool" + }, "filter_list": { "type": "dict", "options": { @@ -304,10 +314,18 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "maximum_prefix": { "type": "dict", "options": { - "max_prefix_limit": {"type": "int"}, - "generate_warning_threshold": {"type": "int"}, - "restart_interval": {"type": "int"}, - "warning_only": {"type": "bool"}, + "max_prefix_limit": { + "type": "int" + }, + "generate_warning_threshold": { + "type": "int" + }, + "restart_interval": { + "type": "int" + }, + "warning_only": { + "type": "bool" + }, }, }, "next_hop_self": { @@ -317,7 +335,9 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "all_routes": {"type": "bool"}, }, }, - "next_hop_third_party": {"type": "bool"}, + "next_hop_third_party": { + "type": "bool" + }, "prefix_list": { "type": "dict", "options": { @@ -325,7 +345,9 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "outbound": {"type": "str"}, }, }, - "rewrite_evpn_rt_asn": {"type": "bool"}, + "rewrite_evpn_rt_asn": { + "type": "bool" + }, "rewrite_rt_asn": {"type": "bool"}, "route_map": { "type": "dict", @@ -334,7 +356,9 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "outbound": {"type": "str"}, }, }, - "route_reflector_client": {"type": "bool"}, + "route_reflector_client": { + "type": "bool" + }, "send_community": { "type": "dict", "options": { diff --git a/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py b/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py index 22a6666e5..a7eec977a 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py @@ -58,7 +58,12 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 }, "safi": { "type": "str", - "choices": ["unicast", "multicast", "mvpn", "evpn"], + "choices": [ + "unicast", + "multicast", + "mvpn", + "evpn", + ], }, "advertise_map": { "type": "dict", @@ -121,7 +126,9 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 }, "inherit": { "type": "dict", - "options": {"peer_policy": {"type": "str"}}, + "options": { + "peer_policy": {"type": "str"} + }, }, "maximum_prefix": { "type": "dict", @@ -159,7 +166,11 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 "route_reflector_client": {"type": "bool"}, "send_community": { "type": "str", - "choices": ["standard", "extended", "both"], + "choices": [ + "standard", + "extended", + "both", + ], }, "soft_reconfiguration_inbound": { "type": "dict", @@ -186,12 +197,18 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 "interval": { "type": "dict", "options": { - "tx_interval": {"type": "int", "required": True}, + "tx_interval": { + "type": "int", + "required": True, + }, "min_rx_interval": { "type": "int", "required": True, }, - "multiplier": {"type": "int", "required": True}, + "multiplier": { + "type": "int", + "required": True, + }, }, }, }, @@ -201,7 +218,9 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 "bmp_activate_server": {"type": "int"}, "capability": { "type": "dict", - "options": {"suppress_4_byte_as": {"type": "bool"}}, + "options": { + "suppress_4_byte_as": {"type": "bool"} + }, }, "description": {"type": "str"}, "disable_connected_check": {"type": "bool"}, @@ -251,7 +270,10 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 "options": { "action": { "type": "str", - "choices": ["discard", "treat-as-withdraw"], + "choices": [ + "discard", + "treat-as-withdraw", + ], }, "type": {"type": "int"}, "range": { diff --git a/plugins/module_utils/network/nxos/argspec/fc_interfaces/fc_interfaces.py b/plugins/module_utils/network/nxos/argspec/fc_interfaces/fc_interfaces.py index 5a58d99e0..a3db145d0 100644 --- a/plugins/module_utils/network/nxos/argspec/fc_interfaces/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/argspec/fc_interfaces/fc_interfaces.py @@ -53,7 +53,10 @@ class Fc_interfacesArgs(object): # pylint: disable=R0903 "choices": allowed_port_modes, "type": "str", }, - "trunk_mode": {"choices": ["auto", "on", "off"], "type": "str"}, + "trunk_mode": { + "choices": ["auto", "on", "off"], + "type": "str", + }, "analytics": { "choices": ["fc-scsi", "fc-nvme", "fc-all"], "type": "str", diff --git a/plugins/module_utils/network/nxos/argspec/l2_interfaces/l2_interfaces.py b/plugins/module_utils/network/nxos/argspec/l2_interfaces/l2_interfaces.py index 046511c72..dccf67240 100644 --- a/plugins/module_utils/network/nxos/argspec/l2_interfaces/l2_interfaces.py +++ b/plugins/module_utils/network/nxos/argspec/l2_interfaces/l2_interfaces.py @@ -44,7 +44,13 @@ class L2_interfacesArgs(object): # pylint: disable=R0903 }, "mode": { "type": "str", - "choices": ["access", "dot1q-tunnel", "trunk", "fex-fabric", "fabricpath"], + "choices": [ + "access", + "dot1q-tunnel", + "trunk", + "fex-fabric", + "fabricpath", + ], }, "name": {"required": True, "type": "str"}, "trunk": { diff --git a/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py b/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py index 58a9052f1..45cf32a6e 100644 --- a/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py +++ b/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py @@ -246,7 +246,9 @@ class Logging_globalArgs(object): # pylint: disable=R0903 "options": { "trustpoint": { "type": "dict", - "options": {"client_identity": {"type": "str"}}, + "options": { + "client_identity": {"type": "str"} + }, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py b/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py index 30d65035f..c3b400a2a 100644 --- a/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py @@ -41,7 +41,9 @@ class Ospf_interfacesArgs(object): # pylint: disable=R0903 "address_family": { "type": "list", "elements": "dict", - "mutually_exclusive": [["passive_interface", "default_passive_interface"]], + "mutually_exclusive": [ + ["passive_interface", "default_passive_interface"] + ], "options": { "afi": { "type": "str", diff --git a/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py b/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py index 2e5e62f12..193c6244a 100644 --- a/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py +++ b/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py @@ -81,18 +81,28 @@ class Ospfv2Args(object): # pylint: disable=R0903 }, "nssa": { "options": { - "default_information_originate": {"type": "bool"}, + "default_information_originate": { + "type": "bool" + }, "no_redistribution": {"type": "bool"}, "no_summary": {"type": "bool"}, "set": {"type": "bool"}, "translate": { "options": { "type7": { - "mutually_exclusive": [["always", "never"]], + "mutually_exclusive": [ + ["always", "never"] + ], "options": { - "always": {"type": "bool"}, - "never": {"type": "bool"}, - "supress_fa": {"type": "bool"}, + "always": { + "type": "bool" + }, + "never": { + "type": "bool" + }, + "supress_fa": { + "type": "bool" + }, }, "type": "dict", }, @@ -191,7 +201,9 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "external_lsa": { "options": { - "max_metric_value": {"type": "int"}, + "max_metric_value": { + "type": "int" + }, "set": {"type": "bool"}, }, "type": "dict", @@ -200,7 +212,9 @@ class Ospfv2Args(object): # pylint: disable=R0903 "on_startup": { "options": { "set": {"type": "bool"}, - "wait_for_bgp_asn": {"type": "int"}, + "wait_for_bgp_asn": { + "type": "int" + }, "wait_period": {"type": "int"}, }, "type": "dict", @@ -208,7 +222,9 @@ class Ospfv2Args(object): # pylint: disable=R0903 "set": {"type": "bool"}, "summary_lsa": { "options": { - "max_metric_value": {"type": "int"}, + "max_metric_value": { + "type": "int" + }, "set": {"type": "bool"}, }, "type": "dict", @@ -227,7 +243,9 @@ class Ospfv2Args(object): # pylint: disable=R0903 "areas": { "type": "list", "elements": "dict", - "options": {"area_id": {"type": "str"}}, + "options": { + "area_id": {"type": "str"} + }, }, "multicast_intact": {"type": "bool"}, "router_id": {"type": "str"}, @@ -293,17 +311,29 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "lsa": { "options": { - "hold_interval": {"type": "int"}, - "max_interval": {"type": "int"}, - "start_interval": {"type": "int"}, + "hold_interval": { + "type": "int" + }, + "max_interval": { + "type": "int" + }, + "start_interval": { + "type": "int" + }, }, "type": "dict", }, "spf": { "options": { - "initial_spf_delay": {"type": "int"}, - "max_wait_time": {"type": "int"}, - "min_hold_time": {"type": "int"}, + "initial_spf_delay": { + "type": "int" + }, + "max_wait_time": { + "type": "int" + }, + "min_hold_time": { + "type": "int" + }, }, "type": "dict", }, @@ -336,7 +366,9 @@ class Ospfv2Args(object): # pylint: disable=R0903 "authentication": { "options": { "set": {"type": "bool"}, - "message_digest": {"type": "bool"}, + "message_digest": { + "type": "bool" + }, }, "type": "dict", }, @@ -358,8 +390,12 @@ class Ospfv2Args(object): # pylint: disable=R0903 }, "nssa": { "options": { - "default_information_originate": {"type": "bool"}, - "no_redistribution": {"type": "bool"}, + "default_information_originate": { + "type": "bool" + }, + "no_redistribution": { + "type": "bool" + }, "no_summary": {"type": "bool"}, "set": {"type": "bool"}, "translate": { @@ -372,9 +408,15 @@ class Ospfv2Args(object): # pylint: disable=R0903 ], ], "options": { - "always": {"type": "bool"}, - "never": {"type": "bool"}, - "supress_fa": {"type": "bool"}, + "always": { + "type": "bool" + }, + "never": { + "type": "bool" + }, + "supress_fa": { + "type": "bool" + }, }, "type": "dict", }, @@ -388,7 +430,9 @@ class Ospfv2Args(object): # pylint: disable=R0903 "elements": "dict", "options": { "cost": {"type": "int"}, - "not_advertise": {"type": "bool"}, + "not_advertise": { + "type": "bool" + }, "prefix": { "type": "str", "required": True, @@ -484,25 +528,41 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "external_lsa": { "options": { - "max_metric_value": {"type": "int"}, - "set": {"type": "bool"}, + "max_metric_value": { + "type": "int" + }, + "set": { + "type": "bool" + }, }, "type": "dict", }, - "include_stub": {"type": "bool"}, + "include_stub": { + "type": "bool" + }, "on_startup": { "options": { - "set": {"type": "bool"}, - "wait_for_bgp_asn": {"type": "int"}, - "wait_period": {"type": "int"}, + "set": { + "type": "bool" + }, + "wait_for_bgp_asn": { + "type": "int" + }, + "wait_period": { + "type": "int" + }, }, "type": "dict", }, "set": {"type": "bool"}, "summary_lsa": { "options": { - "max_metric_value": {"type": "int"}, - "set": {"type": "bool"}, + "max_metric_value": { + "type": "int" + }, + "set": { + "type": "bool" + }, }, "type": "dict", }, @@ -576,17 +636,29 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "lsa": { "options": { - "hold_interval": {"type": "int"}, - "max_interval": {"type": "int"}, - "start_interval": {"type": "int"}, + "hold_interval": { + "type": "int" + }, + "max_interval": { + "type": "int" + }, + "start_interval": { + "type": "int" + }, }, "type": "dict", }, "spf": { "options": { - "initial_spf_delay": {"type": "int"}, - "max_wait_time": {"type": "int"}, - "min_hold_time": {"type": "int"}, + "initial_spf_delay": { + "type": "int" + }, + "max_wait_time": { + "type": "int" + }, + "min_hold_time": { + "type": "int" + }, }, "type": "dict", }, diff --git a/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py b/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py index 601bb618f..0854a62dc 100644 --- a/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py +++ b/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py @@ -84,7 +84,9 @@ class Ospfv3Args(object): # pylint: disable=R0903 "required": True, }, "cost": {"type": "int"}, - "not_advertise": {"type": "bool"}, + "not_advertise": { + "type": "bool" + }, }, }, }, @@ -160,9 +162,15 @@ class Ospfv3Args(object): # pylint: disable=R0903 "spf": { "type": "dict", "options": { - "initial_spf_delay": {"type": "int"}, - "min_hold_time": {"type": "int"}, - "max_wait_time": {"type": "int"}, + "initial_spf_delay": { + "type": "int" + }, + "min_hold_time": { + "type": "int" + }, + "max_wait_time": { + "type": "int" + }, }, }, }, @@ -180,7 +188,9 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "set": {"type": "bool"}, - "default_information_originate": {"type": "bool"}, + "default_information_originate": { + "type": "bool" + }, "no_redistribution": {"type": "bool"}, "no_summary": {"type": "bool"}, "route_map": {"type": "str"}, @@ -190,9 +200,15 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type7": { "type": "dict", "options": { - "always": {"type": "bool"}, - "never": {"type": "bool"}, - "supress_fa": {"type": "bool"}, + "always": { + "type": "bool" + }, + "never": { + "type": "bool" + }, + "supress_fa": { + "type": "bool" + }, }, }, }, @@ -265,7 +281,9 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "set": {"type": "bool"}, - "max_metric_value": {"type": "int"}, + "max_metric_value": { + "type": "int" + }, }, }, "stub_prefix_lsa": {"type": "bool"}, @@ -274,14 +292,18 @@ class Ospfv3Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "wait_period": {"type": "int"}, - "wait_for_bgp_asn": {"type": "int"}, + "wait_for_bgp_asn": { + "type": "int" + }, }, }, "inter_area_prefix_lsa": { "type": "dict", "options": { "set": {"type": "bool"}, - "max_metric_value": {"type": "int"}, + "max_metric_value": { + "type": "int" + }, }, }, }, @@ -307,9 +329,15 @@ class Ospfv3Args(object): # pylint: disable=R0903 "lsa": { "type": "dict", "options": { - "start_interval": {"type": "int"}, - "hold_interval": {"type": "int"}, - "max_interval": {"type": "int"}, + "start_interval": { + "type": "int" + }, + "hold_interval": { + "type": "int" + }, + "max_interval": { + "type": "int" + }, }, }, }, @@ -332,8 +360,12 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "set": {"type": "bool"}, - "default_information_originate": {"type": "bool"}, - "no_redistribution": {"type": "bool"}, + "default_information_originate": { + "type": "bool" + }, + "no_redistribution": { + "type": "bool" + }, "no_summary": {"type": "bool"}, "route_map": {"type": "str"}, "translate": { @@ -342,9 +374,15 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type7": { "type": "dict", "options": { - "always": {"type": "bool"}, - "never": {"type": "bool"}, - "supress_fa": {"type": "bool"}, + "always": { + "type": "bool" + }, + "never": { + "type": "bool" + }, + "supress_fa": { + "type": "bool" + }, }, }, }, @@ -414,24 +452,40 @@ class Ospfv3Args(object): # pylint: disable=R0903 "external_lsa": { "type": "dict", "options": { - "set": {"type": "bool"}, - "max_metric_value": {"type": "int"}, + "set": { + "type": "bool" + }, + "max_metric_value": { + "type": "int" + }, }, }, - "stub_prefix_lsa": {"type": "bool"}, + "stub_prefix_lsa": { + "type": "bool" + }, "on_startup": { "type": "dict", "options": { - "set": {"type": "bool"}, - "wait_period": {"type": "int"}, - "wait_for_bgp_asn": {"type": "int"}, + "set": { + "type": "bool" + }, + "wait_period": { + "type": "int" + }, + "wait_for_bgp_asn": { + "type": "int" + }, }, }, "inter_area_prefix_lsa": { "type": "dict", "options": { - "set": {"type": "bool"}, - "max_metric_value": {"type": "int"}, + "set": { + "type": "bool" + }, + "max_metric_value": { + "type": "int" + }, }, }, }, @@ -456,9 +510,15 @@ class Ospfv3Args(object): # pylint: disable=R0903 "lsa": { "type": "dict", "options": { - "start_interval": {"type": "int"}, - "hold_interval": {"type": "int"}, - "max_interval": {"type": "int"}, + "start_interval": { + "type": "int" + }, + "hold_interval": { + "type": "int" + }, + "max_interval": { + "type": "int" + }, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py b/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py index 14dfa5b05..91de47ec9 100644 --- a/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py +++ b/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py @@ -118,19 +118,29 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "source": {"type": "str"}, "group": { "type": "dict", - "options": {"prefix": {"type": "str"}}, + "options": { + "prefix": { + "type": "str" + } + }, }, "group_range": { "type": "dict", "options": { - "first": {"type": "str"}, - "last": {"type": "str"}, + "first": { + "type": "str" + }, + "last": { + "type": "str" + }, }, }, "rp": { "type": "dict", "options": { - "prefix": {"type": "str"}, + "prefix": { + "type": "str" + }, "rp_type": { "type": "str", "choices": [ @@ -181,19 +191,29 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "source": {"type": "str"}, "group": { "type": "dict", - "options": {"prefix": {"type": "str"}}, + "options": { + "prefix": { + "type": "str" + } + }, }, "group_range": { "type": "dict", "options": { - "first": {"type": "str"}, - "last": {"type": "str"}, + "first": { + "type": "str" + }, + "last": { + "type": "str" + }, }, }, "rp": { "type": "dict", "options": { - "prefix": {"type": "str"}, + "prefix": { + "type": "str" + }, "rp_type": { "type": "str", "choices": [ @@ -297,7 +317,9 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "options": { "half_life": {"type": "int"}, "start_reuse_route": {"type": "int"}, - "start_suppress_route": {"type": "int"}, + "start_suppress_route": { + "type": "int" + }, "max_suppress_time": {"type": "int"}, }, }, @@ -314,10 +336,14 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "options": { "gateway_ip": { "type": "dict", - "mutually_exclusive": [["ip", "use_nexthop"]], + "mutually_exclusive": [ + ["ip", "use_nexthop"] + ], "options": { "ip": {"type": "str"}, - "use_nexthop": {"type": "bool"}, + "use_nexthop": { + "type": "bool" + }, }, }, }, @@ -345,7 +371,9 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "options": { "address": { "type": "dict", - "options": {"prefix_list": {"type": "str"}}, + "options": { + "prefix_list": {"type": "str"} + }, }, "precedence": {"type": "str"}, "next_hop": { @@ -366,11 +394,24 @@ class Route_mapsArgs(object): # pylint: disable=R0903 ], "options": { "address": {"type": "str"}, - "drop_on_fail": {"type": "bool", "default": False}, - "force_order": {"type": "bool", "default": False}, - "load_share": {"type": "bool", "default": False}, - "peer_address": {"type": "bool"}, - "redist_unchanged": {"type": "bool"}, + "drop_on_fail": { + "type": "bool", + "default": False, + }, + "force_order": { + "type": "bool", + "default": False, + }, + "load_share": { + "type": "bool", + "default": False, + }, + "peer_address": { + "type": "bool" + }, + "redist_unchanged": { + "type": "bool" + }, "unchanged": {"type": "bool"}, "verify_availability": { "type": "list", @@ -380,7 +421,10 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "type": "str", "required": True, }, - "track": {"type": "int", "required": True}, + "track": { + "type": "int", + "required": True, + }, "drop_on_fail": { "type": "bool", "default": False, @@ -404,7 +448,9 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "options": { "address": { "type": "dict", - "options": {"prefix_list": {"type": "str"}}, + "options": { + "prefix_list": {"type": "str"} + }, }, "precedence": {"type": "str"}, }, @@ -424,8 +470,12 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "options": { "bandwidth": {"type": "int"}, "igrp_delay_metric": {"type": "int"}, - "igrp_reliability_metric": {"type": "int"}, - "igrp_effective_bandwidth_metric": {"type": "int"}, + "igrp_reliability_metric": { + "type": "int" + }, + "igrp_effective_bandwidth_metric": { + "type": "int" + }, "igrp_mtu": {"type": "int"}, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py b/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py index a6b3d4201..9cba81b8f 100644 --- a/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py +++ b/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py @@ -132,12 +132,16 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "enable": {"type": "bool"}, - "cefcMIBEnableStatusNotification": {"type": "bool"}, + "cefcMIBEnableStatusNotification": { + "type": "bool" + }, "entity_fan_status_change": {"type": "bool"}, "entity_mib_change": {"type": "bool"}, "entity_module_inserted": {"type": "bool"}, "entity_module_removed": {"type": "bool"}, - "entity_module_status_change": {"type": "bool"}, + "entity_module_status_change": { + "type": "bool" + }, "entity_power_out_change": {"type": "bool"}, "entity_power_status_change": {"type": "bool"}, "entity_sensor": {"type": "bool"}, @@ -165,16 +169,22 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "options": { "enable": {"type": "bool"}, "notify_license_expiry": {"type": "bool"}, - "notify_license_expiry_warning": {"type": "bool"}, + "notify_license_expiry_warning": { + "type": "bool" + }, "notify_licensefile_missing": {"type": "bool"}, - "notify_no_license_for_feature": {"type": "bool"}, + "notify_no_license_for_feature": { + "type": "bool" + }, }, }, "link": { "type": "dict", "options": { "enable": {"type": "bool"}, - "cErrDisableInterfaceEventRev1": {"type": "bool"}, + "cErrDisableInterfaceEventRev1": { + "type": "bool" + }, "cieLinkDown": {"type": "bool"}, "cieLinkUp": {"type": "bool"}, "cisco_xcvr_mon_status_chg": {"type": "bool"}, @@ -254,7 +264,9 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "enable": {"type": "bool"}, - "cseFailSwCoreNotifyExtended": {"type": "bool"}, + "cseFailSwCoreNotifyExtended": { + "type": "bool" + }, }, }, "system": { @@ -269,7 +281,9 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "options": { "enable": {"type": "bool"}, "upgradeJobStatusNotify": {"type": "bool"}, - "upgradeOpNotifyOnCompletion": {"type": "bool"}, + "upgradeOpNotifyOnCompletion": { + "type": "bool" + }, }, }, "vtp": { diff --git a/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py b/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py index 25b78da1b..e6945f3ce 100644 --- a/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py +++ b/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py @@ -57,7 +57,9 @@ class Static_routesArgs(object): # pylint: disable=R0903 "type": "list", "elements": "dict", "options": { - "forward_router_address": {"type": "str"}, + "forward_router_address": { + "type": "str" + }, "interface": {"type": "str"}, "admin_distance": {"type": "int"}, "route_name": {"type": "str"}, diff --git a/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py b/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py index 5bd15062e..68f47d777 100644 --- a/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py +++ b/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py @@ -23,7 +23,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( get_interface_type, normalize_interface, @@ -54,7 +56,9 @@ def get_acl_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - acl_interfaces_facts = facts["ansible_network_resources"].get("acl_interfaces") + acl_interfaces_facts = facts["ansible_network_resources"].get( + "acl_interfaces" + ) if not acl_interfaces_facts: return [] return acl_interfaces_facts @@ -137,9 +141,14 @@ def set_state(self, want, have): :returns: the commands necessary to migrate the current configuration to the desired configuration """ - if self.state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + self.state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(self.state), + msg="value of config parameter must not be empty for state {0}".format( + self.state + ), ) commands = [] @@ -185,7 +194,9 @@ def _state_replaced(self, want, have): for ag in obj_in_have["access_groups"]: want_afi = [] if want.get("access_groups"): - want_afi = search_obj_in_list(ag["afi"], want["access_groups"], "afi") + want_afi = search_obj_in_list( + ag["afi"], want["access_groups"], "afi" + ) if not want_afi: # whatever in have is not in want del_dict["access_groups"].append(ag) @@ -198,12 +209,18 @@ def _state_replaced(self, want, have): else: del_acl.append(acl) afi = want_afi["afi"] - del_dict["access_groups"].append({"afi": afi, "acls": del_acl}) + del_dict["access_groups"].append( + {"afi": afi, "acls": del_acl} + ) commands.extend(self._state_deleted([del_dict], have)) commands.extend(self._state_merged(want, have)) new_commands.append(commands[0]) - commands = [commands[i] for i in range(1, len(commands)) if commands[i] != commands[0]] + commands = [ + commands[i] + for i in range(1, len(commands)) + if commands[i] != commands[0] + ] new_commands.extend(commands) return new_commands @@ -241,26 +258,36 @@ def set_commands(self, want, have, deleted=False): ip = "ipv6" if w_afi["afi"] == "ipv4": ip = "ip" - have_afi = search_obj_in_list(w_afi["afi"], have_name["access_groups"], "afi") + have_afi = search_obj_in_list( + w_afi["afi"], have_name["access_groups"], "afi" + ) if have_afi: new_acls = [] if deleted: if w_afi.get("acls") and have_afi.get("acls"): new_acls = [ - acl for acl in w_afi.get("acls") if acl in have_afi.get("acls") + acl + for acl in w_afi.get("acls") + if acl in have_afi.get("acls") ] elif "acls" not in w_afi.keys(): new_acls = have_afi.get("acls") else: if w_afi.get("acls"): new_acls = [ - acl for acl in w_afi["acls"] if acl not in have_afi["acls"] + acl + for acl in w_afi["acls"] + if acl not in have_afi["acls"] ] - commands.extend(self.process_acl(new_acls, ip, deleted)) + commands.extend( + self.process_acl(new_acls, ip, deleted) + ) else: if not deleted: if w_afi.get("acls"): - commands.extend(self.process_acl(w_afi["acls"], ip)) + commands.extend( + self.process_acl(w_afi["acls"], ip) + ) else: # only name is given to delete if deleted and "access_groups" in have_name.keys(): @@ -295,7 +322,9 @@ def process_acl(self, acls, ip, deleted=False): ag = " access-group " if ip == "ipv6": ag = " traffic-filter " - commands.append(no + ip + port + ag + acl["name"] + " " + acl["direction"]) + commands.append( + no + ip + port + ag + acl["name"] + " " + acl["direction"] + ) return commands def _state_deleted(self, main_want, have): @@ -313,7 +342,9 @@ def _state_deleted(self, main_want, have): commands.extend(self.set_commands(h, have, deleted=True)) else: for want in main_want: - commands.extend(self.set_commands(want, have, deleted=True)) + commands.extend( + self.set_commands(want, have, deleted=True) + ) else: for h in have: commands.extend(self.set_commands(h, have, deleted=True)) diff --git a/plugins/module_utils/network/nxos/config/acls/acls.py b/plugins/module_utils/network/nxos/config/acls/acls.py index 5e6f3c34a..dcc4fc7a8 100644 --- a/plugins/module_utils/network/nxos/config/acls/acls.py +++ b/plugins/module_utils/network/nxos/config/acls/acls.py @@ -17,7 +17,9 @@ import re -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import ( ConfigBase, ) @@ -29,7 +31,9 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acls.acls import ( AclsArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( search_obj_in_list, ) @@ -222,37 +226,57 @@ def convert_values(self, want): ace["dscp"] = ace["dscp"].lower() if "precedence" in ace.keys(): if ace["precedence"].isdigit(): - ace["precedence"] = precedence[int(ace["precedence"])] + ace["precedence"] = precedence[ + int(ace["precedence"]) + ] if ( "protocol" in ace.keys() and ace["protocol"].isdigit() and int(ace["protocol"]) in protocol.keys() ): - ace["protocol"] = protocol[int(ace["protocol"])] + ace["protocol"] = protocol[ + int(ace["protocol"]) + ] # convert number to name - if "protocol" in ace.keys() and ace["protocol"] in ["tcp", "udp"]: + if "protocol" in ace.keys() and ace[ + "protocol" + ] in ["tcp", "udp"]: for x in ["source", "destination"]: if "port_protocol" in ace[x].keys(): - key = list(ace[x]["port_protocol"].keys())[0] + key = list( + ace[x]["port_protocol"].keys() + )[0] # key could be eq,gt,lt,neq or range if key != "range": val = ace[x]["port_protocol"][key] - if val.isdigit() and int(val) in port_protocol.keys(): - ace[x]["port_protocol"][key] = port_protocol[ - int(val) - ] + if ( + val.isdigit() + and int(val) + in port_protocol.keys() + ): + ace[x]["port_protocol"][ + key + ] = port_protocol[int(val)] else: - st = int(ace[x]["port_protocol"]["range"]["start"]) - end = int(ace[x]["port_protocol"]["range"]["end"]) + st = int( + ace[x]["port_protocol"][ + "range" + ]["start"] + ) + end = int( + ace[x]["port_protocol"][ + "range" + ]["end"] + ) if st in port_protocol.keys(): - ace[x]["port_protocol"]["range"][ - "start" - ] = port_protocol[st] + ace[x]["port_protocol"][ + "range" + ]["start"] = port_protocol[st] if end in port_protocol.keys(): - ace[x]["port_protocol"]["range"][ - "end" - ] = port_protocol[end] + ace[x]["port_protocol"][ + "range" + ]["end"] = port_protocol[end] return want def set_state(self, want, have): @@ -317,11 +341,19 @@ def _state_replaced(self, want, have): if w["name"] not in have_names: # creates new ACL in replaced state merge_dict = {"afi": want["afi"], "acls": [w]} - commands.extend(self._state_merged(merge_dict, have)) + commands.extend( + self._state_merged(merge_dict, have) + ) else: # acl in want exists in have - have_name = search_obj_in_list(w["name"], have_afi["acls"], "name") - have_aces = have_name.get("aces") if have_name.get("aces") else [] + have_name = search_obj_in_list( + w["name"], have_afi["acls"], "name" + ) + have_aces = ( + have_name.get("aces") + if have_name.get("aces") + else [] + ) merge_aces = [] del_aces = [] w_aces = w.get("aces") if w.get("aces") else [] @@ -334,15 +366,23 @@ def _state_replaced(self, want, have): merge_aces.append(ace) merge_dict = { "afi": want["afi"], - "acls": [{"name": w["name"], "aces": merge_aces}], + "acls": [ + {"name": w["name"], "aces": merge_aces} + ], } del_dict = { "afi": want["afi"], - "acls": [{"name": w["name"], "aces": del_aces}], + "acls": [ + {"name": w["name"], "aces": del_aces} + ], } if del_dict["acls"]: - acl_commands.extend(self._state_deleted([del_dict], have)) - acl_commands.extend(self._state_merged(merge_dict, have)) + acl_commands.extend( + self._state_deleted([del_dict], have) + ) + acl_commands.extend( + self._state_merged(merge_dict, have) + ) for i in range(1, len(acl_commands)): if acl_commands[i] == acl_commands[0]: @@ -377,7 +417,9 @@ def _state_overridden(self, want, have): if h["afi"] in want_afi: w = search_obj_in_list(h["afi"], want, "afi") for h_acl in h["acls"]: - w_acl = search_obj_in_list(h_acl["name"], w["acls"], "name") + w_acl = search_obj_in_list( + h_acl["name"], w["acls"], "name" + ) if not w_acl: del_dict = { "afi": h["afi"], @@ -417,7 +459,10 @@ def _state_deleted(self, want, have): if have_afi: if w.get("acls"): for acl in w["acls"]: - if "aces" in acl.keys() and self.state != "deleted": + if ( + "aces" in acl.keys() + and self.state != "deleted" + ): have_name = search_obj_in_list( acl["name"], have_afi["acls"], @@ -431,20 +476,32 @@ def _state_deleted(self, want, have): # only sequence number is specified to be deleted if "aces" in have_name.keys(): for h_ace in have_name["aces"]: - if h_ace["sequence"] == ace["sequence"]: + if ( + h_ace["sequence"] + == ace["sequence"] + ): ace_commands.append( - "no " + str(ace["sequence"]), + "no " + + str( + ace["sequence"] + ), ) flag = 1 else: if "aces" in have_name.keys(): for h_ace in have_name["aces"]: # when want['ace'] does not have seq number - if "sequence" not in ace.keys(): + if ( + "sequence" + not in ace.keys() + ): del h_ace["sequence"] if ace == h_ace: ace_commands.append( - "no " + self.process_ace(ace), + "no " + + self.process_ace( + ace + ), ) flag = 1 if flag: @@ -459,7 +516,9 @@ def _state_deleted(self, want, have): if h["name"] == acl["name"]: acl_names.append(acl["name"]) for name in acl_names: - commands.append("no " + ip + " access-list " + name) + commands.append( + "no " + ip + " access-list " + name + ) else: # 'only afi is given' @@ -467,7 +526,9 @@ def _state_deleted(self, want, have): for h in have_afi["acls"]: acl_names.append(h["name"]) for name in acl_names: - commands.append("no " + ip + " access-list " + name) + commands.append( + "no " + ip + " access-list " + name + ) else: v6 = [] v4 = [] @@ -510,7 +571,9 @@ def set_commands(self, want, have): if have_afi: if want.get("acls"): for w_acl in want["acls"]: - have_acl = search_obj_in_list(w_acl["name"], have_afi["acls"], "name") + have_acl = search_obj_in_list( + w_acl["name"], have_afi["acls"], "name" + ) name = w_acl["name"] flag = 0 ace_commands = [] @@ -524,7 +587,9 @@ def set_commands(self, want, have): # For replaced and overridden, rule is deleted in the state's config) ace_list = [ - item for item in w_acl["aces"] if "sequence" not in item.keys() + item + for item in w_acl["aces"] + if "sequence" not in item.keys() ] # case 1 want_seq = [ @@ -533,15 +598,21 @@ def set_commands(self, want, have): if "sequence" in item.keys() ] - have_seq = [item["sequence"] for item in have_acl["aces"]] + have_seq = [ + item["sequence"] + for item in have_acl["aces"] + ] new_seq = list(set(want_seq) - set(have_seq)) - common_seq = list(set(want_seq).intersection(set(have_seq))) + common_seq = list( + set(want_seq).intersection(set(have_seq)) + ) temp_list = [ item for item in w_acl["aces"] - if "sequence" in item.keys() and item["sequence"] in new_seq + if "sequence" in item.keys() + and item["sequence"] in new_seq ] # case 2 ace_list.extend(temp_list) for w in w_acl["aces"]: @@ -562,7 +633,10 @@ def set_commands(self, want, have): ], }, ) - if "sequence" in w.keys() and w["sequence"] in common_seq: + if ( + "sequence" in w.keys() + and w["sequence"] in common_seq + ): temp_obj = search_obj_in_list( w["sequence"], have_acl["aces"], @@ -583,17 +657,23 @@ def set_commands(self, want, have): # 'have' has ACL defined without any ACE ace_list = list(w_acl["aces"]) for w_ace in ace_list: - ace_commands.append(self.process_ace(w_ace).strip()) + ace_commands.append( + self.process_ace(w_ace).strip() + ) flag = 1 if flag: - ace_commands.insert(0, ip + "access-list " + name) + ace_commands.insert( + 0, ip + "access-list " + name + ) else: commands.append(ip + "access-list " + name) if "aces" in w_acl.keys(): for w_ace in w_acl["aces"]: - commands.append(self.process_ace(w_ace).strip()) + commands.append( + self.process_ace(w_ace).strip() + ) commands.extend(ace_commands) else: if want.get("acls"): @@ -619,12 +699,16 @@ def process_ace(self, w_ace): else: command += w_ace["protocol"] + " " src = self.get_address(w_ace["source"], w_ace["protocol"]) - dest = self.get_address(w_ace["destination"], w_ace["protocol"]) + dest = self.get_address( + w_ace["destination"], w_ace["protocol"] + ) command += src + dest if "protocol_options" in ace_keys: pro = list(w_ace["protocol_options"].keys())[0] if pro != w_ace["protocol"]: - self._module.fail_json(msg="protocol and protocol_options mismatch") + self._module.fail_json( + msg="protocol and protocol_options mismatch" + ) flags = "" for k in w_ace["protocol_options"][pro].keys(): if k not in ["telemetry_queue", "telemetry_path"]: @@ -648,9 +732,13 @@ def get_address(self, endpoint, pro=""): keys = list(endpoint.keys()) if "address" in keys: if "wildcard_bits" not in keys: - self._module.fail_json(msg="wildcard bits not specified for address") + self._module.fail_json( + msg="wildcard bits not specified for address" + ) else: - ret_addr = endpoint["address"] + " " + endpoint["wildcard_bits"] + " " + ret_addr = ( + endpoint["address"] + " " + endpoint["wildcard_bits"] + " " + ) elif "any" in keys: ret_addr = "any " elif "host" in keys: @@ -668,7 +756,13 @@ def get_options(self, item): com = "" subkey = list(item.keys()) if "range" in subkey: - com = "range " + item["range"]["start"] + " " + item["range"]["end"] + " " + com = ( + "range " + + item["range"]["start"] + + " " + + item["range"]["end"] + + " " + ) else: com = subkey[0] + " " + item[subkey[0]] + " " return com diff --git a/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py b/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py index a9dc51fd9..2b81658a9 100644 --- a/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py +++ b/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py @@ -24,7 +24,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, search_obj_in_list, @@ -55,7 +57,9 @@ def get_bfd_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - bfd_interfaces_facts = facts["ansible_network_resources"].get("bfd_interfaces", []) + bfd_interfaces_facts = facts["ansible_network_resources"].get( + "bfd_interfaces", [] + ) platform = facts.get("ansible_net_platform", "") return bfd_interfaces_facts, platform @@ -82,7 +86,9 @@ def execute_module(self): existing_bfd_interfaces_facts, platform = [], "" if self.state in self.ACTION_STATES or self.state == "rendered": - commands.extend(self.set_config(existing_bfd_interfaces_facts, platform)) + commands.extend( + self.set_config(existing_bfd_interfaces_facts, platform) + ) if commands and self.state in self.ACTION_STATES: if not self._module.check_mode: @@ -107,7 +113,9 @@ def execute_module(self): self._module.fail_json( msg="value of running_config parameter must not be empty for state parsed", ) - result["parsed"], platform = self.get_bfd_interfaces_facts(data=running_config) + result["parsed"], platform = self.get_bfd_interfaces_facts( + data=running_config + ) if self.state in self.ACTION_STATES: result["before"] = existing_bfd_interfaces_facts @@ -158,9 +166,14 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) cmds = list() @@ -214,7 +227,9 @@ def _state_overridden(self, want, have): for h in have: # Clean up bfd attrs for any interfaces not listed in the play h = flatten_dict(h) - obj_in_want = flatten_dict(search_obj_in_list(h["name"], want, "name")) + obj_in_want = flatten_dict( + search_obj_in_list(h["name"], want, "name") + ) if obj_in_want: # Let the 'want' loop handle all vals for this interface continue @@ -248,7 +263,9 @@ def _state_deleted(self, want, have): cmds = [] if want: for w in want: - obj_in_have = flatten_dict(search_obj_in_list(w["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(w["name"], have, "name") + ) cmds.extend(self.del_attribs(obj_in_have)) else: for h in have: @@ -302,7 +319,9 @@ def add_commands(self, want): def set_commands(self, want, have): cmds = [] - obj_in_have = flatten_dict(search_obj_in_list(want["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(want["name"], have, "name") + ) if not obj_in_have: cmds = self.add_commands(want) else: diff --git a/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py b/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py index 4443039c3..2aae0a64a 100644 --- a/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py @@ -29,7 +29,9 @@ remove_empties, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_address_family import ( Bgp_address_familyTemplate, ) @@ -114,14 +116,18 @@ def generate_commands(self): # if state is overridden or deleted, remove superfluos config if self.state in ["deleted", "overridden"]: - if (haved and haved["as_number"] == wantd.get("as_number")) or not wantd: + if ( + haved and haved["as_number"] == wantd.get("as_number") + ) or not wantd: remove = True if self.state == "deleted" else False purge = True if not wantd else False self._remove_af(want_af, have_af, remove=remove, purge=purge) for k, hvrf in iteritems(hvrfs): wvrf = wvrfs.get(k, {}) - self._remove_af(wvrf, hvrf, vrf=k, remove=remove, purge=purge) + self._remove_af( + wvrf, hvrf, vrf=k, remove=remove, purge=purge + ) if self.state in ["merged", "replaced", "overridden", "rendered"]: for k, want in iteritems(want_af): @@ -140,7 +146,9 @@ def generate_commands(self): self.commands.insert(cur_ptr, "vrf {0}".format(wk)) if self.commands: - self.commands.insert(0, "router bgp {as_number}".format(**haved or wantd)) + self.commands.insert( + 0, "router bgp {as_number}".format(**haved or wantd) + ) def _compare(self, want, have): """Leverages the base class `compare()` method and @@ -196,13 +204,19 @@ def _build_key(data): # transform parameters which are # list of dicts to dict of dicts for item in entry.get("address_family", []): - item["aggregate_address"] = {x["prefix"]: x for x in item.get("aggregate_address", [])} + item["aggregate_address"] = { + x["prefix"]: x for x in item.get("aggregate_address", []) + } item["inject_map"] = { - (x["route_map"], x["exist_map"]): x for x in item.get("inject_map", []) + (x["route_map"], x["exist_map"]): x + for x in item.get("inject_map", []) + } + item["networks"] = { + x["prefix"]: x for x in item.get("networks", []) } - item["networks"] = {x["prefix"]: x for x in item.get("networks", [])} item["redistribute"] = { - (x.get("id"), x["protocol"]): x for x in item.get("redistribute", []) + (x.get("id"), x["protocol"]): x + for x in item.get("redistribute", []) } # transform all entries under @@ -234,7 +248,9 @@ def _build_key(data): # final structure: https://gist.github.com/NilashishC/628dae5fe39a4908e87c9e833bfbe57d - def _remove_af(self, want_af, have_af, vrf=None, remove=False, purge=False): + def _remove_af( + self, want_af, have_af, vrf=None, remove=False, purge=False + ): cur_ptr = len(self.commands) for k, v in iteritems(have_af): # first conditional is for deleted with config provided diff --git a/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py b/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py index fe738d1af..7aa6b51c6 100644 --- a/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py @@ -26,7 +26,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_global import ( Bgp_globalTemplate, ) @@ -132,11 +134,15 @@ def generate_commands(self): # if state is deleted, clean up global params if self.state == "deleted": - if not self.want or (self.have.get("as_number") == self.want.get("as_number")): + if not self.want or ( + self.have.get("as_number") == self.want.get("as_number") + ): self._compare(want={}, have=self.have) elif self.state == "purged": - if not self.want or (self.have.get("as_number") == self.want.get("as_number")): + if not self.want or ( + self.have.get("as_number") == self.want.get("as_number") + ): self.addcmd(self.have or {}, "as_number", True) else: @@ -164,7 +170,9 @@ def _compare(self, want, have, vrf=None): begin, self._tmplt.render( want or have, - "vrf" if "vrf" in (want.keys() or have.keys()) else "as_number", + "vrf" + if "vrf" in (want.keys() or have.keys()) + else "as_number", False, ), ) @@ -235,7 +243,9 @@ def _compare_neighbors(self, want, have, vrf=None): self._compare_path_attribute(entry, have_nbr) if len(self.commands) != begin or (entry and not have_nbr): - self.commands.insert(begin, self._tmplt.render(entry, "neighbor_address", False)) + self.commands.insert( + begin, self._tmplt.render(entry, "neighbor_address", False) + ) # cleanup remaining neighbors # but do not negate it entirely @@ -288,7 +298,9 @@ def _vrfs_compare(self, want, have): if self._has_af(vrf=name): self._module.fail_json( msg="VRF {0} has address-family configurations. " - "Please use the nxos_bgp_af module to remove those first.".format(name), + "Please use the nxos_bgp_af module to remove those first.".format( + name + ), ) else: self.addcmd(entry, "vrf", True) @@ -317,10 +329,13 @@ def _build_key(x): for x in entry["neighbors"]: if "path_attribute" in x: x["path_attribute"] = { - _build_key(item): item for item in x.get("path_attribute", []) + _build_key(item): item + for item in x.get("path_attribute", []) } - entry["neighbors"] = {x["neighbor_address"]: x for x in entry.get("neighbors", [])} + entry["neighbors"] = { + x["neighbor_address"]: x for x in entry.get("neighbors", []) + } if "vrfs" in entry: entry["vrfs"] = {x["vrf"]: x for x in entry.get("vrfs", [])} @@ -328,7 +343,9 @@ def _build_key(x): self._bgp_list_to_dict(vrf) def _get_config(self): - return self._connection.get("show running-config | section '^router bgp'") + return self._connection.get( + "show running-config | section '^router bgp'" + ) def _build_af_data(self): """Build a dictionary with AF related information diff --git a/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py index 0ab282a6c..17a1d706b 100644 --- a/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py @@ -27,7 +27,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_neighbor_address_family import ( Bgp_neighbor_address_familyTemplate, ) @@ -124,7 +126,9 @@ def generate_commands(self): self._compare(want=wantd, have=haved) if self.commands: - self.commands.insert(0, "router bgp {as_number}".format(**haved or wantd)) + self.commands.insert( + 0, "router bgp {as_number}".format(**haved or wantd) + ) def _compare(self, want, have, vrf=""): """Leverages the base class `compare()` method and @@ -171,7 +175,9 @@ def _compare(self, want, have, vrf=""): self.addcmd(have_af, "address_family", True) if len(self.commands) != begin: - self.commands.insert(begin, "neighbor {0}".format(w_nbr["neighbor_address"])) + self.commands.insert( + begin, "neighbor {0}".format(w_nbr["neighbor_address"]) + ) if self.state in ["overridden", "deleted"]: for k, h_nbr in iteritems(h_nbrs): @@ -181,7 +187,9 @@ def _compare(self, want, have, vrf=""): for k, have_af in iteritems(have_afs): self.addcmd(have_af, "address_family", True) if len(self.commands) != begin: - self.commands.insert(begin, "neighbor {0}".format(h_nbr["neighbor_address"])) + self.commands.insert( + begin, "neighbor {0}".format(h_nbr["neighbor_address"]) + ) if vrf: if len(self.commands) != begin_vrf: @@ -204,9 +212,12 @@ def _bgp_list_to_dict(self, data): for nbr in data["neighbors"]: if "address_family" in nbr: nbr["address_family"] = { - (x["afi"], x.get("safi")): x for x in nbr["address_family"] + (x["afi"], x.get("safi")): x + for x in nbr["address_family"] } - data["neighbors"] = {x["neighbor_address"]: x for x in data["neighbors"]} + data["neighbors"] = { + x["neighbor_address"]: x for x in data["neighbors"] + } if "vrfs" in data: for vrf in data["vrfs"]: diff --git a/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py b/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py index 648db72e6..441250c22 100644 --- a/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py @@ -27,7 +27,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_templates import ( Bgp_templatesTemplate, ) @@ -130,7 +132,9 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } wantd = {} # remove superfluous config for overridden and deleted @@ -145,7 +149,9 @@ def generate_commands(self): begin = len(self.commands) self._compare(want=want, have=haved.pop(k, {})) if len(self.commands) != begin: - self.commands.insert(begin, "template peer {0}".format(want["name"])) + self.commands.insert( + begin, "template peer {0}".format(want["name"]) + ) if self.commands: self.commands.insert(0, "router bgp {0}".format(asn)) @@ -186,9 +192,13 @@ def _afs_compare(self, want, have): begin = len(self.commands) self._af_compare(want=wentry, have=have.pop(name, {})) if begin != len(self.commands): - self.commands.insert(begin, self._tmplt.render(wentry, "address_family", False)) + self.commands.insert( + begin, self._tmplt.render(wentry, "address_family", False) + ) for name, hentry in iteritems(have): - self.commands.append(self._tmplt.render(hentry, "address_family", True)) + self.commands.append( + self._tmplt.render(hentry, "address_family", True) + ) def _af_compare(self, want, have): # "unpack" send_community @@ -224,11 +234,13 @@ def _build_key(x): for entry in v: if "address_family" in entry: entry["address_family"] = { - (x["afi"], x.get("safi")): x for x in entry["address_family"] + (x["afi"], x.get("safi")): x + for x in entry["address_family"] } if "path_attribute" in entry: entry["path_attribute"] = { - _build_key(x): x for x in entry.get("path_attribute", []) + _build_key(x): x + for x in entry.get("path_attribute", []) } # attach top-level keys with their values diff --git a/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py b/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py index e08a9ce1b..3f9f2c688 100644 --- a/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py @@ -27,7 +27,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.fc_interfaces import ( Fc_interfacesTemplate, ) @@ -49,7 +51,13 @@ def __init__(self, module): resource="fc_interfaces", tmplt=Fc_interfacesTemplate(), ) - self.parsers = ["description", "speed", "mode", "trunk_mode", "analytics"] + self.parsers = [ + "description", + "speed", + "mode", + "trunk_mode", + "analytics", + ] def execute_module(self): """Execute the module @@ -79,7 +87,9 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } wantd = {} # remove superfluous config for overridden and deleted @@ -92,7 +102,9 @@ def generate_commands(self): self._compare(want=want, have=haved.pop(k, {})) modified_list = [ - "switchport trunk mode on" if item.startswith("no switchport trunk mode") else item + "switchport trunk mode on" + if item.startswith("no switchport trunk mode") + else item for item in self.commands ] self.commands = modified_list @@ -158,7 +170,10 @@ def _calculate_ana_config(self, want_ana, have_ana): elif have_ana == "": val = [f"analytics type {want_ana}"] else: - val = ["no analytics type fc-all", f"analytics type {want_ana}"] + val = [ + "no analytics type fc-all", + f"analytics type {want_ana}", + ] elif self.state in ["deleted"]: if have_ana: val = ["no analytics type fc-all"] @@ -188,12 +203,16 @@ def _compare(self, want, have): # negates if no shutdown self.addcmd(have, "enabled", False) - ana_cmds = self._calculate_ana_config(want.get("analytics", ""), have.get("analytics", "")) + ana_cmds = self._calculate_ana_config( + want.get("analytics", ""), have.get("analytics", "") + ) self.commands.extend(ana_cmds) if len(self.commands) != begin: - self.commands.insert(begin, self._tmplt.render(want or have, "interface", False)) + self.commands.insert( + begin, self._tmplt.render(want or have, "interface", False) + ) def normalize_interface_names(self, param): if param: diff --git a/plugins/module_utils/network/nxos/config/hostname/hostname.py b/plugins/module_utils/network/nxos/config/hostname/hostname.py index 42ed06946..1c4082f33 100644 --- a/plugins/module_utils/network/nxos/config/hostname/hostname.py +++ b/plugins/module_utils/network/nxos/config/hostname/hostname.py @@ -22,7 +22,9 @@ ResourceModule, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.hostname import ( HostnameTemplate, ) diff --git a/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py b/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py index 757505e71..b82af93c8 100644 --- a/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py +++ b/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py @@ -22,7 +22,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, normalize_interface, @@ -53,7 +55,9 @@ def get_hsrp_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - hsrp_interfaces_facts = facts["ansible_network_resources"].get("hsrp_interfaces", []) + hsrp_interfaces_facts = facts["ansible_network_resources"].get( + "hsrp_interfaces", [] + ) return hsrp_interfaces_facts def edit_config(self, commands): @@ -97,7 +101,9 @@ def execute_module(self): self._module.fail_json( msg="value of running_config parameter must not be empty for state parsed", ) - result["parsed"] = self.get_hsrp_interfaces_facts(data=running_config) + result["parsed"] = self.get_hsrp_interfaces_facts( + data=running_config + ) if self.state in self.ACTION_STATES: result["before"] = existing_hsrp_interfaces_facts @@ -139,9 +145,14 @@ def set_state(self, want, have): """ state = self._module.params["state"] # check for 'config' keyword in play - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) cmds = list() @@ -229,7 +240,9 @@ def _state_deleted(self, want, have): cmds = [] if want: for w in want: - obj_in_have = flatten_dict(search_obj_in_list(w["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(w["name"], have, "name") + ) cmds.extend(self.del_attribs(obj_in_have)) else: for h in have: @@ -267,7 +280,11 @@ def add_commands(self, want, obj_in_have): if want["bfd"] == "enable": cmd = "hsrp bfd" cmds.append(cmd) - elif want["bfd"] == "disable" and obj_in_have and obj_in_have.get("bfd") == "enable": + elif ( + want["bfd"] == "disable" + and obj_in_have + and obj_in_have.get("bfd") == "enable" + ): cmd = "no hsrp bfd" cmds.append(cmd) diff --git a/plugins/module_utils/network/nxos/config/interfaces/interfaces.py b/plugins/module_utils/network/nxos/config/interfaces/interfaces.py index 400f0432f..f67599b28 100644 --- a/plugins/module_utils/network/nxos/config/interfaces/interfaces.py +++ b/plugins/module_utils/network/nxos/config/interfaces/interfaces.py @@ -29,7 +29,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( default_intf_enabled, ) @@ -65,7 +67,9 @@ def get_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - interfaces_facts = self.facts["ansible_network_resources"].get("interfaces") + interfaces_facts = self.facts["ansible_network_resources"].get( + "interfaces" + ) return interfaces_facts @@ -184,7 +188,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state, @@ -429,7 +436,12 @@ def add_commands(self, d, obj_in_have=None): if "duplex" in d: commands.append("duplex " + d["duplex"]) if "enabled" in d: - have_enabled = obj_in_have.get("enabled", self.default_enabled(d, obj_in_have)) or False + have_enabled = ( + obj_in_have.get( + "enabled", self.default_enabled(d, obj_in_have) + ) + or False + ) if d["enabled"] is False and have_enabled is True: commands.append("shutdown") elif d["enabled"] is True and have_enabled is False: @@ -476,7 +488,9 @@ def render_interface_defaults(self, config, intfs): Run through the gathered interfaces and tag their default enabled state. """ intf_defs = {} - L3_enabled = True if re.search("N[56]K", self.get_platform()) else False + L3_enabled = ( + True if re.search("N[56]K", self.get_platform()) else False + ) intf_defs = { "sysdefs": { "mode": None, @@ -487,12 +501,16 @@ def render_interface_defaults(self, config, intfs): pat = "(no )*system default switchport$" m = re.search(pat, config, re.MULTILINE) if m: - intf_defs["sysdefs"]["mode"] = "layer3" if "no " in m.groups() else "layer2" + intf_defs["sysdefs"]["mode"] = ( + "layer3" if "no " in m.groups() else "layer2" + ) pat = "(no )*system default switchport shutdown$" m = re.search(pat, config, re.MULTILINE) if m: - intf_defs["sysdefs"]["L2_enabled"] = True if "no " in m.groups() else False + intf_defs["sysdefs"]["L2_enabled"] = ( + True if "no " in m.groups() else False + ) for item in intfs: intf_defs[item["name"]] = default_intf_enabled( diff --git a/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py b/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py index e7d91498f..2401cc619 100644 --- a/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py +++ b/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py @@ -26,7 +26,9 @@ remove_empties, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, normalize_interface, @@ -61,7 +63,9 @@ def get_l2_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - l2_interfaces_facts = facts["ansible_network_resources"].get("l2_interfaces") + l2_interfaces_facts = facts["ansible_network_resources"].get( + "l2_interfaces" + ) if not l2_interfaces_facts: return [] return l2_interfaces_facts @@ -104,7 +108,9 @@ def execute_module(self): self._module.fail_json( msg="value of running_config parameter must not be empty for state parsed", ) - result["parsed"] = self.get_l2_interfaces_facts(data=running_config) + result["parsed"] = self.get_l2_interfaces_facts( + data=running_config + ) if self.state in self.ACTION_STATES: result["before"] = existing_l2_interfaces_facts @@ -159,9 +165,14 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = list() @@ -174,7 +185,9 @@ def set_state(self, want, have): if state in ["merged", "rendered"]: commands.extend(self._state_merged(flatten_dict(w), have)) elif state == "replaced": - commands.extend(self._state_replaced(flatten_dict(w), have)) + commands.extend( + self._state_replaced(flatten_dict(w), have) + ) return commands def _state_replaced(self, w, have): @@ -218,7 +231,9 @@ def _state_overridden(self, want, have): commands = [] for h in have: h = flatten_dict(h) - obj_in_want = flatten_dict(search_obj_in_list(h["name"], want, "name")) + obj_in_want = flatten_dict( + search_obj_in_list(h["name"], want, "name") + ) if h == obj_in_want: continue for w in want: @@ -253,7 +268,9 @@ def _state_deleted(self, want, have): commands = [] if want: for w in want: - obj_in_have = flatten_dict(search_obj_in_list(w["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(w["name"], have, "name") + ) commands.extend(self.del_attribs(obj_in_have)) else: if not have: @@ -299,9 +316,13 @@ def add_commands(self, d, vlan_exists=False): commands.append(cmd + "access vlan " + str(d["vlan"])) if "allowed_vlans" in d: if vlan_exists: - commands.append(cmd + "trunk allowed vlan add " + str(d["allowed_vlans"])) + commands.append( + cmd + "trunk allowed vlan add " + str(d["allowed_vlans"]) + ) else: - commands.append(cmd + "trunk allowed vlan " + str(d["allowed_vlans"])) + commands.append( + cmd + "trunk allowed vlan " + str(d["allowed_vlans"]) + ) if "native_vlan" in d: commands.append(cmd + "trunk native vlan " + str(d["native_vlan"])) if commands: @@ -330,7 +351,9 @@ def set_commands(self, w, have, replace=False): if w_vlans in have_vlans: vlan_tobe_added.pop(vlan_tobe_added.index(w_vlans)) if vlan_tobe_added: - diff.update({"allowed_vlans": ",".join(vlan_tobe_added)}) + diff.update( + {"allowed_vlans": ",".join(vlan_tobe_added)} + ) if have_vlans: commands = self.add_commands(diff, True) else: diff --git a/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py index d4da881f5..40a5c52e2 100644 --- a/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py @@ -28,7 +28,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( normalize_interface, search_obj_in_list, @@ -64,7 +66,9 @@ def get_l3_interfaces_facts(self, data=None): data=data, ) - l3_interfaces_facts = facts["ansible_network_resources"].get("l3_interfaces") + l3_interfaces_facts = facts["ansible_network_resources"].get( + "l3_interfaces" + ) self.platform = facts.get("ansible_net_platform", "") return l3_interfaces_facts @@ -110,7 +114,9 @@ def execute_module(self): self._module.fail_json( msg="value of running_config parameter must not be empty for state parsed", ) - result["parsed"] = self.get_l3_interfaces_facts(data=running_config) + result["parsed"] = self.get_l3_interfaces_facts( + data=running_config + ) if self.state in self.ACTION_STATES: result["before"] = existing_l3_interfaces_facts @@ -152,9 +158,14 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = [] @@ -186,15 +197,21 @@ def _state_replaced(self, want, have): have_v6 = obj_in_have.pop("ipv6", []) if obj_in_have else [] # Process lists of dicts separately - v4_cmds = self._v4_cmds(want.pop("ipv4", []), have_v4, state="replaced") - v6_cmds = self._v6_cmds(want.pop("ipv6", []), have_v6, state="replaced") + v4_cmds = self._v4_cmds( + want.pop("ipv4", []), have_v4, state="replaced" + ) + v6_cmds = self._v6_cmds( + want.pop("ipv6", []), have_v6, state="replaced" + ) # Process remaining attrs if obj_in_have: # Find 'want' changes first diff = self.diff_of_dicts(want, obj_in_have) rmv = {"name": name} - haves_not_in_want = set(obj_in_have.keys()) - set(want.keys()) - set(diff.keys()) + haves_not_in_want = ( + set(obj_in_have.keys()) - set(want.keys()) - set(diff.keys()) + ) for i in haves_not_in_want: rmv[i] = obj_in_have[i] cmds.extend(self.generate_delete_commands(rmv)) @@ -293,7 +310,9 @@ def _v4_cmds(self, want, have, state=None): sec_to_rmv = [] sec_diff = self.diff_list_of_dicts(sec_h, sec_w) for i in sec_diff: - if overridden or [w for w in sec_w if w["address"] == i["address"]]: + if overridden or [ + w for w in sec_w if w["address"] == i["address"] + ]: sec_to_rmv.append(i["address"]) # Check if new primary is currently a secondary @@ -420,7 +439,9 @@ def generate_delete_commands(self, obj): if "evpn_multisite_tracking" in obj: have = self.existing_facts.get(name, {}) if have.get("evpn_multisite_tracking", False) is not False: - cmd = "no evpn multisite %s" % have.get("evpn_multisite_tracking") + cmd = "no evpn multisite %s" % have.get( + "evpn_multisite_tracking" + ) commands.append(cmd) return commands @@ -480,16 +501,22 @@ def add_commands(self, diff, name=""): self.cmd_order_fixup(commands, name) if "ipv6_redirects" in diff: # Note: device will auto-disable redirects when secondaries are present - if diff["ipv6_redirects"] != self.check_existing(name, "ipv6_redirects"): + if diff["ipv6_redirects"] != self.check_existing( + name, "ipv6_redirects" + ): no_cmd = "no " if diff["ipv6_redirects"] is False else "" commands.append(no_cmd + "ipv6 redirects") self.cmd_order_fixup(commands, name) if "unreachables" in diff: - if diff["unreachables"] != self.check_existing(name, "unreachables"): + if diff["unreachables"] != self.check_existing( + name, "unreachables" + ): no_cmd = "no " if diff["unreachables"] is False else "" commands.append(no_cmd + "ip unreachables") if "evpn_multisite_tracking" in diff: - commands.append("evpn multisite " + str(diff["evpn_multisite_tracking"])) + commands.append( + "evpn multisite " + str(diff["evpn_multisite_tracking"]) + ) if "ipv4" in diff: commands.extend(self.generate_afi_commands(diff["ipv4"])) if "ipv6" in diff: @@ -501,7 +528,11 @@ def add_commands(self, diff, name=""): def generate_afi_commands(self, diff): cmds = [] for i in diff: - cmd = "ipv6 address " if re.search("::", i["address"]) else "ip address " + cmd = ( + "ipv6 address " + if re.search("::", i["address"]) + else "ip address " + ) cmd += i["address"] if i.get("secondary"): cmd += " secondary" @@ -518,8 +549,12 @@ def set_commands(self, w, have): commands = self.add_commands(w, name=name) else: # lists of dicts must be processed separately from non-list attrs - v4_cmds = self._v4_cmds(w.pop("ipv4", []), obj_in_have.pop("ipv4", []), state="merged") - v6_cmds = self._v6_cmds(w.pop("ipv6", []), obj_in_have.pop("ipv6", []), state="merged") + v4_cmds = self._v4_cmds( + w.pop("ipv4", []), obj_in_have.pop("ipv4", []), state="merged" + ) + v6_cmds = self._v6_cmds( + w.pop("ipv6", []), obj_in_have.pop("ipv6", []), state="merged" + ) # diff remaining attrs diff = self.diff_of_dicts(w, obj_in_have) @@ -533,10 +568,16 @@ def set_commands(self, w, have): def cmd_order_fixup(self, cmds, name): """Inserts 'interface ' config at the beginning of populated command list; reorders dependent commands that must process after others.""" if cmds: - if name and not [item for item in cmds if item.startswith("interface")]: + if name and not [ + item for item in cmds if item.startswith("interface") + ]: cmds.insert(0, "interface " + name) - redirects = [item for item in cmds if re.match("(no )*ip(v6)* redirects", item)] + redirects = [ + item + for item in cmds + if re.match("(no )*ip(v6)* redirects", item) + ] if redirects: # redirects should occur after ipv4 commands, just move to end of list redirects = redirects.pop() diff --git a/plugins/module_utils/network/nxos/config/lacp/lacp.py b/plugins/module_utils/network/nxos/config/lacp/lacp.py index 526d70b85..1d1fe7576 100644 --- a/plugins/module_utils/network/nxos/config/lacp/lacp.py +++ b/plugins/module_utils/network/nxos/config/lacp/lacp.py @@ -24,7 +24,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) class Lacp(ConfigBase): @@ -132,7 +134,9 @@ def set_state(self, want, have): state = self._module.params["state"] if state in ("merged", "replaced", "rendered") and not want: self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = list() diff --git a/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py b/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py index eaad0763d..6bcb1788a 100644 --- a/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py +++ b/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py @@ -24,7 +24,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, get_interface_type, @@ -58,7 +60,9 @@ def get_lacp_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - lacp_interfaces_facts = facts["ansible_network_resources"].get("lacp_interfaces") + lacp_interfaces_facts = facts["ansible_network_resources"].get( + "lacp_interfaces" + ) if not lacp_interfaces_facts: return [] return lacp_interfaces_facts @@ -101,7 +105,9 @@ def execute_module(self): self._module.fail_json( msg="value of running_config parameter must not be empty for state parsed", ) - result["parsed"] = self.get_lacp_interfaces_facts(data=running_config) + result["parsed"] = self.get_lacp_interfaces_facts( + data=running_config + ) if self.state in self.ACTION_STATES: result["before"] = existing_lacp_interfaces_facts @@ -149,9 +155,14 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = list() @@ -164,7 +175,9 @@ def set_state(self, want, have): if state in ["merged", "rendered"]: commands.extend(self._state_merged(flatten_dict(w), have)) elif state == "replaced": - commands.extend(self._state_replaced(flatten_dict(w), have)) + commands.extend( + self._state_replaced(flatten_dict(w), have) + ) return commands def _state_replaced(self, w, have): @@ -205,7 +218,9 @@ def _state_overridden(self, want, have): commands = [] for h in have: h = flatten_dict(h) - obj_in_want = flatten_dict(search_obj_in_list(h["name"], want, "name")) + obj_in_want = flatten_dict( + search_obj_in_list(h["name"], want, "name") + ) if h == obj_in_want: continue for w in want: @@ -240,7 +255,9 @@ def _state_deleted(self, want, have): commands = [] if want: for w in want: - obj_in_have = flatten_dict(search_obj_in_list(w["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(w["name"], have, "name") + ) commands.extend(self.del_attribs(obj_in_have)) else: if not have: diff --git a/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py b/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py index fc3202a7f..e5fbacc9a 100644 --- a/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py +++ b/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py @@ -25,7 +25,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( normalize_interface, ) @@ -54,7 +56,9 @@ def get_lag_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - lag_interfaces_facts = facts["ansible_network_resources"].get("lag_interfaces") + lag_interfaces_facts = facts["ansible_network_resources"].get( + "lag_interfaces" + ) if not lag_interfaces_facts: return [] return lag_interfaces_facts @@ -103,7 +107,9 @@ def execute_module(self): self._module.fail_json( msg="value of running_config parameter must not be empty for state parsed", ) - result["parsed"] = self.get_lag_interfaces_facts(data=running_config) + result["parsed"] = self.get_lag_interfaces_facts( + data=running_config + ) if self.state in self.ACTION_STATES: result["before"] = existing_lag_interfaces_facts @@ -130,7 +136,9 @@ def set_config(self, existing_lag_interfaces_facts): w.update(remove_empties(w)) if "members" in w and w["members"]: for item in w["members"]: - item.update({"member": normalize_interface(item["member"])}) + item.update( + {"member": normalize_interface(item["member"])} + ) have = existing_lag_interfaces_facts resp = self.set_state(want, have) return to_list(resp) @@ -145,9 +153,14 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = list() @@ -189,7 +202,9 @@ def _state_overridden(self, want, have): for h in have: obj_in_want = search_obj_in_list(h["name"], want, "name") if obj_in_want: - diff = self.diff_list_of_dicts(h.get("members", []), obj_in_want["members"]) + diff = self.diff_list_of_dicts( + h.get("members", []), obj_in_want["members"] + ) if not diff: continue commands.extend(self.del_all_commands(h)) @@ -234,7 +249,9 @@ def diff_list_of_dicts(self, want, have): diff = [] for w_item in want: - h_item = search_obj_in_list(w_item["member"], have, key="member") or {} + h_item = ( + search_obj_in_list(w_item["member"], have, key="member") or {} + ) delta = dict_diff(h_item, w_item) if delta: if h_item: @@ -302,7 +319,9 @@ def set_commands(self, w, have): else: if "members" not in obj_in_have: obj_in_have["members"] = None - diff = self.diff_list_of_dicts(w["members"], obj_in_have["members"]) + diff = self.diff_list_of_dicts( + w["members"], obj_in_have["members"] + ) commands = self.add_commands(diff, w["name"]) return commands @@ -319,7 +338,9 @@ def del_intf_commands(self, w, have): commands = [] obj_in_have = search_obj_in_list(w["name"], have, "name") if obj_in_have: - lst_to_del = self.intersect_list_of_dicts(w["members"], obj_in_have["members"]) + lst_to_del = self.intersect_list_of_dicts( + w["members"], obj_in_have["members"] + ) if lst_to_del: for item in lst_to_del: commands.append("interface" + " " + item["member"]) diff --git a/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py b/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py index 85f39682c..455939c62 100644 --- a/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py +++ b/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py @@ -23,7 +23,9 @@ remove_empties, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) class Lldp_global(ConfigBase): @@ -49,7 +51,9 @@ def get_lldp_global_facts(self, data=None): self.gather_network_resources, data=data, ) - lldp_global_facts = facts["ansible_network_resources"].get("lldp_global") + lldp_global_facts = facts["ansible_network_resources"].get( + "lldp_global" + ) if not lldp_global_facts: return {} return lldp_global_facts @@ -130,7 +134,9 @@ def set_state(self, want, have): state = self._module.params["state"] if state in ("merged", "replaced", "rendered") and not want: self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = list() @@ -173,7 +179,9 @@ def delete_nested_dict(self, have, want): return inner_dict else: if key in want.keys(): - outer_dict.update({key: self.delete_nested_dict(val, want[key])}) + outer_dict.update( + {key: self.delete_nested_dict(val, want[key])} + ) else: outer_dict.update({key: val}) return outer_dict @@ -189,7 +197,11 @@ def find_delete_params(self, have, want): else: if key == "tlv_select": delete_dict.update( - {key: self.delete_nested_dict(have["tlv_select"], want["tlv_select"])}, + { + key: self.delete_nested_dict( + have["tlv_select"], want["tlv_select"] + ) + }, ) return delete_dict diff --git a/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py b/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py index 528f74970..2fbfc9fe9 100644 --- a/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py +++ b/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py @@ -24,7 +24,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, get_interface_type, @@ -56,7 +58,9 @@ def get_lldp_interfaces_facts(self, data=None): self.gather_network_resources, data=data, ) - lldp_interfaces_facts = facts["ansible_network_resources"].get("lldp_interfaces") + lldp_interfaces_facts = facts["ansible_network_resources"].get( + "lldp_interfaces" + ) if not lldp_interfaces_facts: return [] return lldp_interfaces_facts @@ -154,7 +158,9 @@ def set_state(self, want, have): if state == "merged": commands.extend(self._state_merged(flatten_dict(w), have)) elif state == "replaced": - commands.extend(self._state_replaced(flatten_dict(w), have)) + commands.extend( + self._state_replaced(flatten_dict(w), have) + ) return commands def _state_parsed(self, want): @@ -187,7 +193,9 @@ def _state_replaced(self, want, have): commands = [] del_commands = [] delete_dict = {} - obj_in_have = flatten_dict(search_obj_in_list(want["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(want["name"], have, "name") + ) for k1 in obj_in_have.keys(): if k1 not in want.keys(): delete_dict.update({k1: obj_in_have[k1]}) @@ -252,7 +260,9 @@ def _state_deleted(self, want, have): commands = [] if want: for w in want: - obj_in_have = flatten_dict(search_obj_in_list(w["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(w["name"], have, "name") + ) commands.extend(self.del_commands(obj_in_have)) else: if not have: @@ -263,7 +273,9 @@ def _state_deleted(self, want, have): def set_commands(self, want, have): commands = [] - obj_in_have = flatten_dict(search_obj_in_list(want["name"], have, "name")) + obj_in_have = flatten_dict( + search_obj_in_list(want["name"], have, "name") + ) if not obj_in_have: commands = self.add_commands(flatten_dict(want)) else: @@ -289,7 +301,9 @@ def add_commands(self, d): else: commands.append("no lldp receive") if "management_address" in d: - commands.append("lldp tlv-set management-address " + d["management_address"]) + commands.append( + "lldp tlv-set management-address " + d["management_address"] + ) if "vlan" in d: commands.append("lldp tlv-set vlan " + str(d["vlan"])) @@ -305,7 +319,10 @@ def del_commands(self, obj): if "receive" in obj: commands.append("lldp receive") if "management_address" in obj: - commands.append("no lldp tlv-set management-address " + obj["management_address"]) + commands.append( + "no lldp tlv-set management-address " + + obj["management_address"] + ) if "vlan" in obj: commands.append("no lldp tlv-set vlan " + str(obj["vlan"])) diff --git a/plugins/module_utils/network/nxos/config/logging_global/logging_global.py b/plugins/module_utils/network/nxos/config/logging_global/logging_global.py index 6e493ad36..b9a3cf00e 100644 --- a/plugins/module_utils/network/nxos/config/logging_global/logging_global.py +++ b/plugins/module_utils/network/nxos/config/logging_global/logging_global.py @@ -29,7 +29,9 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.logging_global import ( Logging_globalTemplate, ) diff --git a/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py b/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py index 57a1a58d9..823f09008 100644 --- a/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py +++ b/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py @@ -28,7 +28,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ntp_global import ( Ntp_globalTemplate, ) @@ -148,7 +150,9 @@ def _ntp_list_to_dict(self, data): if "access_group" in tmp: for x in ["peer", "query_only", "serve", "serve_only"]: if x in tmp["access_group"]: - tmp["access_group"][x] = {i["access_list"]: i for i in tmp["access_group"][x]} + tmp["access_group"][x] = { + i["access_list"]: i for i in tmp["access_group"][x] + } pkey = { "authentication_keys": "id", "peers": "peer", diff --git a/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py b/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py index 0a1bc5806..ca201d7e5 100644 --- a/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py @@ -26,7 +26,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ospf_interfaces import ( Ospf_interfacesTemplate, ) @@ -90,7 +92,9 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } wantd = {} # remove superfluous config for overridden and deleted @@ -111,7 +115,9 @@ def _compare(self, want, have): begin = len(self.commands) self._compare_ospf_interfaces(want, have) if len(self.commands) != begin: - self.commands.insert(begin, self._tmplt.render(want or have, "interface", False)) + self.commands.insert( + begin, self._tmplt.render(want or have, "interface", False) + ) def _compare_ospf_interfaces(self, want, have): waf = want.get("address_family", {}) @@ -130,10 +136,15 @@ def _compare_ospf_interfaces(self, want, have): # this ensures that the "no" form of "ip ospf passive-interface" # command is executed even when there is no existing config - if witem.get("passive_interface") is False and "passive_interface" not in hitem: + if ( + witem.get("passive_interface") is False + and "passive_interface" not in hitem + ): hitem["passive_interface"] = True - if "passive_interface" in hitem and witem.get("default_passive_interface"): + if "passive_interface" in hitem and witem.get( + "default_passive_interface" + ): self.commands.append(self._generate_passive_intf(witem)) self.compare(parsers=self.parsers, want=witem, have=hitem) @@ -141,14 +152,20 @@ def _compare_ospf_interfaces(self, want, have): # compare top-level `multi_areas` config for area in witem.get("multi_areas", []): if area not in hitem.get("multi_areas", []): - self.addcmd({"afi": afi, "area": area}, "multi_areas", negate=False) + self.addcmd( + {"afi": afi, "area": area}, "multi_areas", negate=False + ) # remove superfluous top-level `multi_areas` config for area in hitem.get("multi_areas", []): if area not in witem.get("multi_areas", []): - self.addcmd({"afi": afi, "area": area}, "multi_areas", negate=True) + self.addcmd( + {"afi": afi, "area": area}, "multi_areas", negate=True + ) # compare config->address_family->processes - self._compare_processes(afi, witem.get("processes", {}), hitem.get("processes", {})) + self._compare_processes( + afi, witem.get("processes", {}), hitem.get("processes", {}) + ) def _compare_processes(self, afi, want, have): # add and update config->address_family->processes @@ -165,12 +182,16 @@ def _compare_processes(self, afi, want, have): for area in wproc.get("multi_areas", []): if area not in hproc.get("multi_areas", []): marea_dict["area"] = area - self.addcmd(marea_dict, "processes_multi_areas", negate=False) + self.addcmd( + marea_dict, "processes_multi_areas", negate=False + ) # remove superfluous processes->multi_areas config for area in hproc.get("multi_areas", []): if area not in wproc.get("multi_areas", []): marea_dict["area"] = area - self.addcmd(marea_dict, "processes_multi_areas", negate=True) + self.addcmd( + marea_dict, "processes_multi_areas", negate=True + ) # remove superflous config->address_family->processes for hproc in have.values(): @@ -189,10 +210,12 @@ def _list_to_dict(self, entry): for item in entry.values(): for ag in item.get("address_family", []): ag["processes"] = { - subentry["process_id"]: subentry for subentry in ag.get("processes", []) + subentry["process_id"]: subentry + for subentry in ag.get("processes", []) } item["address_family"] = { - subentry["afi"]: subentry for subentry in item.get("address_family", []) + subentry["afi"]: subentry + for subentry in item.get("address_family", []) } def _generate_passive_intf(self, data): diff --git a/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py b/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py index 8a6f42e7a..03ea3e3f3 100644 --- a/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py +++ b/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py @@ -25,7 +25,9 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ospfv2 import ( Ospfv2Template, ) @@ -91,8 +93,14 @@ def gen_config(self): :returns: the commands necessary to migrate the current configuration to the desired configuration """ - wantd = {(entry["process_id"]): entry for entry in self.want.get("processes", [])} - haved = {(entry["process_id"]): entry for entry in self.have.get("processes", [])} + wantd = { + (entry["process_id"]): entry + for entry in self.want.get("processes", []) + } + haved = { + (entry["process_id"]): entry + for entry in self.have.get("processes", []) + } # turn all lists of dicts into dicts prior to merge for entry in wantd, haved: @@ -104,7 +112,9 @@ def gen_config(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } wantd = {} # if state is overridden, first remove processes that are in have but not in want @@ -128,7 +138,9 @@ def _compare(self, want, have): begin, self._tmplt.render( want or have, - "vrf" if "vrf" in (want.keys() or have.keys()) else "process_id", + "vrf" + if "vrf" in (want.keys() or have.keys()) + else "process_id", False, ), ) @@ -193,24 +205,34 @@ def _vrfs_compare(self, want, have): def _ospf_list_to_dict(self, entry): for _pid, proc in iteritems(entry): for area in proc.get("areas", []): - area["ranges"] = {entry["prefix"]: entry for entry in area.get("ranges", [])} + area["ranges"] = { + entry["prefix"]: entry for entry in area.get("ranges", []) + } area["filter_list"] = { - entry["direction"]: entry for entry in area.get("filter_list", []) + entry["direction"]: entry + for entry in area.get("filter_list", []) } mpls_areas = { entry["area_id"]: entry - for entry in proc.get("mpls", {}).get("traffic_eng", {}).get("areas", []) + for entry in proc.get("mpls", {}) + .get("traffic_eng", {}) + .get("areas", []) } if mpls_areas: proc["mpls"]["traffic_eng"]["areas"] = mpls_areas - proc["areas"] = {entry["area_id"]: entry for entry in proc.get("areas", [])} + proc["areas"] = { + entry["area_id"]: entry for entry in proc.get("areas", []) + } proc["summary_address"] = { - entry["prefix"]: entry for entry in proc.get("summary_address", []) + entry["prefix"]: entry + for entry in proc.get("summary_address", []) } proc["redistribute"] = { (entry.get("id"), entry["protocol"]): entry for entry in proc.get("redistribute", []) } if "vrfs" in proc: - proc["vrfs"] = {entry["vrf"]: entry for entry in proc.get("vrfs", [])} + proc["vrfs"] = { + entry["vrf"]: entry for entry in proc.get("vrfs", []) + } self._ospf_list_to_dict(proc["vrfs"]) diff --git a/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py b/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py index e60fc31a2..0d08d85d7 100644 --- a/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py +++ b/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py @@ -27,7 +27,9 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ospfv3 import ( Ospfv3Template, ) @@ -81,8 +83,14 @@ def generate_commands(self): """Generate configuration commands to send based on want, have and desired state. """ - wantd = {(entry["process_id"]): entry for entry in self.want.get("processes", [])} - haved = {(entry["process_id"]): entry for entry in self.have.get("processes", [])} + wantd = { + (entry["process_id"]): entry + for entry in self.want.get("processes", []) + } + haved = { + (entry["process_id"]): entry + for entry in self.have.get("processes", []) + } # turn all lists of dicts into dicts prior to merge for entry in wantd, haved: @@ -94,7 +102,9 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } wantd = {} # if state is overridden, first remove processes that are in have but not in want @@ -123,7 +133,9 @@ def _compare(self, want, have): begin, self._tmplt.render( want or have, - "vrf" if "vrf" in (want.keys() or have.keys()) else "process_id", + "vrf" + if "vrf" in (want.keys() or have.keys()) + else "process_id", False, ), ) @@ -209,22 +221,33 @@ def _af_compare_lists(self, want, have): def _ospfv3_list_to_dict(self, entry): for _pid, proc in iteritems(entry): - proc["areas"] = {entry["area_id"]: entry for entry in proc.get("areas", [])} + proc["areas"] = { + entry["area_id"]: entry for entry in proc.get("areas", []) + } af = proc.get("address_family") if af: for area in af.get("areas", []): - area["ranges"] = {entry["prefix"]: entry for entry in area.get("ranges", [])} + area["ranges"] = { + entry["prefix"]: entry + for entry in area.get("ranges", []) + } area["filter_list"] = { - entry["direction"]: entry for entry in area.get("filter_list", []) + entry["direction"]: entry + for entry in area.get("filter_list", []) } - af["areas"] = {entry["area_id"]: entry for entry in af.get("areas", [])} + af["areas"] = { + entry["area_id"]: entry for entry in af.get("areas", []) + } af["summary_address"] = { - entry["prefix"]: entry for entry in af.get("summary_address", []) + entry["prefix"]: entry + for entry in af.get("summary_address", []) } af["redistribute"] = { (entry.get("id"), entry["protocol"]): entry for entry in af.get("redistribute", []) } if "vrfs" in proc: - proc["vrfs"] = {entry["vrf"]: entry for entry in proc.get("vrfs", [])} + proc["vrfs"] = { + entry["vrf"]: entry for entry in proc.get("vrfs", []) + } self._ospfv3_list_to_dict(proc["vrfs"]) diff --git a/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py b/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py index 2c6bb8142..a7c7abf60 100644 --- a/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py +++ b/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py @@ -26,7 +26,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.prefix_lists import ( Prefix_listsTemplate, ) @@ -74,14 +76,18 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } for key, hvalue in iteritems(haved): wvalue = wantd.pop(key, {}) if wvalue: wplists = wvalue.get("prefix_lists", {}) hplists = hvalue.get("prefix_lists", {}) hvalue["prefix_lists"] = { - k: v for k, v in iteritems(hplists) if k in wplists or not wplists + k: v + for k, v in iteritems(hplists) + if k in wplists or not wplists } # remove superfluous config for overridden and deleted @@ -105,13 +111,17 @@ def _compare(self, want, have): hentry = hplists.pop(wk, {}) self.compare(["description"], want=wentry, have=hentry) # compare sequences - self._compare_seqs(wentry.pop("entries", {}), hentry.pop("entries", {})) + self._compare_seqs( + wentry.pop("entries", {}), hentry.pop("entries", {}) + ) if self.state in ["overridden", "deleted"]: # remove remaining prefix lists for h in hplists.values(): self.commands.append( - "no {0} prefix-list {1}".format(h["afi"].replace("ipv4", "ip"), h["name"]), + "no {0} prefix-list {1}".format( + h["afi"].replace("ipv4", "ip"), h["name"] + ), ) def _compare_seqs(self, want, have): @@ -142,5 +152,9 @@ def _prefix_list_transform(self, entry): if "entries" in plist: for seq in plist["entries"]: seq.update({"afi": afi, "name": plist["name"]}) - plist["entries"] = {x["sequence"]: x for x in plist["entries"]} - value["prefix_lists"] = {entry["name"]: entry for entry in value["prefix_lists"]} + plist["entries"] = { + x["sequence"]: x for x in plist["entries"] + } + value["prefix_lists"] = { + entry["name"]: entry for entry in value["prefix_lists"] + } diff --git a/plugins/module_utils/network/nxos/config/route_maps/route_maps.py b/plugins/module_utils/network/nxos/config/route_maps/route_maps.py index fa7d57b1b..8de4ab2f1 100644 --- a/plugins/module_utils/network/nxos/config/route_maps/route_maps.py +++ b/plugins/module_utils/network/nxos/config/route_maps/route_maps.py @@ -27,7 +27,9 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.route_maps import ( Route_mapsTemplate, ) @@ -130,7 +132,9 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} + haved = { + k: v for k, v in iteritems(haved) if k in wantd or not wantd + } wantd = {} # remove superfluous config for overridden and deleted @@ -138,7 +142,9 @@ def generate_commands(self): for k, have in iteritems(haved): if k not in wantd: for _hk, hentry in iteritems(have.get("entries", {})): - self.commands.append(self._tmplt.render(hentry, "route_map", True)) + self.commands.append( + self._tmplt.render(hentry, "route_map", True) + ) for wk, want in iteritems(wantd): self._compare(want=want, have=haved.pop(wk, {})) @@ -169,24 +175,38 @@ def _compare_entries(self, want, have): if self.commands[i][0:3] == "no ": self.commands.insert(pos, self.commands.pop(i)) pos += 1 - self.commands.insert(begin, self._tmplt.render(wentry, "route_map", False)) + self.commands.insert( + begin, self._tmplt.render(wentry, "route_map", False) + ) # remove superfluos entries from have for _hk, hentry in iteritems(have): self.commands.append(self._tmplt.render(hentry, "route_map", True)) def _compare_extcomm(self, want, have): - hentry = get_from_dict(data_dict=have, keypath="set.extcommunity.rt") or {} - wentry = get_from_dict(data_dict=want, keypath="set.extcommunity.rt") or {} + hentry = ( + get_from_dict(data_dict=have, keypath="set.extcommunity.rt") or {} + ) + wentry = ( + get_from_dict(data_dict=want, keypath="set.extcommunity.rt") or {} + ) h_nums = set(hentry.get("extcommunity_numbers", [])) w_nums = set(wentry.get("extcommunity_numbers", [])) - if h_nums != w_nums or wentry.get("additive") != hentry.get("additive"): + if h_nums != w_nums or wentry.get("additive") != hentry.get( + "additive" + ): if self.state not in ["merged", "rendered"]: # need to explicitly remove existing entry to correctly apply new one - self.commands.append(self._tmplt.render(hentry, "set.extcommunity.rt", negate=True)) + self.commands.append( + self._tmplt.render( + hentry, "set.extcommunity.rt", negate=True + ) + ) # default CLI behaviour is to 'merge' with existing entry - self.commands.append(self._tmplt.render(wentry, "set.extcommunity.rt", negate=False)) + self.commands.append( + self._tmplt.render(wentry, "set.extcommunity.rt", negate=False) + ) def _compare_lists(self, want, have): for x in self.complex_parsers: @@ -202,26 +222,46 @@ def _compare_lists(self, want, have): h_set[hx[i]["address"]] = hx[i] sum_set = list(set(list(w_set) + list(h_set))) for each in sum_set: - if each in w_set and each in h_set and w_set[each] == h_set[each]: + if ( + each in w_set + and each in h_set + and w_set[each] == h_set[each] + ): for i in range( 0, - len(want["set"]["ip"]["next_hop"]["verify_availability"]), + len( + want["set"]["ip"]["next_hop"][ + "verify_availability" + ] + ), ): if ( - want["set"]["ip"]["next_hop"]["verify_availability"][i]["address"] + want["set"]["ip"]["next_hop"][ + "verify_availability" + ][i]["address"] == each ): - want["set"]["ip"]["next_hop"]["verify_availability"].pop(i) + want["set"]["ip"]["next_hop"][ + "verify_availability" + ].pop(i) break for i in range( 0, - len(have["set"]["ip"]["next_hop"]["verify_availability"]), + len( + have["set"]["ip"]["next_hop"][ + "verify_availability" + ] + ), ): if ( - have["set"]["ip"]["next_hop"]["verify_availability"][i]["address"] + have["set"]["ip"]["next_hop"][ + "verify_availability" + ][i]["address"] == each ): - have["set"]["ip"]["next_hop"]["verify_availability"].pop(i) + have["set"]["ip"]["next_hop"][ + "verify_availability" + ].pop(i) break w_set.pop(each) h_set.pop(each) diff --git a/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py b/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py index 472e7285f..27e767973 100644 --- a/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py +++ b/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py @@ -29,7 +29,9 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.snmp_server import ( Snmp_serverTemplate, ) @@ -230,10 +232,14 @@ def _build_key(x): tmp = deepcopy(data) if "communities" in tmp: - tmp["communities"] = {_build_key(entry): entry for entry in tmp["communities"]} + tmp["communities"] = { + _build_key(entry): entry for entry in tmp["communities"] + } if "users" in tmp: if "auth" in tmp["users"]: - tmp["users"]["auth"] = {_build_key(entry): entry for entry in tmp["users"]["auth"]} + tmp["users"]["auth"] = { + _build_key(entry): entry for entry in tmp["users"]["auth"] + } if "use_acls" in tmp["users"]: tmp["users"]["use_acls"] = { entry["user"]: entry for entry in tmp["users"]["use_acls"] diff --git a/plugins/module_utils/network/nxos/config/static_routes/static_routes.py b/plugins/module_utils/network/nxos/config/static_routes/static_routes.py index 3b554cea5..539401115 100644 --- a/plugins/module_utils/network/nxos/config/static_routes/static_routes.py +++ b/plugins/module_utils/network/nxos/config/static_routes/static_routes.py @@ -26,7 +26,9 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.static_routes import ( Static_routesTemplate, ) @@ -92,11 +94,17 @@ def generate_commands(self): wantd = dict_merge(haved, wantd) for k, want in wantd.items(): - self._compare_top_level_keys(want=want, have=haved.pop(k, {}), vrf_name=k) + self._compare_top_level_keys( + want=want, have=haved.pop(k, {}), vrf_name=k + ) - if (self.state == "deleted" and not wantd) or self.state in ["overridden"]: + if (self.state == "deleted" and not wantd) or self.state in [ + "overridden" + ]: for k, have in haved.items(): - self._compare_top_level_keys(want={}, have=have, vrf_name=k) + self._compare_top_level_keys( + want={}, have=have, vrf_name=k + ) def _compare_top_level_keys(self, want, have, vrf_name): begin = len(self.commands) @@ -117,7 +125,9 @@ def _compare_top_level_keys(self, want, have, vrf_name): if self.state != "deleted": for _afi, routes in want.items(): - self._compare(s_want=routes, s_have=have.pop(_afi, {}), afi=_afi) + self._compare( + s_want=routes, s_have=have.pop(_afi, {}), afi=_afi + ) if self.state in ["overridden", "deleted"]: for _afi, routes in have.items(): @@ -131,7 +141,10 @@ def _compare_top_level_keys(self, want, have, vrf_name): # afi_cmds.append(self.commands.pop()) # self.commands = afi_cmds + self.commands else: - self.commands.insert(begin, self._tmplt.render({"namevrf": vrf_name}, "vrf", False)) + self.commands.insert( + begin, + self._tmplt.render({"namevrf": vrf_name}, "vrf", False), + ) def _compare(self, s_want, s_have, afi): for name, w_srs in s_want.items(): @@ -173,7 +186,9 @@ def list_to_dict(self, param, operation): _delete_spc[_afi].append(_dest) for nxh in rts.get("next_hops", []): - _forw_rtr_add = nxh.get("forward_router_address", "").upper() + _forw_rtr_add = nxh.get( + "forward_router_address", "" + ).upper() _intf = nxh.get("interface", "") _key = _dest + "_" + _forw_rtr_add + _intf @@ -187,7 +202,9 @@ def list_to_dict(self, param, operation): if _intf: dummy_sr["interface"] = _intf if _forw_rtr_add: - dummy_sr["forward_router_address"] = _forw_rtr_add + dummy_sr[ + "forward_router_address" + ] = _forw_rtr_add dummy_sr.update(nxh) _routes[_key] = dummy_sr diff --git a/plugins/module_utils/network/nxos/config/telemetry/telemetry.py b/plugins/module_utils/network/nxos/config/telemetry/telemetry.py index da3f77439..f561215fd 100644 --- a/plugins/module_utils/network/nxos/config/telemetry/telemetry.py +++ b/plugins/module_utils/network/nxos/config/telemetry/telemetry.py @@ -18,7 +18,9 @@ from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import ( ConfigBase, ) -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.cmdref.telemetry.telemetry import ( TMS_DESTGROUP, @@ -26,8 +28,12 @@ TMS_SENSORGROUP, TMS_SUBSCRIPTION, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import NxosCmdRef +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( + NxosCmdRef, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.telemetry.telemetry import ( get_module_params_subsection, get_setval_path, @@ -83,18 +89,24 @@ def execute_module(self): state = self._module.params["state"] if "overridden" in state: - self._module.fail_json(msg="State is invalid for this module.") + self._module.fail_json( + msg="State is invalid for this module." + ) # When state is 'deleted', the module_params should not contain data # under the 'config' key if "deleted" in state and self._module.params.get("config"): - self._module.fail_json(msg="Remove config key from playbook when state is ") + self._module.fail_json( + msg="Remove config key from playbook when state is " + ) if self._module.params["config"] is None: self._module.params["config"] = {} # Normalize interface name. int = self._module.params["config"].get("source_interface") if int: - self._module.params["config"]["source_interface"] = normalize_interface(int) + self._module.params["config"][ + "source_interface" + ] = normalize_interface(int) if self.state in self.ACTION_STATES: existing_telemetry_facts = self.get_telemetry_facts() @@ -169,8 +181,12 @@ def set_state(self, want, have): # Build Telemetry Global NxosCmdRef Object cmd_ref["TMS_GLOBAL"]["ref"] = [] - self._module.params["config"] = get_module_params_subsection(ALL_MP, "TMS_GLOBAL") - cmd_ref["TMS_GLOBAL"]["ref"].append(NxosCmdRef(self._module, TMS_GLOBAL)) + self._module.params["config"] = get_module_params_subsection( + ALL_MP, "TMS_GLOBAL" + ) + cmd_ref["TMS_GLOBAL"]["ref"].append( + NxosCmdRef(self._module, TMS_GLOBAL) + ) ref = cmd_ref["TMS_GLOBAL"]["ref"][0] ref.set_context() ref.get_existing() @@ -188,19 +204,27 @@ def build_cmdref_objects(td): saved_ids.append(playvals["id"]) resource_key = td["cmd"].format(playvals["id"]) # Only build the NxosCmdRef object for the td['name'] module parameters. - self._module.params["config"] = get_module_params_subsection( + self._module.params[ + "config" + ] = get_module_params_subsection( ALL_MP, td["type"], playvals["id"], ) - cmd_ref[td["type"]]["ref"].append(NxosCmdRef(self._module, td["obj"])) + cmd_ref[td["type"]]["ref"].append( + NxosCmdRef(self._module, td["obj"]) + ) ref = cmd_ref[td["type"]]["ref"][-1] ref.set_context([resource_key]) - if td["type"] == "TMS_SENSORGROUP" and get_setval_path(self._module): + if td["type"] == "TMS_SENSORGROUP" and get_setval_path( + self._module + ): # Sensor group path setting can contain optional values. # Call get_setval_path helper function to process any # optional setval keys. - ref._ref["path"]["setval"] = get_setval_path(self._module) + ref._ref["path"]["setval"] = get_setval_path( + self._module + ) ref.get_existing(device_cache) ref.get_playvals() if td["type"] == "TMS_DESTGROUP": @@ -254,7 +278,9 @@ def _state_replaced(want, have): ref["tms_global"] = NxosCmdRef([], TMS_GLOBAL, ref_only=True) ref["tms_destgroup"] = NxosCmdRef([], TMS_DESTGROUP, ref_only=True) ref["tms_sensorgroup"] = NxosCmdRef([], TMS_SENSORGROUP, ref_only=True) - ref["tms_subscription"] = NxosCmdRef([], TMS_SUBSCRIPTION, ref_only=True) + ref["tms_subscription"] = NxosCmdRef( + [], TMS_SUBSCRIPTION, ref_only=True + ) # Order matters for state replaced. # First remove all subscriptions, followed by sensor-groups and destination-groups. @@ -353,20 +379,28 @@ def _state_replaced(want, have): have_resources = massaged_have.get("destination_groups") if resource == "TMS_SENSORGROUP": name = "sensor-group" - global_ctx = ref["tms_sensorgroup"]._ref["_template"]["context"] + global_ctx = ref["tms_sensorgroup"]._ref["_template"][ + "context" + ] setval = {} - setval["data_source"] = ref["tms_sensorgroup"]._ref["data_source"]["setval"] + setval["data_source"] = ref["tms_sensorgroup"]._ref[ + "data_source" + ]["setval"] setval["path"] = ref["tms_sensorgroup"]._ref["path"]["setval"] want_resources = massaged_want.get("sensor_groups") have_resources = massaged_have.get("sensor_groups") if resource == "TMS_SUBSCRIPTION": name = "subscription" - global_ctx = ref["tms_subscription"]._ref["_template"]["context"] - setval = {} - setval["destination_group"] = ref["tms_subscription"]._ref["destination_group"][ - "setval" + global_ctx = ref["tms_subscription"]._ref["_template"][ + "context" ] - setval["sensor_group"] = ref["tms_subscription"]._ref["sensor_group"]["setval"] + setval = {} + setval["destination_group"] = ref["tms_subscription"]._ref[ + "destination_group" + ]["setval"] + setval["sensor_group"] = ref["tms_subscription"]._ref[ + "sensor_group" + ]["setval"] want_resources = massaged_want.get("subscriptions") have_resources = massaged_have.get("subscriptions") @@ -395,11 +429,17 @@ def _state_replaced(want, have): cmd = {} if item.get("data_source"): cmd["data_source"] = [ - setval["data_source"].format(item["data_source"]), + setval["data_source"].format( + item["data_source"] + ), ] if item.get("path"): - setval["path"] = get_setval_path(item.get("path")) - cmd["path"] = [setval["path"].format(**item["path"])] + setval["path"] = get_setval_path( + item.get("path") + ) + cmd["path"] = [ + setval["path"].format(**item["path"]) + ] add[resource].extend(global_ctx) if property_ctx[0] not in add[resource]: add[resource].extend(property_ctx) @@ -417,13 +457,17 @@ def _state_replaced(want, have): ] if item.get("sensor_group"): cmd["sensor_group"] = [ - setval["sensor_group"].format(**item["sensor_group"]), + setval["sensor_group"].format( + **item["sensor_group"] + ), ] add[resource].extend(global_ctx) if property_ctx[0] not in add[resource]: add[resource].extend(property_ctx) if cmd.get("destination_group"): - add[resource].extend(cmd["destination_group"]) + add[resource].extend( + cmd["destination_group"] + ) if cmd.get("sensor_group"): add[resource].extend(cmd["sensor_group"]) @@ -436,7 +480,9 @@ def _state_replaced(want, have): if item is None: continue # item wanted but does not exist so add it - property_ctx = ["{0} {1}".format(name, want_key)] + property_ctx = [ + "{0} {1}".format(name, want_key) + ] if resource == "TMS_DESTGROUP": cmd = [setval.format(**item[cmd_property])] add[resource].extend(global_ctx) @@ -447,16 +493,26 @@ def _state_replaced(want, have): cmd = {} if item.get("data_source"): cmd["data_source"] = [ - setval["data_source"].format(item["data_source"]), + setval["data_source"].format( + item["data_source"] + ), ] if item.get("path"): - setval["path"] = get_setval_path(item.get("path")) - cmd["path"] = [setval["path"].format(**item["path"])] + setval["path"] = get_setval_path( + item.get("path") + ) + cmd["path"] = [ + setval["path"].format( + **item["path"] + ) + ] add[resource].extend(global_ctx) if property_ctx[0] not in add[resource]: add[resource].extend(property_ctx) if cmd.get("data_source"): - add[resource].extend(cmd["data_source"]) + add[resource].extend( + cmd["data_source"] + ) if cmd.get("path"): add[resource].extend(cmd["path"]) if resource == "TMS_SUBSCRIPTION": @@ -469,15 +525,21 @@ def _state_replaced(want, have): ] if item.get("sensor_group"): cmd["sensor_group"] = [ - setval["sensor_group"].format(**item["sensor_group"]), + setval["sensor_group"].format( + **item["sensor_group"] + ), ] add[resource].extend(global_ctx) if property_ctx[0] not in add[resource]: add[resource].extend(property_ctx) if cmd.get("destination_group"): - add[resource].extend(cmd["destination_group"]) + add[resource].extend( + cmd["destination_group"] + ) if cmd.get("sensor_group"): - add[resource].extend(cmd["sensor_group"]) + add[resource].extend( + cmd["sensor_group"] + ) # process haves: for have_key in have_resources.keys(): @@ -495,9 +557,14 @@ def _state_replaced(want, have): if item is None: continue # have item not wanted so remove it - property_ctx = ["{0} {1}".format(name, have_key)] + property_ctx = [ + "{0} {1}".format(name, have_key) + ] if resource == "TMS_DESTGROUP": - cmd = ["no " + setval.format(**item[cmd_property])] + cmd = [ + "no " + + setval.format(**item[cmd_property]) + ] delete[resource].extend(global_ctx) if property_ctx[0] not in delete[resource]: delete[resource].extend(property_ctx) @@ -507,18 +574,27 @@ def _state_replaced(want, have): if item.get("data_source"): cmd["data_source"] = [ "no " - + setval["data_source"].format(item["data_source"]), + + setval["data_source"].format( + item["data_source"] + ), ] if item.get("path"): - setval["path"] = get_setval_path(item.get("path")) + setval["path"] = get_setval_path( + item.get("path") + ) cmd["path"] = [ - "no " + setval["path"].format(**item["path"]), + "no " + + setval["path"].format( + **item["path"] + ), ] delete[resource].extend(global_ctx) if property_ctx[0] not in delete[resource]: delete[resource].extend(property_ctx) if cmd.get("data_source"): - delete[resource].extend(cmd["data_source"]) + delete[resource].extend( + cmd["data_source"] + ) if cmd.get("path"): delete[resource].extend(cmd["path"]) if resource == "TMS_SUBSCRIPTION": @@ -526,22 +602,30 @@ def _state_replaced(want, have): if item.get("destination_group"): cmd["destination_group"] = [ "no " - + setval["destination_group"].format( + + setval[ + "destination_group" + ].format( item["destination_group"], ), ] if item.get("sensor_group"): cmd["sensor_group"] = [ "no " - + setval["sensor_group"].format(**item["sensor_group"]), + + setval["sensor_group"].format( + **item["sensor_group"] + ), ] delete[resource].extend(global_ctx) if property_ctx[0] not in delete[resource]: delete[resource].extend(property_ctx) if cmd.get("destination_group"): - delete[resource].extend(cmd["destination_group"]) + delete[resource].extend( + cmd["destination_group"] + ) if cmd.get("sensor_group"): - delete[resource].extend(cmd["sensor_group"]) + delete[resource].extend( + cmd["sensor_group"] + ) add[resource] = remove_duplicate_context(add[resource]) delete[resource] = remove_duplicate_context(delete[resource]) diff --git a/plugins/module_utils/network/nxos/config/vlans/vlans.py b/plugins/module_utils/network/nxos/config/vlans/vlans.py index 515618ad8..5f5775ddf 100644 --- a/plugins/module_utils/network/nxos/config/vlans/vlans.py +++ b/plugins/module_utils/network/nxos/config/vlans/vlans.py @@ -27,7 +27,9 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( search_obj_in_list, ) @@ -150,9 +152,14 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if state in ("overridden", "merged", "replaced", "rendered") and not want: + if ( + state in ("overridden", "merged", "replaced", "rendered") + and not want + ): self._module.fail_json( - msg="value of config parameter must not be empty for state {0}".format(state), + msg="value of config parameter must not be empty for state {0}".format( + state + ), ) commands = list() diff --git a/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py b/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py index 053b56a91..18df7c068 100644 --- a/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py @@ -19,7 +19,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acl_interfaces.acl_interfaces import ( Acl_interfacesArgs, @@ -62,7 +64,9 @@ def populate_facts(self, connection, ansible_facts, data=None): for i in range(len(data)): intf = data[i].split("\n") for l in range(1, len(intf)): - if not re.search("ip(v6)?( port)? (access-group|traffic-filter)", intf[l]): + if not re.search( + "ip(v6)?( port)? (access-group|traffic-filter)", intf[l] + ): intf[l] = "" intf = list(filter(None, intf)) resources.append(intf) @@ -77,7 +81,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("acl_interfaces", None) facts = {} if objs: - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) params = utils.remove_empties(params) facts["acl_interfaces"] = params["config"] diff --git a/plugins/module_utils/network/nxos/facts/acls/acls.py b/plugins/module_utils/network/nxos/facts/acls/acls.py index 2a7366bc2..ad1efbe0a 100644 --- a/plugins/module_utils/network/nxos/facts/acls/acls.py +++ b/plugins/module_utils/network/nxos/facts/acls/acls.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acls.acls import ( AclsArgs, @@ -46,7 +48,9 @@ def __init__(self, module, subspec="config", options="options"): self.generated_spec = utils.generate_dict(facts_argument_spec) def get_device_data(self, connection): - data = connection.get("show running-config | section '^ip(v6)* access-list'") + data = connection.get( + "show running-config | section '^ip(v6)* access-list'" + ) if data == "{}": return "" return data @@ -85,7 +89,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("acls", None) facts = {} if objs: - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) params = utils.remove_empties(params) facts["acls"] = params["config"] @@ -122,11 +128,15 @@ def get_endpoint(self, ace, pro): if "range" not in ace.split()[0]: port_pro = re.search(r"(eq|lt|gt|neq) (\S+)", ace) if port_pro: - port_protocol.update({port_pro.group(1): port_pro.group(2)}) + port_protocol.update( + {port_pro.group(1): port_pro.group(2)} + ) ace = re.sub(port_pro.group(1), "", ace, 1) ace = re.sub(port_pro.group(2), "", ace, 1) else: - limit = re.search(r"range\s(?P\S+)\s(?P\S+)", ace) + limit = re.search( + r"range\s(?P\S+)\s(?P\S+)", ace + ) if limit: rstart = limit.groupdict()["rstart"] rend = limit.groupdict()["rend"] @@ -253,7 +263,9 @@ def render_config(self, spec, conf): acl = acl.split("\n") acl = [a.strip() for a in acl] acl = list(filter(None, acl)) - acls["name"] = re.match(r"(ip)?(v6)?\s?access-list (.*)", acl[0]).group( + acls["name"] = re.match( + r"(ip)?(v6)?\s?access-list (.*)", acl[0] + ).group( 3, ) acls["aces"] = [] @@ -311,14 +323,21 @@ def render_config(self, spec, conf): pro_options = {} options = {} for option in protocol_options[pro]: - if option not in ["telemetry_path", "telemetry_queue"]: + if option not in [ + "telemetry_path", + "telemetry_queue", + ]: option = re.sub("_", "-", option) if option in ace: if option == "echo" and ( - "echo_request" in options or "echo_reply" in options + "echo_request" in options + or "echo_reply" in options ): continue - elif option == "unreachable" and "port_unreachable" in options: + elif ( + option == "unreachable" + and "port_unreachable" in options + ): continue option = re.sub("-", "_", option) options.update({option: True}) diff --git a/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py b/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py index 9d7cceac3..cbdb8dab2 100644 --- a/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py @@ -16,7 +16,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bfd_interfaces.bfd_interfaces import ( Bfd_interfacesArgs, @@ -54,7 +56,9 @@ def populate_facts(self, connection, ansible_facts, data=None): objs = [] if not data: - data = connection.get("show running-config | section '^interface|^feature bfd'") + data = connection.get( + "show running-config | section '^interface|^feature bfd'" + ) # Some of the bfd attributes if "feature bfd" in data.split("\n"): @@ -72,7 +76,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["bfd_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["bfd_interfaces"].append(utils.remove_empties(cfg)) @@ -98,7 +104,13 @@ def render_config(self, spec, conf): config["name"] = intf # 'bfd'/'bfd echo' do not nvgen when enabled thus set to 'enable' when None. # 'bfd' is not supported on some platforms - config["bfd"] = utils.parse_conf_cmd_arg(conf, "bfd", "enable", "disable") or "enable" - config["echo"] = utils.parse_conf_cmd_arg(conf, "bfd echo", "enable", "disable") or "enable" + config["bfd"] = ( + utils.parse_conf_cmd_arg(conf, "bfd", "enable", "disable") + or "enable" + ) + config["echo"] = ( + utils.parse_conf_cmd_arg(conf, "bfd echo", "enable", "disable") + or "enable" + ) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py b/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py index a1b0bc22d..9efdd88dc 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py @@ -16,7 +16,9 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_address_family.bgp_address_family import ( Bgp_address_familyArgs, @@ -58,7 +60,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self._flatten_config(data) # parse native config using the Bgp_address_family template - bgp_address_family_parser = Bgp_address_familyTemplate(lines=data.splitlines()) + bgp_address_family_parser = Bgp_address_familyTemplate( + lines=data.splitlines() + ) objs = bgp_address_family_parser.parse() if objs: nbr = [] @@ -79,7 +83,9 @@ def populate_facts(self, connection, ansible_facts, data=None): key=lambda k, s="prefix": k[s], ) if "networks" in x: - x["networks"] = sorted(x["networks"], key=lambda k, s="prefix": k[s]) + x["networks"] = sorted( + x["networks"], key=lambda k, s="prefix": k[s] + ) if "redistribute" in x: x["redistribute"] = sorted( x["redistribute"], @@ -94,9 +100,13 @@ def populate_facts(self, connection, ansible_facts, data=None): ), ) - ansible_facts["ansible_network_resources"].pop("bgp_address_family", None) + ansible_facts["ansible_network_resources"].pop( + "bgp_address_family", None + ) - params = utils.remove_empties(utils.validate_config(self.argument_spec, {"config": objs})) + params = utils.remove_empties( + utils.validate_config(self.argument_spec, {"config": objs}) + ) facts["bgp_address_family"] = params.get("config", {}) ansible_facts["ansible_network_resources"].update(facts) diff --git a/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py b/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py index 9e149d8f6..cef7b52b4 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py @@ -16,7 +16,9 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_global.bgp_global import ( Bgp_globalArgs, @@ -57,7 +59,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self._flatten_config(data) # parse native config using the Bgp_global template - bgp_global_parser = Bgp_globalTemplate(lines=data.splitlines(), module=self._module) + bgp_global_parser = Bgp_globalTemplate( + lines=data.splitlines(), module=self._module + ) obj = bgp_global_parser.parse() vrfs = obj.get("vrfs", {}) @@ -71,7 +75,9 @@ def populate_facts(self, connection, ansible_facts, data=None): # transform vrfs into a list if vrfs: - obj["vrfs"] = sorted(list(obj["vrfs"].values()), key=lambda k, sk="vrf": k[sk]) + obj["vrfs"] = sorted( + list(obj["vrfs"].values()), key=lambda k, sk="vrf": k[sk] + ) for vrf in obj["vrfs"]: self._post_parse(vrf) @@ -81,7 +87,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("bgp_global", None) params = utils.remove_empties( - bgp_global_parser.validate_config(self.argument_spec, {"config": obj}, redact=True), + bgp_global_parser.validate_config( + self.argument_spec, {"config": obj}, redact=True + ), ) facts["bgp_global"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py index 625ed5082..5b0eed8b3 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_neighbor_address_family.bgp_neighbor_address_family import ( Bgp_neighbor_address_familyArgs, @@ -57,21 +59,29 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self._flatten_config(data) # parse native config using the Bgp_neighbor_address_family template - bgp_neighbor_address_family_parser = Bgp_neighbor_address_familyTemplate(lines=data) + bgp_neighbor_address_family_parser = ( + Bgp_neighbor_address_familyTemplate(lines=data) + ) objs = bgp_neighbor_address_family_parser.parse() if objs: top_lvl_nbrs = objs.get("vrfs", {}).pop("vrf_", {}) - objs["neighbors"] = self._post_parse(top_lvl_nbrs).get("neighbors", []) + objs["neighbors"] = self._post_parse(top_lvl_nbrs).get( + "neighbors", [] + ) if "vrfs" in objs: for vrf in objs["vrfs"].values(): vrf["neighbors"] = self._post_parse(vrf)["neighbors"] objs["vrfs"] = list(objs["vrfs"].values()) - ansible_facts["ansible_network_resources"].pop("bgp_neighbor_address_family", None) + ansible_facts["ansible_network_resources"].pop( + "bgp_neighbor_address_family", None + ) - params = utils.remove_empties(utils.validate_config(self.argument_spec, {"config": objs})) + params = utils.remove_empties( + utils.validate_config(self.argument_spec, {"config": objs}) + ) facts["bgp_neighbor_address_family"] = params.get("config", {}) ansible_facts["ansible_network_resources"].update(facts) diff --git a/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py b/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py index 021e518a7..8f24cfc45 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py @@ -16,7 +16,9 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_templates.bgp_templates import ( Bgp_templatesArgs, @@ -37,8 +39,12 @@ def get_config(self, connection): """Wrapper method for `connection.get()` This method exists solely to allow the unit test framework to mock device connection calls. """ - as_number = connection.get("show running-config bgp | include 'router bgp'") - templates = connection.get("show running-config bgp | section 'template'") + as_number = connection.get( + "show running-config bgp | include 'router bgp'" + ) + templates = connection.get( + "show running-config bgp | section 'template'" + ) return as_number + "\n" + templates @@ -60,7 +66,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self._flatten_config(data) # parse native config using the Bgp_templates template - bgp_templates_parser = Bgp_templatesTemplate(lines=data, module=self._module) + bgp_templates_parser = Bgp_templatesTemplate( + lines=data, module=self._module + ) parsed = bgp_templates_parser.parse() objs = {} @@ -72,7 +80,9 @@ def populate_facts(self, connection, ansible_facts, data=None): objs[k] = list(v.values()) for x in objs[k]: if "address_family" in x: - x["address_family"] = list(x["address_family"].values()) + x["address_family"] = list( + x["address_family"].values() + ) for nbr in objs.get("neighbor", []): for af in nbr.get("address_family", []): @@ -88,7 +98,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("bgp_templates", None) params = utils.remove_empties( - bgp_templates_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + bgp_templates_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["bgp_templates"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/facts.py b/plugins/module_utils/network/nxos/facts/facts.py index a7c2ab350..4f1baa5f8 100644 --- a/plugins/module_utils/network/nxos/facts/facts.py +++ b/plugins/module_utils/network/nxos/facts/facts.py @@ -177,7 +177,9 @@ def get_resource_subsets(self): facts_resource_subsets = MDS_FACT_RESOURCE_SUBSETS return facts_resource_subsets - def get_facts(self, legacy_facts_type=None, resource_facts_type=None, data=None): + def get_facts( + self, legacy_facts_type=None, resource_facts_type=None, data=None + ): """Collect the facts for nxos :param legacy_facts_type: List of legacy facts types :param resource_facts_type: List of resource fact types @@ -188,9 +190,13 @@ def get_facts(self, legacy_facts_type=None, resource_facts_type=None, data=None) VALID_RESOURCE_SUBSETS = self.get_resource_subsets() if frozenset(VALID_RESOURCE_SUBSETS.keys()): - self.get_network_resources_facts(VALID_RESOURCE_SUBSETS, resource_facts_type, data) + self.get_network_resources_facts( + VALID_RESOURCE_SUBSETS, resource_facts_type, data + ) if self.VALID_LEGACY_GATHER_SUBSETS: - self.get_network_legacy_facts(FACT_LEGACY_SUBSETS, legacy_facts_type) + self.get_network_legacy_facts( + FACT_LEGACY_SUBSETS, legacy_facts_type + ) return self.ansible_facts, self._warnings diff --git a/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py b/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py index e9d85c086..6f25c4deb 100644 --- a/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py @@ -8,7 +8,9 @@ import operator import re -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.fc_interfaces.fc_interfaces import ( Fc_interfacesArgs, @@ -55,7 +57,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_interfaces_data(connection) # parse native config using the Fc_interfaces template - fc_interfaces_parser = Fc_interfacesTemplate(lines=data.splitlines(), module=self._module) + fc_interfaces_parser = Fc_interfacesTemplate( + lines=data.splitlines(), module=self._module + ) objs = list(fc_interfaces_parser.parse().values()) @@ -87,14 +91,20 @@ def populate_facts(self, connection, ansible_facts, data=None): sorted_dict = sorted(modified_objs, key=operator.itemgetter("m", "p")) objs = [ - {key: value for key, value in eachdict.items() if key not in ["m", "p"]} + { + key: value + for key, value in eachdict.items() + if key not in ["m", "p"] + } for eachdict in sorted_dict ] ansible_facts["ansible_network_resources"].pop("fc_interfaces", None) params = utils.remove_empties( - fc_interfaces_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + fc_interfaces_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["fc_interfaces"] = params.get("config", []) diff --git a/plugins/module_utils/network/nxos/facts/hostname/hostname.py b/plugins/module_utils/network/nxos/facts/hostname/hostname.py index 981648c0c..56300fc1a 100644 --- a/plugins/module_utils/network/nxos/facts/hostname/hostname.py +++ b/plugins/module_utils/network/nxos/facts/hostname/hostname.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.hostname.hostname import ( HostnameArgs, @@ -55,13 +57,17 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_config(connection) # parse native config using the Hostname template - hostname_parser = HostnameTemplate(lines=data.splitlines(), module=self._module) + hostname_parser = HostnameTemplate( + lines=data.splitlines(), module=self._module + ) objs = hostname_parser.parse() ansible_facts["ansible_network_resources"].pop("hostname", None) params = utils.remove_empties( - hostname_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + hostname_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["hostname"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py b/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py index d12e32233..f8bb5a3b9 100644 --- a/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py @@ -16,7 +16,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.hsrp_interfaces.hsrp_interfaces import ( Hsrp_interfacesArgs, @@ -67,7 +69,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["hsrp_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["hsrp_interfaces"].append(utils.remove_empties(cfg)) @@ -91,6 +95,8 @@ def render_config(self, spec, conf): if get_interface_type(intf) == "unknown": return {} config["name"] = intf - config["bfd"] = utils.parse_conf_cmd_arg(conf, "hsrp bfd", "enable", "disable") + config["bfd"] = utils.parse_conf_cmd_arg( + conf, "hsrp bfd", "enable", "disable" + ) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py b/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py index 92592b07c..155afd358 100644 --- a/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py +++ b/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.interfaces.interfaces import ( InterfacesArgs, @@ -68,7 +70,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} facts["interfaces"] = [] if objs: - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["interfaces"].append(utils.remove_empties(cfg)) @@ -95,16 +99,22 @@ def render_config(self, spec, conf): config["speed"] = utils.parse_conf_arg(conf, "speed") config["mtu"] = utils.parse_conf_arg(conf, "mtu") config["duplex"] = utils.parse_conf_arg(conf, "duplex") - config["mode"] = utils.parse_conf_cmd_arg(conf, "switchport", "layer2", "layer3") + config["mode"] = utils.parse_conf_cmd_arg( + conf, "switchport", "layer2", "layer3" + ) - config["enabled"] = utils.parse_conf_cmd_arg(conf, "shutdown", False, True) + config["enabled"] = utils.parse_conf_cmd_arg( + conf, "shutdown", False, True + ) config["fabric_forwarding_anycast_gateway"] = utils.parse_conf_cmd_arg( conf, "fabric forwarding mode anycast-gateway", True, ) - config["ip_forward"] = utils.parse_conf_cmd_arg(conf, "ip forward", True) + config["ip_forward"] = utils.parse_conf_cmd_arg( + conf, "ip forward", True + ) interfaces_cfg = utils.remove_empties(config) return interfaces_cfg diff --git a/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py b/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py index cf55552b8..90a534488 100644 --- a/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.l2_interfaces.l2_interfaces import ( L2_interfacesArgs, @@ -68,7 +70,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["l2_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["l2_interfaces"].append(utils.remove_empties(cfg)) @@ -94,11 +98,15 @@ def render_config(self, spec, conf): config["name"] = intf config["mode"] = utils.parse_conf_arg(conf, "switchport mode") config["ip_forward"] = utils.parse_conf_arg(conf, "ip forward") - config["access"]["vlan"] = utils.parse_conf_arg(conf, "switchport access vlan") + config["access"]["vlan"] = utils.parse_conf_arg( + conf, "switchport access vlan" + ) config["trunk"]["allowed_vlans"] = utils.parse_conf_arg( conf, "switchport trunk allowed vlan", ) - config["trunk"]["native_vlan"] = utils.parse_conf_arg(conf, "switchport trunk native vlan") + config["trunk"]["native_vlan"] = utils.parse_conf_arg( + conf, "switchport trunk native vlan" + ) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py index ad36e17ca..d93be1f43 100644 --- a/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.l3_interfaces.l3_interfaces import ( L3_interfacesArgs, @@ -68,7 +70,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["l3_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["l3_interfaces"].append(utils.remove_empties(cfg)) @@ -91,10 +95,18 @@ def render_config(self, spec, conf): return {} config["name"] = intf config["dot1q"] = utils.parse_conf_arg(conf, "encapsulation dot1[qQ]") - config["redirects"] = utils.parse_conf_cmd_arg(conf, "no ip redirects", False, True) - config["ipv6_redirects"] = utils.parse_conf_cmd_arg(conf, "no ipv6 redirects", False, True) - config["unreachables"] = utils.parse_conf_cmd_arg(conf, "ip unreachables", True, False) - config["evpn_multisite_tracking"] = utils.parse_conf_arg(conf, "evpn multisite") + config["redirects"] = utils.parse_conf_cmd_arg( + conf, "no ip redirects", False, True + ) + config["ipv6_redirects"] = utils.parse_conf_cmd_arg( + conf, "no ipv6 redirects", False, True + ) + config["unreachables"] = utils.parse_conf_cmd_arg( + conf, "ip unreachables", True, False + ) + config["evpn_multisite_tracking"] = utils.parse_conf_arg( + conf, "evpn multisite" + ) ipv4_match = re.compile(r"\n ip address (.*)") matches = ipv4_match.findall(conf) if matches: @@ -111,7 +123,9 @@ def render_config(self, spec, conf): config_dict.update({"secondary": True}) if len(ipv4_conf) == 4: if ipv4_conf[2] == "tag": - config_dict.update({"tag": int(ipv4_conf[-1])}) + config_dict.update( + {"tag": int(ipv4_conf[-1])} + ) elif d == "tag": config_dict.update({"tag": int(ipv4_conf[-1])}) config["ipv4"].append(config_dict) diff --git a/plugins/module_utils/network/nxos/facts/lacp/lacp.py b/plugins/module_utils/network/nxos/facts/lacp/lacp.py index 51b1413da..31c29c0ef 100644 --- a/plugins/module_utils/network/nxos/facts/lacp/lacp.py +++ b/plugins/module_utils/network/nxos/facts/lacp/lacp.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lacp.lacp import ( LacpArgs, @@ -57,7 +59,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("lacp", None) facts = {} if objs: - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) facts["lacp"] = utils.remove_empties(params["config"]) ansible_facts["ansible_network_resources"].update(facts) return ansible_facts @@ -82,7 +86,9 @@ def render_config(self, spec, conf): if a_match: address = a_match.group(1) config["system"]["mac"]["address"] = address - r_match = re.search(r"lacp system-mac {0} role (\S+)".format(address), conf, re.M) + r_match = re.search( + r"lacp system-mac {0} role (\S+)".format(address), conf, re.M + ) if r_match: config["system"]["mac"]["role"] = r_match.group(1) diff --git a/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py b/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py index c60d8abd0..2d9e7beff 100644 --- a/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lacp_interfaces.lacp_interfaces import ( Lacp_interfacesArgs, @@ -69,7 +71,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["lacp_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["lacp_interfaces"].append(utils.remove_empties(cfg)) @@ -93,7 +97,9 @@ def render_config(self, spec, conf): if get_interface_type(intf) == "unknown": return {} config["name"] = intf - config["port_priority"] = utils.parse_conf_arg(conf, "lacp port-priority") + config["port_priority"] = utils.parse_conf_arg( + conf, "lacp port-priority" + ) config["rate"] = utils.parse_conf_arg(conf, "lacp rate") config["mode"] = utils.parse_conf_arg(conf, "lacp mode") suspend_individual = re.search(r"no lacp suspend-individual", conf) diff --git a/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py b/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py index b94c57e27..1f0fb0289 100644 --- a/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lag_interfaces.lag_interfaces import ( Lag_interfacesArgs, @@ -59,7 +61,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["lag_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["lag_interfaces"].append(utils.remove_empties(cfg)) @@ -96,7 +100,9 @@ def render_config(self, spec, conf, connection): member.update(match_line.groupdict()) if member and member.get("port_channel", None): - port_channel = "port-channel{0}".format(member.pop("port_channel")) + port_channel = "port-channel{0}".format( + member.pop("port_channel") + ) for x in result: if x["name"] == port_channel: x["members"].append(utils.remove_empties(member)) diff --git a/plugins/module_utils/network/nxos/facts/legacy/base.py b/plugins/module_utils/network/nxos/facts/legacy/base.py index 16540a435..6cc5447ea 100644 --- a/plugins/module_utils/network/nxos/facts/legacy/base.py +++ b/plugins/module_utils/network/nxos/facts/legacy/base.py @@ -60,7 +60,8 @@ def run(self, command, output="text"): return resp[0] except IndexError: self.warnings.append( - "command %s failed, facts for this command will not be populated" % command_string, + "command %s failed, facts for this command will not be populated" + % command_string, ) return None @@ -156,8 +157,12 @@ def populate(self): if data: if isinstance(data, dict): - self.facts["memtotal_mb"] = int(data["memory_usage_total"]) / 1024 - self.facts["memfree_mb"] = int(data["memory_usage_free"]) / 1024 + self.facts["memtotal_mb"] = ( + int(data["memory_usage_total"]) / 1024 + ) + self.facts["memfree_mb"] = ( + int(data["memory_usage_free"]) / 1024 + ) else: self.facts["memtotal_mb"] = self.parse_memtotal_mb(data) self.facts["memfree_mb"] = self.parse_memfree_mb(data) @@ -223,9 +228,13 @@ class Interfaces(FactsBase): ], ) - INTERFACE_IPV4_MAP = frozenset([("eth_ip_addr", "address"), ("eth_ip_mask", "masklen")]) + INTERFACE_IPV4_MAP = frozenset( + [("eth_ip_addr", "address"), ("eth_ip_mask", "masklen")] + ) - INTERFACE_SVI_IPV4_MAP = frozenset([("svi_ip_addr", "address"), ("svi_ip_mask", "masklen")]) + INTERFACE_SVI_IPV4_MAP = frozenset( + [("svi_ip_addr", "address"), ("svi_ip_mask", "masklen")] + ) INTERFACE_IPV6_MAP = frozenset([("addr", "address"), ("prefix", "subnet")]) @@ -249,7 +258,9 @@ def populate(self): if data: if isinstance(data, dict): - self.facts["interfaces"] = self.populate_structured_interfaces(data) + self.facts["interfaces"] = self.populate_structured_interfaces( + data + ) else: interfaces = self.parse_interfaces(data) self.facts["interfaces"] = self.populate_interfaces(interfaces) @@ -268,16 +279,22 @@ def populate(self): data = self.run("show lldp neighbors", output="json") if data: if isinstance(data, dict): - self.facts["neighbors"].update(self.populate_structured_neighbors_lldp(data)) + self.facts["neighbors"].update( + self.populate_structured_neighbors_lldp(data) + ) else: self.facts["neighbors"].update(self.populate_neighbors(data)) data = self.run("show cdp neighbors detail", output="json") if data: if isinstance(data, dict): - self.facts["neighbors"].update(self.populate_structured_neighbors_cdp(data)) + self.facts["neighbors"].update( + self.populate_structured_neighbors_cdp(data) + ) else: - self.facts["neighbors"].update(self.populate_neighbors_cdp(data)) + self.facts["neighbors"].update( + self.populate_neighbors_cdp(data) + ) self.facts["neighbors"].pop(None, None) # Remove null key @@ -298,11 +315,15 @@ def populate_structured_interfaces(self, data): intf.update(self.transform_dict(item, self.INTERFACE_MAP)) if "eth_ip_addr" in item: - intf["ipv4"] = self.transform_dict(item, self.INTERFACE_IPV4_MAP) + intf["ipv4"] = self.transform_dict( + item, self.INTERFACE_IPV4_MAP + ) self.facts["all_ipv4_addresses"].append(item["eth_ip_addr"]) if "svi_ip_addr" in item: - intf["ipv4"] = self.transform_dict(item, self.INTERFACE_SVI_IPV4_MAP) + intf["ipv4"] = self.transform_dict( + item, self.INTERFACE_SVI_IPV4_MAP + ) self.facts["all_ipv4_addresses"].append(item["svi_ip_addr"]) interfaces[name] = intf @@ -318,11 +339,15 @@ def populate_structured_ipv6_interfaces(self, data): for item in data: name = item["ROW_intf"]["intf-name"] intf = self.facts["interfaces"][name] - intf["ipv6"] = self.transform_dict(item, self.INTERFACE_IPV6_MAP) + intf["ipv6"] = self.transform_dict( + item, self.INTERFACE_IPV6_MAP + ) try: addr = item["ROW_intf"]["addr"] except KeyError: - addr = item["ROW_intf"]["TABLE_addr"]["ROW_addr"]["addr"] + addr = item["ROW_intf"]["TABLE_addr"]["ROW_addr"][ + "addr" + ] self.facts["all_ipv6_addresses"].append(addr) else: return "" @@ -348,7 +373,9 @@ def populate_structured_neighbors_lldp(self, data): def populate_structured_neighbors_cdp(self, data): objects = dict() - data = data["TABLE_cdp_neighbor_detail_info"]["ROW_cdp_neighbor_detail_info"] + data = data["TABLE_cdp_neighbor_detail_info"][ + "ROW_cdp_neighbor_detail_info" + ] if isinstance(data, dict): data = [data] @@ -379,7 +406,9 @@ def parse_interfaces(self, data): match = re.match(r"^(\S+)", line) if match: key = match.group(1) - if not key.startswith("admin") or not key.startswith("IPv6 Interface"): + if not key.startswith("admin") or not key.startswith( + "IPv6 Interface" + ): parsed[key] = line return parsed @@ -389,12 +418,18 @@ def populate_interfaces(self, interfaces): intf = dict() if get_interface_type(key) == "svi": intf["state"] = self.parse_state(key, value, intf_type="svi") - intf["macaddress"] = self.parse_macaddress(value, intf_type="svi") + intf["macaddress"] = self.parse_macaddress( + value, intf_type="svi" + ) intf["mtu"] = self.parse_mtu(value, intf_type="svi") - intf["bandwidth"] = self.parse_bandwidth(value, intf_type="svi") + intf["bandwidth"] = self.parse_bandwidth( + value, intf_type="svi" + ) intf["type"] = self.parse_type(value, intf_type="svi") if "Internet Address" in value: - intf["ipv4"] = self.parse_ipv4_address(value, intf_type="svi") + intf["ipv4"] = self.parse_ipv4_address( + value, intf_type="svi" + ) facts[key] = intf else: intf["state"] = self.parse_state(key, value) @@ -618,7 +653,9 @@ def populate(self): data = self.run("show interface", output="json") if data: if isinstance(data, dict): - self.facts["interfaces_list"] = self.parse_structured_interfaces(data) + self.facts[ + "interfaces_list" + ] = self.parse_structured_interfaces(data) else: self.facts["interfaces_list"] = self.parse_interfaces(data) @@ -646,9 +683,13 @@ def populate(self): data = self.run("show environment power", output="json") if data: if isinstance(data, dict): - self.facts["power_supply_info"] = self.parse_structured_power_supply_info(data) + self.facts[ + "power_supply_info" + ] = self.parse_structured_power_supply_info(data) else: - self.facts["power_supply_info"] = self.parse_power_supply_info(data) + self.facts["power_supply_info"] = self.parse_power_supply_info( + data + ) def parse_structured_interfaces(self, data): objects = list() @@ -680,7 +721,9 @@ def parse_structured_module(self, data): entry = entry["ROW_modinfo"] if isinstance(entry, dict): entry = [entry] - entry_objects = list(self.transform_iterable(entry, self.MODULE_MAP)) + entry_objects = list( + self.transform_iterable(entry, self.MODULE_MAP) + ) objects.extend(entry_objects) return objects diff --git a/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py b/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py index 6e8aabde2..b7693886f 100644 --- a/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py +++ b/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lldp_global.lldp_global import ( Lldp_globalArgs, @@ -59,7 +61,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("lldp_global", None) facts = {} if objs: - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) facts["lldp_global"] = params["config"] facts = utils.remove_empties(facts) ansible_facts["ansible_network_resources"].update((facts)) @@ -78,7 +82,9 @@ def render_config(self, spec, conf): config = deepcopy(spec) conf = re.split("\n", conf) for command in conf: - param = re.search(r"(.*)lldp (\w+(-?)\w+)", command) # get the word after 'lldp' + param = re.search( + r"(.*)lldp (\w+(-?)\w+)", command + ) # get the word after 'lldp' if param: # get the nested-dict/value for that param key2 = re.search(r"%s(.*)" % param.group(2), command) @@ -92,7 +98,9 @@ def render_config(self, spec, conf): key2 = key2.split() key2[0] = key2[0].replace("-", "_") if len(key2) == 1: - if "port" in key2[0] or "system" in key2[0]: # nested dicts + if ( + "port" in key2[0] or "system" in key2[0] + ): # nested dicts key2 = key2[0].split("_") # config[tlv_select][system][name]=False config[key1][key2[0]][key2[1]] = False diff --git a/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py b/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py index 4cd8b2115..58b2edf40 100644 --- a/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lldp_interfaces.lldp_interfaces import ( Lldp_interfacesArgs, @@ -83,7 +85,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["lldp_interfaces"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["lldp_interfaces"].append(utils.remove_empties(cfg)) diff --git a/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py b/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py index 189db0e41..3d59d5a59 100644 --- a/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py +++ b/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.logging_global.logging_global import ( Logging_globalArgs, @@ -59,7 +61,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_config(connection) # parse native config using the Logging_global template - logging_global_parser = Logging_globalTemplate(lines=data.splitlines(), module=self._module) + logging_global_parser = Logging_globalTemplate( + lines=data.splitlines(), module=self._module + ) objs = logging_global_parser.parse() if objs: diff --git a/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py b/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py index 258b68aaf..f66471676 100644 --- a/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py +++ b/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ntp_global.ntp_global import ( Ntp_globalArgs, @@ -55,7 +57,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_config(connection) # parse native config using the Ntp_global template - ntp_global_parser = Ntp_globalTemplate(lines=data.splitlines(), module=self._module) + ntp_global_parser = Ntp_globalTemplate( + lines=data.splitlines(), module=self._module + ) objs = ntp_global_parser.parse() if "access_group" in objs: @@ -80,7 +84,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("ntp_global", None) params = utils.remove_empties( - ntp_global_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + ntp_global_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["ntp_global"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py b/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py index 745f373b2..82a1b26e4 100644 --- a/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ospf_interfaces.ospf_interfaces import ( Ospf_interfacesArgs, @@ -69,12 +71,15 @@ def populate_facts(self, connection, ansible_facts, data=None): af["processes"] = list(af["processes"].values()) if af.get("multi_areas"): af["multi_areas"].sort() - item["address_family"] = sorted(item["address_family"], key=lambda i: i["afi"]) + item["address_family"] = sorted( + item["address_family"], key=lambda i: i["afi"] + ) objs = sorted( objs, key=lambda i: [ - int(k) if k.isdigit() else k for k in i["name"].replace(".", "/").split("/") + int(k) if k.isdigit() else k + for k in i["name"].replace(".", "/").split("/") ], ) diff --git a/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py b/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py index 248f3ed49..ba495b526 100644 --- a/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py +++ b/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py @@ -17,7 +17,9 @@ from copy import deepcopy from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ospfv2.ospfv2 import ( Ospfv2Args, @@ -48,7 +50,9 @@ def get_config(self, connection): """Wrapper method for `connection.get()` This method exists solely to allow the unit test framework to mock device connection calls. """ - return connection.get("show running-config | section '^router ospf .*'") + return connection.get( + "show running-config | section '^router ospf .*'" + ) def populate_facts(self, connection, ansible_facts, data=None): """Populate the facts for interfaces diff --git a/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py b/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py index 796dacfb5..5a8b33ba2 100644 --- a/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py +++ b/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py @@ -16,7 +16,9 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ospfv3.ospfv3 import ( Ospfv3Args, diff --git a/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py b/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py index 7bb186315..79b4b256d 100644 --- a/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py +++ b/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.prefix_lists.prefix_lists import ( Prefix_listsArgs, @@ -36,7 +38,9 @@ def get_config(self, connection): """Wrapper method for `connection.get()` This method exists solely to allow the unit test framework to mock device connection calls. """ - return connection.get("show running-config | section 'ip(.*) prefix-list'") + return connection.get( + "show running-config | section 'ip(.*) prefix-list'" + ) def populate_facts(self, connection, ansible_facts, data=None): """Populate the facts for Prefix_lists network resource @@ -54,7 +58,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_config(connection) # parse native config using the Prefix_lists template - prefix_lists_parser = Prefix_listsTemplate(lines=data.splitlines(), module=self._module) + prefix_lists_parser = Prefix_listsTemplate( + lines=data.splitlines(), module=self._module + ) objs = list(prefix_lists_parser.parse().values()) if objs: @@ -66,12 +72,16 @@ def populate_facts(self, connection, ansible_facts, data=None): ) for x in item["prefix_lists"]: if "entries" in x: - x["entries"] = sorted(x["entries"], key=lambda k: k["sequence"]) + x["entries"] = sorted( + x["entries"], key=lambda k: k["sequence"] + ) objs = sorted(objs, key=lambda k: k["afi"]) ansible_facts["ansible_network_resources"].pop("prefix_lists", None) params = utils.remove_empties( - prefix_lists_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + prefix_lists_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["prefix_lists"] = params.get("config", []) ansible_facts["ansible_network_resources"].update(facts) diff --git a/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py b/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py index d1bad913a..82c13a8d9 100644 --- a/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py +++ b/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py @@ -15,7 +15,9 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.route_maps.route_maps import ( Route_mapsArgs, @@ -55,7 +57,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_config(connection) # parse native config using the Route_maps template - route_maps_parser = Route_mapsTemplate(lines=data.splitlines(), module=self._module) + route_maps_parser = Route_mapsTemplate( + lines=data.splitlines(), module=self._module + ) objs = list(route_maps_parser.parse().values()) @@ -65,7 +69,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("route_maps", None) params = utils.remove_empties( - route_maps_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + route_maps_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["route_maps"] = params.get("config", []) diff --git a/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py b/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py index c46e1a78a..99a1e41d0 100644 --- a/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py +++ b/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py @@ -15,7 +15,9 @@ based on the configuration. """ from ansible.module_utils._text import to_text -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.snmp_server.snmp_server import ( Snmp_serverArgs, @@ -55,11 +57,15 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_config(connection) # parse native config using the Snmp_server template - snmp_server_parser = Snmp_serverTemplate(lines=data.splitlines(), module=self._module) + snmp_server_parser = Snmp_serverTemplate( + lines=data.splitlines(), module=self._module + ) objs = snmp_server_parser.parse() if "communities" in objs: - objs["communities"] = sorted(objs["communities"], key=lambda k: to_text(k["name"])) + objs["communities"] = sorted( + objs["communities"], key=lambda k: to_text(k["name"]) + ) if "users" in objs: if "auth" in objs["users"]: @@ -76,7 +82,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("snmp_server", None) params = utils.remove_empties( - snmp_server_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + snmp_server_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["snmp_server"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py b/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py index 991b552ff..4b041f66c 100644 --- a/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py +++ b/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py @@ -15,7 +15,9 @@ __metaclass__ = type -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.static_routes.static_routes import ( Static_routesArgs, @@ -33,8 +35,12 @@ def __init__(self, module, subspec="config", options="options"): self.argument_spec = Static_routesArgs.argument_spec def get_static_routes_data(self, connection): - non_vrf_data = connection.get("show running-config | include '^ip(v6)* route'") - vrf_data = connection.get("show running-config | section '^vrf context'") + non_vrf_data = connection.get( + "show running-config | include '^ip(v6)* route'" + ) + vrf_data = connection.get( + "show running-config | section '^vrf context'" + ) if vrf_data: non_vrf_data += "\n" + vrf_data return non_vrf_data @@ -84,9 +90,13 @@ def structure_static_routes(self, strout): _triv_static_route = {"address_families": []} if afi_v4: - _triv_static_route["address_families"].append({"afi": "ipv4", "routes": afi_v4}) + _triv_static_route["address_families"].append( + {"afi": "ipv4", "routes": afi_v4} + ) if afi_v6: - _triv_static_route["address_families"].append({"afi": "ipv6", "routes": afi_v6}) + _triv_static_route["address_families"].append( + {"afi": "ipv6", "routes": afi_v6} + ) _static_route_facts.append(_triv_static_route) @@ -100,9 +110,13 @@ def structure_static_routes(self, strout): } if afi_v4: - _vrf_static_route["address_families"].append({"afi": "ipv4", "routes": afi_v4}) + _vrf_static_route["address_families"].append( + {"afi": "ipv4", "routes": afi_v4} + ) if afi_v6: - _vrf_static_route["address_families"].append({"afi": "ipv6", "routes": afi_v6}) + _vrf_static_route["address_families"].append( + {"afi": "ipv6", "routes": afi_v6} + ) _static_route_facts.append(_vrf_static_route) return _static_route_facts @@ -125,7 +139,9 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self.get_static_routes_data(connection) # parse native config using the Static_routes template - static_routes_parser = Static_routesTemplate(lines=data.splitlines(), module=self._module) + static_routes_parser = Static_routesTemplate( + lines=data.splitlines(), module=self._module + ) objs = static_routes_parser.parse() strout = self.process_static_routes(objs) @@ -134,7 +150,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("static_routes", None) params = utils.remove_empties( - static_routes_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), + static_routes_parser.validate_config( + self.argument_spec, {"config": objs}, redact=True + ), ) facts["static_routes"] = params.get("config") diff --git a/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py b/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py index bdb280310..0fc62950c 100644 --- a/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py +++ b/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py @@ -18,7 +18,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.telemetry.telemetry import ( TelemetryArgs, @@ -29,7 +31,9 @@ TMS_SENSORGROUP, TMS_SUBSCRIPTION, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import NxosCmdRef +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( + NxosCmdRef, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.telemetry.telemetry import ( cr_key_lookup, get_instance_data, @@ -79,7 +83,9 @@ def populate_facts(self, connection, ansible_facts, data=None): # Get Telemetry Global Data cmd_ref["TMS_GLOBAL"]["ref"] = [] - cmd_ref["TMS_GLOBAL"]["ref"].append(NxosCmdRef(self._module, TMS_GLOBAL)) + cmd_ref["TMS_GLOBAL"]["ref"].append( + NxosCmdRef(self._module, TMS_GLOBAL) + ) ref = cmd_ref["TMS_GLOBAL"]["ref"][0] ref.set_context() ref.get_existing() @@ -95,7 +101,9 @@ def populate_facts(self, connection, ansible_facts, data=None): for line in device_cache_lines: if re.search(r"destination-group", line): resource_key = line.strip() - cmd_ref["TMS_DESTGROUP"]["ref"].append(NxosCmdRef(self._module, TMS_DESTGROUP)) + cmd_ref["TMS_DESTGROUP"]["ref"].append( + NxosCmdRef(self._module, TMS_DESTGROUP) + ) ref = cmd_ref["TMS_DESTGROUP"]["ref"][-1] ref.set_context([resource_key]) ref.get_existing(device_cache) @@ -106,7 +114,9 @@ def populate_facts(self, connection, ansible_facts, data=None): for line in device_cache_lines: if re.search(r"sensor-group", line): resource_key = line.strip() - cmd_ref["TMS_SENSORGROUP"]["ref"].append(NxosCmdRef(self._module, TMS_SENSORGROUP)) + cmd_ref["TMS_SENSORGROUP"]["ref"].append( + NxosCmdRef(self._module, TMS_SENSORGROUP) + ) ref = cmd_ref["TMS_SENSORGROUP"]["ref"][-1] ref.set_context([resource_key]) ref.get_existing(device_cache) @@ -162,24 +172,39 @@ def render_config(self, spec, cmd_ref): for cr in cmd_ref[mo]["ref"]: cr_keys = cr_key_lookup(key, mo) for cr_key in cr_keys: - if cr._ref.get(cr_key) and cr._ref[cr_key].get("existing"): + if cr._ref.get(cr_key) and cr._ref[cr_key].get( + "existing" + ): if isinstance(config[key], dict): for k in config[key].keys(): - for existing_key in cr._ref[cr_key]["existing"].keys(): - config[key][k] = cr._ref[cr_key]["existing"][existing_key][ - k - ] + for existing_key in cr._ref[cr_key][ + "existing" + ].keys(): + config[key][k] = cr._ref[cr_key][ + "existing" + ][existing_key][k] continue if isinstance(config[key], list): - for existing_key in cr._ref[cr_key]["existing"].keys(): - data = get_instance_data(key, cr_key, cr, existing_key) + for existing_key in cr._ref[cr_key][ + "existing" + ].keys(): + data = get_instance_data( + key, cr_key, cr, existing_key + ) config[key].append(data) continue - for existing_key in cr._ref[cr_key]["existing"].keys(): - config[key] = cr._ref[cr_key]["existing"][existing_key] + for existing_key in cr._ref[cr_key][ + "existing" + ].keys(): + config[key] = cr._ref[cr_key]["existing"][ + existing_key + ] elif cr._ref.get(cr_key): data = get_instance_data(key, cr_key, cr, None) - if isinstance(config[key], list) and data not in config[key]: + if ( + isinstance(config[key], list) + and data not in config[key] + ): config[key].append(data) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/vlans/vlans.py b/plugins/module_utils/network/nxos/facts/vlans/vlans.py index f7ac798f1..380754c85 100644 --- a/plugins/module_utils/network/nxos/facts/vlans/vlans.py +++ b/plugins/module_utils/network/nxos/facts/vlans/vlans.py @@ -20,7 +20,9 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( parse_conf_arg, ) @@ -74,13 +76,19 @@ def populate_facts(self, connection, ansible_facts, data=None): try: # Not all devices support | json-pretty but is a workaround for # libssh issue https://github.com/ansible/pylibssh/issues/208 - structured = self.get_device_data(connection, "show vlan | json-pretty") + structured = self.get_device_data( + connection, "show vlan | json-pretty" + ) except Exception: # When json-pretty is not supported, we fall back to | json - structured = self.get_device_data(connection, "show vlan | json") + structured = self.get_device_data( + connection, "show vlan | json" + ) # Raw cli config is needed for mapped_vni, which is not included in structured. - run_cfg_output = self.get_device_data(connection, "show running-config | section ^vlan") + run_cfg_output = self.get_device_data( + connection, "show running-config | section ^vlan" + ) else: running_config = data.split("\n\n") structured, run_cfg_output = running_config[0], running_config[1] @@ -97,7 +105,9 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: facts["vlans"] = [] - params = utils.validate_config(self.argument_spec, {"config": objs}) + params = utils.validate_config( + self.argument_spec, {"config": objs} + ) for cfg in params["config"]: facts["vlans"].append(utils.remove_empties(cfg)) ansible_facts["ansible_network_resources"].update(facts) @@ -127,7 +137,9 @@ def render_config(self, spec, vlan): obj["mode"] = vlan["vlanshowinfo-vlanmode"].replace("-vlan", "") # enabled: shutdown, noshutdown - obj["enabled"] = True if "noshutdown" in vlan["vlanshowbr-shutstate"] else False + obj["enabled"] = ( + True if "noshutdown" in vlan["vlanshowbr-shutstate"] else False + ) # state: active, suspend obj["state"] = vlan["vlanshowbr-vlanstate"] diff --git a/plugins/module_utils/network/nxos/nxos.py b/plugins/module_utils/network/nxos/nxos.py index f34046b39..6eecac49e 100644 --- a/plugins/module_utils/network/nxos/nxos.py +++ b/plugins/module_utils/network/nxos/nxos.py @@ -104,7 +104,9 @@ def get_config(self, flags=None): try: out = connection.get_config(flags=flags) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) cfg = to_text(out, errors="surrogate_then_replace").strip() + "\n" self._device_configs[cmd] = cfg @@ -123,11 +125,14 @@ def run_commands(self, commands, check_rc=True): if network_api == "cliconf" and out: for index, resp in enumerate(out): if ( - "Invalid command at" in resp or "Ambiguous command at" in resp + "Invalid command at" in resp + or "Ambiguous command at" in resp ) and "json" in resp: if commands[index]["output"] == "json": commands[index]["output"] = "text" - out = connection.run_commands(commands, check_rc) + out = connection.run_commands( + commands, check_rc + ) return out except ConnectionError as exc: self._module.fail_json(msg=to_text(exc)) @@ -151,7 +156,10 @@ def load_config(self, config, return_error=False, opts=None, replace=None): responses.append(err) return responses elif code and "no graceful-restart" in err: - if "ISSU/HA will be affected if Graceful Restart is disabled" in err: + if ( + "ISSU/HA will be affected if Graceful Restart is disabled" + in err + ): msg = [""] responses.extend(msg) return responses @@ -183,7 +191,9 @@ def get_diff( diff_replace=diff_replace, ) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) return response def get_capabilities(self): @@ -195,7 +205,9 @@ def get_capabilities(self): try: capabilities = connection.get_capabilities() except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) self._module._capabilities = json.loads(capabilities) return self._module._capabilities @@ -204,7 +216,9 @@ def read_module_context(self, module_key): try: module_context = connection.read_module_context(module_key) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) return module_context @@ -213,7 +227,9 @@ def save_module_context(self, module_key, module_context): try: connection.save_module_context(module_key, module_context) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) return None @@ -265,7 +281,9 @@ def get_config(self, flags=None): try: out = self._connection.send_request(cmd) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) cfg = to_text(out).strip() self._device_configs[cmd] = cfg @@ -288,7 +306,9 @@ def get_diff( if running and diff_match != "none" and diff_replace != "config": # running configuration - running_obj = NetworkConfig(indent=2, contents=running, ignore_lines=diff_ignore_lines) + running_obj = NetworkConfig( + indent=2, contents=running, ignore_lines=diff_ignore_lines + ) configdiffobjs = candidate_obj.difference( running_obj, path=path, @@ -299,10 +319,14 @@ def get_diff( else: configdiffobjs = candidate_obj.items - diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else "" + diff["config_diff"] = ( + dumps(configdiffobjs, "commands") if configdiffobjs else "" + ) return diff - def load_config(self, commands, return_error=False, opts=None, replace=None): + def load_config( + self, commands, return_error=False, opts=None, replace=None + ): """Sends the ordered set of commands to the device""" if opts is None: opts = {} @@ -320,7 +344,10 @@ def load_config(self, commands, return_error=False, opts=None, replace=None): elif opts.get("catch_clierror") and "400" in code: return [code, err] elif code and "no graceful-restart" in err: - if "ISSU/HA will be affected if Graceful Restart is disabled" in err: + if ( + "ISSU/HA will be affected if Graceful Restart is disabled" + in err + ): msg = [""] responses.extend(msg) return responses @@ -332,7 +359,9 @@ def load_config(self, commands, return_error=False, opts=None, replace=None): responses.extend(resp) return responses - def edit_config(self, candidate=None, commit=True, replace=None, comment=None): + def edit_config( + self, candidate=None, commit=True, replace=None, comment=None + ): resp = list() self.check_edit_config_capability(candidate, commit, replace, comment) @@ -354,15 +383,21 @@ def get_capabilities(self): try: capabilities = self._connection.get_capabilities() except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) return json.loads(capabilities) - def check_edit_config_capability(self, candidate=None, commit=True, replace=None, comment=None): + def check_edit_config_capability( + self, candidate=None, commit=True, replace=None, comment=None + ): operations = self._connection.get_device_operations() if not candidate and not replace: - raise ValueError("must provide a candidate or replace to load configuration") + raise ValueError( + "must provide a candidate or replace to load configuration" + ) if commit not in (True, False): raise ValueError("'commit' must be a bool, got %s" % commit) @@ -377,7 +412,9 @@ def read_module_context(self, module_key): try: module_context = self._connection.read_module_context(module_key) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) return module_context @@ -385,7 +422,9 @@ def save_module_context(self, module_key, module_context): try: self._connection.save_module_context(module_key, module_context) except ConnectionError as exc: - self._module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + self._module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) return None @@ -497,7 +536,9 @@ def get_platform_shortname(self): return None # Supported Platforms: N3K,N5K,N6K,N7K,N9K,N3K-F,N9K-F - m = re.match("(?PN[35679][K57])-(?PC35)*", network_os_platform) + m = re.match( + "(?PN[35679][K57])-(?PC35)*", network_os_platform + ) if not m: return None shortname = m.group("short") @@ -584,13 +625,21 @@ def pattern_match_existing(self, output, k): if not match: return None if len(match) > 1 and not multiple: - raise ValueError("get_existing: multiple matches found for property {0}".format(k)) + raise ValueError( + "get_existing: multiple matches found for property {0}".format( + k + ) + ) else: match = [m.groups() for m in match_lines if m] if not match: return None if len(match) > 1 and not multiple: - raise ValueError("get_existing: multiple matches found for property {0}".format(k)) + raise ValueError( + "get_existing: multiple matches found for property {0}".format( + k + ) + ) for item in match: index = match.index(item) match[index] = list(item) # tuple to list @@ -654,7 +703,10 @@ def get_existing(self, cache_output=None): # We need to remove the last item in context for state absent case. if ref["_state"] in self.absent_states and ref["_context"]: - if ref["_resource_key"] and ref["_resource_key"] == ref["_context"][-1]: + if ( + ref["_resource_key"] + and ref["_resource_key"] == ref["_context"][-1] + ): if ref["_context"][-1] in output: ref["_context"][-1] = "no " + ref["_context"][-1] else: @@ -687,7 +739,9 @@ def get_existing(self, cache_output=None): ref[k]["existing"][index] = item[0] else: raise ValueError( - "get_existing: unknown 'kind' value specified for key '{0}'".format(k), + "get_existing: unknown 'kind' value specified for key '{0}'".format( + k + ), ) def get_playvals(self): @@ -761,9 +815,15 @@ def build_cmd_set(self, playval, existing, k): else: cmd = ref[k]["setval"].format(playval) else: - raise ValueError("get_proposed: unknown 'kind' value specified for key '{0}'".format(k)) + raise ValueError( + "get_proposed: unknown 'kind' value specified for key '{0}'".format( + k + ) + ) if cmd: - if ref["_state"] in self.absent_states and not re.search(r"^no", cmd): + if ref["_state"] in self.absent_states and not re.search( + r"^no", cmd + ): cmd = "no " + cmd # Commands may require parent commands for proper context. # Global _template context is replaced by parameter context @@ -793,11 +853,15 @@ def compare(playval, existing): return False elif str(playval) == str(existing): return True - elif isinstance(existing, dict) and playval in existing.values(): + elif ( + isinstance(existing, dict) and playval in existing.values() + ): return True if ref["_state"] in self.absent_states: - if isinstance(existing, dict) and all(x is None for x in existing.values()): + if isinstance(existing, dict) and all( + x is None for x in existing.values() + ): existing = None if existing is None or playval not in existing.values(): return True @@ -817,7 +881,9 @@ def compare(playval, existing): for ekey, evalue in existing.items(): if isinstance(evalue, dict): # Remove values set to string 'None' from dvalue - evalue = dict((k, v) for k, v in evalue.items() if v != "None") + evalue = dict( + (k, v) for k, v in evalue.items() if v != "None" + ) for pkey, pvalue in playval.items(): if compare(pvalue, evalue): if playval_copy.get(pkey): diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py b/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py index 942e993e3..f271cefc6 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py @@ -68,7 +68,9 @@ def _tmplt_redistribute(redis): class Bgp_address_familyTemplate(NetworkTemplate): def __init__(self, lines=None): - super(Bgp_address_familyTemplate, self).__init__(lines=lines, tmplt=self) + super(Bgp_address_familyTemplate, self).__init__( + lines=lines, tmplt=self + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_global.py b/plugins/module_utils/network/nxos/rm_templates/bgp_global.py index 255ba7db2..437f30fe6 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_global.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_global.py @@ -58,7 +58,9 @@ def _tmplt_bfd(proc): class Bgp_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Bgp_globalTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Bgp_globalTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py index 7db4b860d..ca8c62b14 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py @@ -36,7 +36,9 @@ def _tmplt_maximum_prefix(data): class Bgp_neighbor_address_familyTemplate(NetworkTemplate): def __init__(self, lines=None): - super(Bgp_neighbor_address_familyTemplate, self).__init__(lines=lines, tmplt=self) + super(Bgp_neighbor_address_familyTemplate, self).__init__( + lines=lines, tmplt=self + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py b/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py index 7e7bb5828..6ea434f91 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py @@ -49,7 +49,9 @@ def _tmplt_path_attribute(proc): class Bgp_templatesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Bgp_templatesTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Bgp_templatesTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py b/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py index 1cc9d5973..5a5153a68 100644 --- a/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py @@ -49,12 +49,16 @@ "SD", ] -allowed_values_pattern = "|".join(re.escape(val) for val in allowed_speed_values) +allowed_values_pattern = "|".join( + re.escape(val) for val in allowed_speed_values +) class Fc_interfacesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Fc_interfacesTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Fc_interfacesTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/hostname.py b/plugins/module_utils/network/nxos/rm_templates/hostname.py index bf922fb4c..623c3cd6e 100644 --- a/plugins/module_utils/network/nxos/rm_templates/hostname.py +++ b/plugins/module_utils/network/nxos/rm_templates/hostname.py @@ -24,7 +24,9 @@ class HostnameTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(HostnameTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(HostnameTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/logging_global.py b/plugins/module_utils/network/nxos/rm_templates/logging_global.py index 8287794e0..b728f6714 100644 --- a/plugins/module_utils/network/nxos/rm_templates/logging_global.py +++ b/plugins/module_utils/network/nxos/rm_templates/logging_global.py @@ -24,7 +24,9 @@ def _tmplt_hosts(data): cmd = "logging server {host}" - data["client_identity"] = data.get("secure", {}).get("trustpoint", {}).get("client_identity") + data["client_identity"] = ( + data.get("secure", {}).get("trustpoint", {}).get("client_identity") + ) if "severity" in data: cmd += " {severity}" @@ -44,7 +46,9 @@ def _tmplt_hosts(data): class Logging_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Logging_globalTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Logging_globalTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/ntp_global.py b/plugins/module_utils/network/nxos/rm_templates/ntp_global.py index 9fd6e4d6e..20f48ebeb 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ntp_global.py +++ b/plugins/module_utils/network/nxos/rm_templates/ntp_global.py @@ -24,7 +24,9 @@ class Ntp_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Ntp_globalTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Ntp_globalTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py b/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py index 2321fcaf1..3d149a71f 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py @@ -38,7 +38,9 @@ def _tmplt_authentication(data): class Ospf_interfacesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Ospf_interfacesTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Ospf_interfacesTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/ospfv2.py b/plugins/module_utils/network/nxos/rm_templates/ospfv2.py index c8b518dd6..39086405c 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ospfv2.py +++ b/plugins/module_utils/network/nxos/rm_templates/ospfv2.py @@ -21,7 +21,10 @@ def _tmplt_area_range(arange): def _tmplt_default_information(proc): command = "default-information originate" - if "always" in proc["default_information"] and proc["default_information"]["always"]: + if ( + "always" in proc["default_information"] + and proc["default_information"]["always"] + ): command += " always" if "route_map" in proc["default_information"]: command += " route-map" @@ -108,7 +111,9 @@ def _tmplt_max_metric(proc): if on_startup.get("wait_period"): command += " {wait_period}".format(**on_startup) if on_startup.get("wait_for_bgp_asn"): - command += " wait-for bgp {wait_for_bgp_asn}".format(**on_startup) + command += " wait-for bgp {wait_for_bgp_asn}".format( + **on_startup + ) if summary_lsa: command += " summary-lsa" if summary_lsa.get("max_metric_value"): diff --git a/plugins/module_utils/network/nxos/rm_templates/ospfv3.py b/plugins/module_utils/network/nxos/rm_templates/ospfv3.py index b46c3cf4e..443f5eec9 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ospfv3.py +++ b/plugins/module_utils/network/nxos/rm_templates/ospfv3.py @@ -90,9 +90,13 @@ def _tmplt_max_metric(proc): command = "no {0}".format(command) else: external_lsa = max_metric.get("router_lsa", {}).get("external_lsa", {}) - stub_prefix_lsa = max_metric.get("router_lsa", {}).get("stub_prefix_lsa", {}) + stub_prefix_lsa = max_metric.get("router_lsa", {}).get( + "stub_prefix_lsa", {} + ) on_startup = max_metric.get("router_lsa", {}).get("on_startup", {}) - inter_area_prefix_lsa = max_metric.get("router_lsa", {}).get("inter_area_prefix_lsa", {}) + inter_area_prefix_lsa = max_metric.get("router_lsa", {}).get( + "inter_area_prefix_lsa", {} + ) if external_lsa: command += " external-lsa" if external_lsa.get("max_metric_value"): @@ -104,11 +108,15 @@ def _tmplt_max_metric(proc): if on_startup.get("wait_period"): command += " {wait_period}".format(**on_startup) if on_startup.get("wait_for_bgp_asn"): - command += " wait-for bgp {wait_for_bgp_asn}".format(**on_startup) + command += " wait-for bgp {wait_for_bgp_asn}".format( + **on_startup + ) if inter_area_prefix_lsa: command += " inter-area-prefix-lsa" if inter_area_prefix_lsa.get("max_metric_value"): - command += " {max_metric_value}".format(**inter_area_prefix_lsa) + command += " {max_metric_value}".format( + **inter_area_prefix_lsa + ) return command diff --git a/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py b/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py index 0bb66eada..66232c1d2 100644 --- a/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py +++ b/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py @@ -24,7 +24,9 @@ class Prefix_listsTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Prefix_listsTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Prefix_listsTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/route_maps.py b/plugins/module_utils/network/nxos/rm_templates/route_maps.py index 7e876682a..af6a8c24d 100644 --- a/plugins/module_utils/network/nxos/rm_templates/route_maps.py +++ b/plugins/module_utils/network/nxos/rm_templates/route_maps.py @@ -113,7 +113,9 @@ def _tmplt_set_ip_next_hop_verify_availability(data): class Route_mapsTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Route_mapsTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Route_mapsTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/snmp_server.py b/plugins/module_utils/network/nxos/rm_templates/snmp_server.py index 35451a47b..637f08481 100644 --- a/plugins/module_utils/network/nxos/rm_templates/snmp_server.py +++ b/plugins/module_utils/network/nxos/rm_templates/snmp_server.py @@ -78,7 +78,9 @@ def _tmplt_users_auth(data): class Snmp_serverTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Snmp_serverTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Snmp_serverTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/rm_templates/static_routes.py b/plugins/module_utils/network/nxos/rm_templates/static_routes.py index a70bc4130..f7a3433c9 100644 --- a/plugins/module_utils/network/nxos/rm_templates/static_routes.py +++ b/plugins/module_utils/network/nxos/rm_templates/static_routes.py @@ -24,7 +24,9 @@ class Static_routesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): - super(Static_routesTemplate, self).__init__(lines=lines, tmplt=self, module=module) + super(Static_routesTemplate, self).__init__( + lines=lines, tmplt=self, module=module + ) # fmt: off PARSERS = [ diff --git a/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py b/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py index aa540aded..38b557414 100644 --- a/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py +++ b/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py @@ -61,16 +61,16 @@ def valiate_input(playvals, type, module): msg = "Invalid playbook value: {0}.".format(playvals) msg += " Parameter under is required" module.fail_json(msg=msg) - if playvals.get("destination") and not isinstance(playvals["destination"], dict): + if playvals.get("destination") and not isinstance( + playvals["destination"], dict + ): msg = "Invalid playbook value: {0}.".format(playvals) msg += " Parameter under must be a dict" module.fail_json(msg=msg) if not playvals.get("destination") and len(playvals) > 1: msg = "Invalid playbook value: {0}.".format(playvals) msg += " Playbook entry contains unrecongnized parameters." - msg += ( - " Make sure keys under are specified as follows:" - ) + msg += " Make sure keys under are specified as follows:" msg += " destination: {ip: , port: , protocol: , encoding: }}" module.fail_json(msg=msg) @@ -81,7 +81,9 @@ def valiate_input(playvals, type, module): module.fail_json(msg=msg) if playvals.get("path") and "name" not in playvals["path"].keys(): msg = "Invalid playbook value: {0}.".format(playvals) - msg += " Parameter under requires key" + msg += ( + " Parameter under requires key" + ) module.fail_json(msg=msg) @@ -147,7 +149,9 @@ def remove_duplicate_context(cmds): """Helper method to remove duplicate telemetry context commands""" if not cmds: return cmds - feature_indices = [i for i, x in enumerate(cmds) if x == "feature telemetry"] + feature_indices = [ + i for i, x in enumerate(cmds) if x == "feature telemetry" + ] telemetry_indices = [i for i, x in enumerate(cmds) if x == "telemetry"] if len(feature_indices) == 1 and len(telemetry_indices) == 1: return cmds @@ -177,7 +181,9 @@ def get_setval_path(module_or_path_data): if isinstance(module_or_path_data, dict): path = module_or_path_data else: - path = module_or_path_data.params["config"]["sensor_groups"][0].get("path") + path = module_or_path_data.params["config"]["sensor_groups"][0].get( + "path" + ) if path is None: return path @@ -222,11 +228,17 @@ def massage_data(have_or_want): else: if item.get("destination"): if item.get("destination").get("port"): - item["destination"]["port"] = str(item["destination"]["port"]) + item["destination"]["port"] = str( + item["destination"]["port"] + ) if item.get("destination").get("protocol"): - item["destination"]["protocol"] = item["destination"]["protocol"].lower() + item["destination"]["protocol"] = item["destination"][ + "protocol" + ].lower() if item.get("destination").get("encoding"): - item["destination"]["encoding"] = item["destination"]["encoding"].lower() + item["destination"]["encoding"] = item["destination"][ + "encoding" + ].lower() if item.get("path"): for key in [ "filter_condition", @@ -241,7 +253,9 @@ def massage_data(have_or_want): item["destination_group"] = str(item["destination_group"]) if item.get("sensor_group"): if item.get("sensor_group").get("id"): - item["sensor_group"]["id"] = str(item["sensor_group"]["id"]) + item["sensor_group"]["id"] = str( + item["sensor_group"]["id"] + ) if item.get("sensor_group").get("sample_interval"): item["sensor_group"]["sample_interval"] = str( item["sensor_group"]["sample_interval"], diff --git a/plugins/module_utils/network/nxos/utils/utils.py b/plugins/module_utils/network/nxos/utils/utils.py index 01468edd5..8e5c50b3e 100644 --- a/plugins/module_utils/network/nxos/utils/utils.py +++ b/plugins/module_utils/network/nxos/utils/utils.py @@ -124,7 +124,9 @@ def remove_rsvd_interfaces(interfaces): """Exclude reserved interfaces from user management""" if not interfaces: return [] - return [i for i in interfaces if get_interface_type(i["name"]) != "management"] + return [ + i for i in interfaces if get_interface_type(i["name"]) != "management" + ] def vlan_range_to_list(vlans): diff --git a/plugins/modules/nxos_aaa_server.py b/plugins/modules/nxos_aaa_server.py index 9103f931f..dcf71b92e 100644 --- a/plugins/modules/nxos_aaa_server.py +++ b/plugins/modules/nxos_aaa_server.py @@ -206,7 +206,9 @@ def config_aaa_server(params, server_type): cmds.append("{0}-server deadtime {1}".format(server_type, deadtime)) if server_timeout is not None: - cmds.append("{0}-server timeout {1}".format(server_type, server_timeout)) + cmds.append( + "{0}-server timeout {1}".format(server_type, server_timeout) + ) if directed_request is not None: if directed_request == "enabled": @@ -215,7 +217,11 @@ def config_aaa_server(params, server_type): cmds.append("no {0}-server directed-request".format(server_type)) if global_key is not None: - cmds.append("{0}-server key {1} {2}".format(server_type, encrypt_type, global_key)) + cmds.append( + "{0}-server key {1} {2}".format( + server_type, encrypt_type, global_key + ) + ) return cmds @@ -229,39 +235,52 @@ def default_aaa_server(existing, params, server_type): global_key = params.get("global_key") existing_key = existing.get("global_key") - if deadtime is not None and existing.get("deadtime") != PARAM_TO_DEFAULT_KEYMAP["deadtime"]: + if ( + deadtime is not None + and existing.get("deadtime") != PARAM_TO_DEFAULT_KEYMAP["deadtime"] + ): cmds.append("no {0}-server deadtime 1".format(server_type)) if ( server_timeout is not None - and existing.get("server_timeout") != PARAM_TO_DEFAULT_KEYMAP["server_timeout"] + and existing.get("server_timeout") + != PARAM_TO_DEFAULT_KEYMAP["server_timeout"] ): cmds.append("no {0}-server timeout 1".format(server_type)) if ( directed_request is not None - and existing.get("directed_request") != PARAM_TO_DEFAULT_KEYMAP["directed_request"] + and existing.get("directed_request") + != PARAM_TO_DEFAULT_KEYMAP["directed_request"] ): cmds.append("no {0}-server directed-request".format(server_type)) if global_key is not None and existing_key is not None: - cmds.append("no {0}-server key 7 {1}".format(server_type, existing_key)) + cmds.append( + "no {0}-server key 7 {1}".format(server_type, existing_key) + ) return cmds def main(): argument_spec = dict( - server_type=dict(type="str", choices=["radius", "tacacs"], required=True), + server_type=dict( + type="str", choices=["radius", "tacacs"], required=True + ), global_key=dict(type="str", no_log=True), encrypt_type=dict(type="str", choices=["0", "7"]), deadtime=dict(type="str"), server_timeout=dict(type="str"), - directed_request=dict(type="str", choices=["enabled", "disabled", "default"]), + directed_request=dict( + type="str", choices=["enabled", "disabled", "default"] + ), state=dict(choices=["default", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} @@ -297,14 +316,18 @@ def main(): if int(deadtime) < 0 or int(deadtime) > 1440: raise ValueError except ValueError: - module.fail_json(msg="deadtime must be an integer between 0 and 1440") + module.fail_json( + msg="deadtime must be an integer between 0 and 1440" + ) if server_timeout: try: if int(server_timeout) < 1 or int(server_timeout) > 60: raise ValueError except ValueError: - module.fail_json(msg="server_timeout must be an integer between 1 and 60") + module.fail_json( + msg="server_timeout must be an integer between 1 and 60" + ) delta = dict(set(proposed.items()).difference(existing.items())) if delta: @@ -315,7 +338,10 @@ def main(): elif state == "default": for key, value in proposed.items(): if key != "server_type" and value != "default": - module.fail_json(msg='Parameters must be set to "default"' "when state=default") + module.fail_json( + msg='Parameters must be set to "default"' + "when state=default" + ) command = default_aaa_server(existing, proposed, server_type) if command: commands.append(command) diff --git a/plugins/modules/nxos_aaa_server_host.py b/plugins/modules/nxos_aaa_server_host.py index 192b21ab5..158fb47e8 100644 --- a/plugins/modules/nxos_aaa_server_host.py +++ b/plugins/modules/nxos_aaa_server_host.py @@ -197,19 +197,21 @@ def get_aaa_host_info(module, server_type, address): match = re.search(pattern, body) aaa_host_info["key"] = match.group(1) if aaa_host_info["key"]: - aaa_host_info["key"] = aaa_host_info["key"].replace('"', "") + aaa_host_info["key"] = aaa_host_info["key"].replace( + '"', "" + ) aaa_host_info["encrypt_type"] = "7" aaa_host_info["auth_port"] = match.group(2) aaa_host_info["acct_port"] = match.group(3) aaa_host_info["host_timeout"] = match.group(4) elif "tacacs" in body: - pattern = ( - r"\S+ host \S+(?:\s+key 7\s+(\S+))?(?:\s+port (\d+))?(?:\s+timeout (\d+))?" - ) + pattern = r"\S+ host \S+(?:\s+key 7\s+(\S+))?(?:\s+port (\d+))?(?:\s+timeout (\d+))?" match = re.search(pattern, body) aaa_host_info["key"] = match.group(1) if aaa_host_info["key"]: - aaa_host_info["key"] = aaa_host_info["key"].replace('"', "") + aaa_host_info["key"] = aaa_host_info["key"].replace( + '"', "" + ) aaa_host_info["encrypt_type"] = "7" aaa_host_info["tacacs_port"] = match.group(2) aaa_host_info["host_timeout"] = match.group(3) @@ -279,7 +281,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() @@ -311,11 +315,14 @@ def main(): module.fail_json(msg="encrypt_type must be used with key") if tacacs_port and server_type != "tacacs": - module.fail_json(msg="tacacs_port can only be used with server_type=tacacs") + module.fail_json( + msg="tacacs_port can only be used with server_type=tacacs" + ) if (auth_port or acct_port) and server_type != "radius": module.fail_json( - msg="auth_port and acct_port can only be used" "when server_type=radius", + msg="auth_port and acct_port can only be used" + "when server_type=radius", ) existing = get_aaa_host_info(module, server_type, address) diff --git a/plugins/modules/nxos_acls.py b/plugins/modules/nxos_acls.py index 29d610400..4bd5657b2 100644 --- a/plugins/modules/nxos_acls.py +++ b/plugins/modules/nxos_acls.py @@ -1402,7 +1402,9 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acls.acls import ( AclsArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acls.acls import Acls +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acls.acls import ( + Acls, +) def main(): @@ -1411,7 +1413,9 @@ def main(): :returns: the result form module invocation """ - module = AnsibleModule(argument_spec=AclsArgs.argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=AclsArgs.argument_spec, supports_check_mode=True + ) result = Acls(module).execute_module() module.exit_json(**result) diff --git a/plugins/modules/nxos_banner.py b/plugins/modules/nxos_banner.py index 1a170783a..7fffe8dbe 100644 --- a/plugins/modules/nxos_banner.py +++ b/plugins/modules/nxos_banner.py @@ -219,7 +219,10 @@ def main(): err_str = item["clierror"] else: err_str = item - if "more than 40 lines" in err_str or "buffer overflowed" in err_str: + if ( + "more than 40 lines" in err_str + or "buffer overflowed" in err_str + ): load_config(module, commands) result["changed"] = True diff --git a/plugins/modules/nxos_bfd_global.py b/plugins/modules/nxos_bfd_global.py index 6ae1a88da..1613e5fe0 100644 --- a/plugins/modules/nxos_bfd_global.py +++ b/plugins/modules/nxos_bfd_global.py @@ -307,7 +307,9 @@ def main(): fabricpath_slow_timer=dict(required=False, type="int"), fabricpath_vlan=dict(required=False, type="int"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() cmd_ref = NxosCmdRef(module, BFD_CMD_REF) diff --git a/plugins/modules/nxos_command.py b/plugins/modules/nxos_command.py index 6c3c2c384..2032816a7 100644 --- a/plugins/modules/nxos_command.py +++ b/plugins/modules/nxos_command.py @@ -144,7 +144,9 @@ transform_commands, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( + run_commands, +) def parse_commands(module, warnings): @@ -180,7 +182,9 @@ def main(): interval=dict(default=1, type="int"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() result = {"changed": False, "warnings": warnings} @@ -221,7 +225,9 @@ def main(): msg = "One or more conditional statements have not been satisfied" module.fail_json(msg=msg, failed_conditions=failed_conditions) - result.update({"stdout": responses, "stdout_lines": list(to_lines(responses))}) + result.update( + {"stdout": responses, "stdout_lines": list(to_lines(responses))} + ) module.exit_json(**result) diff --git a/plugins/modules/nxos_config.py b/plugins/modules/nxos_config.py index 84be30a02..71e021781 100644 --- a/plugins/modules/nxos_config.py +++ b/plugins/modules/nxos_config.py @@ -330,7 +330,9 @@ NetworkConfig, dumps, ) -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, +) from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( get_config, @@ -400,7 +402,9 @@ def main(): parents=dict(type="list", elements="str"), before=dict(type="list", elements="str"), after=dict(type="list", elements="str"), - match=dict(default="line", choices=["line", "strict", "exact", "none"]), + match=dict( + default="line", choices=["line", "strict", "exact", "none"] + ), replace=dict(default="line", choices=["line", "block", "config"]), running_config=dict(aliases=["config"]), intended_config=dict(), @@ -446,9 +450,13 @@ def main(): replace_src = module.params["replace_src"] if replace_src: if module.params["replace"] != "config": - module.fail_json(msg="replace: config is required with replace_src") + module.fail_json( + msg="replace: config is required with replace_src" + ) - if module.params["backup"] or (module._diff and module.params["diff_against"] == "running"): + if module.params["backup"] or ( + module._diff and module.params["diff_against"] == "running" + ): contents = get_config(module, flags=flags) config = NetworkConfig(indent=2, contents=contents) if module.params["backup"]: @@ -479,7 +487,9 @@ def main(): diff_replace=replace, ) except ConnectionError as exc: - module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + module.fail_json( + msg=to_text(exc, errors="surrogate_then_replace") + ) config_diff = response["config_diff"] if config_diff: @@ -583,7 +593,9 @@ def main(): }, ) - if result.get("changed") and any((module.params["src"], module.params["lines"])): + if result.get("changed") and any( + (module.params["src"], module.params["lines"]) + ): msg = ( "To ensure idempotency and correct diff the input configuration lines should be" " similar to how they appear if present in" diff --git a/plugins/modules/nxos_devicealias.py b/plugins/modules/nxos_devicealias.py index 1aa4c9d75..3c74da6b7 100644 --- a/plugins/modules/nxos_devicealias.py +++ b/plugins/modules/nxos_devicealias.py @@ -267,7 +267,9 @@ def main(): rename=dict(type="list", elements="dict", options=element_spec_rename), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() messages = list() @@ -301,7 +303,9 @@ def main(): + str(name) + ". Note that name cannot be more than 64 alphanumeric chars, " + "it must start with a letter, and can only contain these characters: " - + ", ".join(["'{0}'".format(c) for c in VALID_DA_CHARS]), + + ", ".join( + ["'{0}'".format(c) for c in VALID_DA_CHARS] + ), ) if not isPwwnValid(pwwn): module.fail_json( @@ -387,7 +391,9 @@ def main(): if m == "enhanced": # but switch mode is enhanced, so set it to basic commands.append("no device-alias mode enhanced") - messages.append("device-alias mode changed from enhanced to basic") + messages.append( + "device-alias mode changed from enhanced to basic" + ) else: messages.append( "device-alias mode remains unchanged. current mode is basic", @@ -398,7 +404,9 @@ def main(): if m == "basic": # but switch mode is basic, so set it to enhanced commands.append("device-alias mode enhanced") - messages.append("device-alias mode changed from basic to enhanced") + messages.append( + "device-alias mode changed from basic to enhanced" + ) else: messages.append( "device-alias mode remains unchanged. current mode is enhanced", @@ -407,11 +415,15 @@ def main(): if commands: if distribute: commands.append("device-alias commit") - commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + ) else: if distribute is None and d == "enabled": commands.append("device-alias commit") - commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + ) cmds = flatten_list(commands) @@ -471,18 +483,26 @@ def main(): ) else: - commands.append("device-alias name " + name + " pwwn " + pwwn) + commands.append( + "device-alias name " + name + " pwwn " + pwwn + ) da_add_list.append(name) if len(da_add_list) != 0 or len(da_remove_list) != 0: commands = ["device-alias database"] + commands if distribute: commands.append("device-alias commit") - commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + ) else: if distribute is None and d == "enabled": commands.append("device-alias commit") - commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + + commands + + ["no terminal dont-ask"] + ) cmds = flatten_list(commands) if cmds: @@ -495,11 +515,13 @@ def main(): load_config(module, cmds) if len(da_remove_list) != 0: messages.append( - "the required device-alias were removed. " + ",".join(da_remove_list), + "the required device-alias were removed. " + + ",".join(da_remove_list), ) if len(da_add_list) != 0: messages.append( - "the required device-alias were added. " + ",".join(da_add_list), + "the required device-alias were added. " + + ",".join(da_add_list), ) # Step 5: Process rename @@ -518,7 +540,9 @@ def main(): + " with this one", ) if shDADatabaseObj.isNameInDaDatabase(oldname): - commands.append("device-alias rename " + oldname + " " + newname) + commands.append( + "device-alias rename " + oldname + " " + newname + ) else: module.fail_json( changed=False, @@ -531,11 +555,17 @@ def main(): commands = ["device-alias database"] + commands if distribute: commands.append("device-alias commit") - commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + ) else: if distribute is None and d == "enabled": commands.append("device-alias commit") - commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + + commands + + ["no terminal dont-ask"] + ) cmds = flatten_list(commands) if cmds: commands_to_execute = commands_to_execute + cmds diff --git a/plugins/modules/nxos_evpn_global.py b/plugins/modules/nxos_evpn_global.py index 83ef78392..383658e02 100644 --- a/plugins/modules/nxos_evpn_global.py +++ b/plugins/modules/nxos_evpn_global.py @@ -66,7 +66,9 @@ def main(): argument_spec = dict(nv_overlay_evpn=dict(required=True, type="bool")) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) result = {"changed": False} @@ -81,7 +83,9 @@ def main(): os_platform = info.get("network_os_platform", "") if "3K" in os_platform: - module.fail_json(msg="This module is not supported on Nexus 3000 series") + module.fail_json( + msg="This module is not supported on Nexus 3000 series" + ) if module.params["nv_overlay_evpn"] is True: if "nv overlay evpn" not in config: diff --git a/plugins/modules/nxos_evpn_vni.py b/plugins/modules/nxos_evpn_vni.py index 89771f374..4ada03d17 100644 --- a/plugins/modules/nxos_evpn_vni.py +++ b/plugins/modules/nxos_evpn_vni.py @@ -223,7 +223,9 @@ def state_present(module, existing, proposed): commands.append("{0} {1}".format(key, target)) if existing.get(key.replace("-", "_").replace(" ", "_")): - for exi in existing.get(key.replace("-", "_").replace(" ", "_")): + for exi in existing.get( + key.replace("-", "_").replace(" ", "_") + ): if exi not in value: commands.append("no {0} {1}".format(key, exi)) @@ -254,10 +256,14 @@ def main(): route_target_both=dict(required=False, type="list", elements="str"), route_target_import=dict(required=False, type="list", elements="str"), route_target_export=dict(required=False, type="list", elements="str"), - state=dict(choices=["present", "absent"], default="present", required=False), + state=dict( + choices=["present", "absent"], default="present", required=False + ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = dict(changed=False, warnings=warnings) @@ -265,7 +271,9 @@ def main(): state = module.params["state"] args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) - proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed_args = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) commands = [] parents = [] diff --git a/plugins/modules/nxos_facts.py b/plugins/modules/nxos_facts.py index 77ca123d5..f506f5bf5 100644 --- a/plugins/modules/nxos_facts.py +++ b/plugins/modules/nxos_facts.py @@ -219,7 +219,9 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.facts.facts import ( FactsArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( + Facts, +) def get_chassis_type(connection): @@ -246,7 +248,9 @@ def main(): """ argument_spec = FactsArgs.argument_spec - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) connection = Connection(module._socket_path) facts = Facts(module, chassis_type=get_chassis_type(connection)) @@ -254,7 +258,9 @@ def main(): ansible_facts = {} if module.params.get("available_network_resources"): - ansible_facts["available_network_resources"] = sorted(facts.get_resource_subsets().keys()) + ansible_facts["available_network_resources"] = sorted( + facts.get_resource_subsets().keys() + ) result = facts.get_facts() additional_facts, additional_warnings = result diff --git a/plugins/modules/nxos_feature.py b/plugins/modules/nxos_feature.py index c9229c4d5..aa58aaee2 100644 --- a/plugins/modules/nxos_feature.py +++ b/plugins/modules/nxos_feature.py @@ -117,7 +117,10 @@ def get_available_features(feature, module): if feature not in available_features: available_features[feature] = state else: - if available_features[feature] == "disabled" and state == "enabled": + if ( + available_features[feature] == "disabled" + and state == "enabled" + ): available_features[feature] = state # certain configurable features do not @@ -268,7 +271,9 @@ def main(): state=dict(choices=["enabled", "disabled"], default="enabled"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = dict(changed=False, warnings=warnings) diff --git a/plugins/modules/nxos_file_copy.py b/plugins/modules/nxos_file_copy.py index 4847a446e..23b3a25a8 100644 --- a/plugins/modules/nxos_file_copy.py +++ b/plugins/modules/nxos_file_copy.py @@ -252,14 +252,18 @@ def __init__(self, module): def md5sum_check(self, dst, file_system): command = "show file {0}{1} md5sum".format(file_system, dst) remote_filehash = self._connection.run_commands(command)[0] - remote_filehash = to_bytes(remote_filehash, errors="surrogate_or_strict") + remote_filehash = to_bytes( + remote_filehash, errors="surrogate_or_strict" + ) local_file = self._module.params["local_file"] try: with open(local_file, "rb") as f: filecontent = f.read() except (OSError, IOError) as exc: - self._module.fail_json("Error reading the file: {0}".format(to_text(exc))) + self._module.fail_json( + "Error reading the file: {0}".format(to_text(exc)) + ) filecontent = to_bytes(filecontent, errors="surrogate_or_strict") local_filehash = hashlib.md5(filecontent).hexdigest() @@ -291,9 +295,15 @@ def get_flash_size(self, file_system): match = re.search(r"No such file or directory", body) if match: - self._module.fail_json("Invalid nxos filesystem {0}".format(file_system)) + self._module.fail_json( + "Invalid nxos filesystem {0}".format(file_system) + ) else: - self._module.fail_json("Unable to determine size of filesystem {0}".format(file_system)) + self._module.fail_json( + "Unable to determine size of filesystem {0}".format( + file_system + ) + ) def enough_space(self, file, file_system): flash_size = self.get_flash_size(file_system) @@ -308,7 +318,9 @@ def transfer_file_to_device(self, remote_file): file_system = self._module.params["file_system"] if not self.enough_space(local_file, file_system): - self._module.fail_json("Could not transfer file. Not enough space on device.") + self._module.fail_json( + "Could not transfer file. Not enough space on device." + ) # frp = full_remote_path, flp = full_local_path frp = remote_file @@ -321,20 +333,28 @@ def transfer_file_to_device(self, remote_file): source=flp, destination=frp, proto="scp", - timeout=self._connection.get_option("persistent_command_timeout"), + timeout=self._connection.get_option( + "persistent_command_timeout" + ), ) - self.result["transfer_status"] = "Sent: File copied to remote device." + self.result[ + "transfer_status" + ] = "Sent: File copied to remote device." except Exception as exc: self.result["failed"] = True self.result["msg"] = "Exception received : %s" % exc def run(self): local_file = self._module.params["local_file"] - remote_file = self._module.params["remote_file"] or os.path.basename(local_file) + remote_file = self._module.params["remote_file"] or os.path.basename( + local_file + ) file_system = self._module.params["file_system"] if not os.path.isfile(local_file): - self._module.fail_json("Local file {0} not found".format(local_file)) + self._module.fail_json( + "Local file {0} not found".format(local_file) + ) remote_file = remote_file or os.path.basename(local_file) remote_exists = self.remote_file_exists(remote_file, file_system) @@ -343,7 +363,9 @@ def run(self): self.result["changed"] = True file_exists = False else: - self.result["transfer_status"] = "No Transfer: File already copied to remote device." + self.result[ + "transfer_status" + ] = "No Transfer: File already copied to remote device." file_exists = True if not self._module.check_mode and not file_exists: @@ -416,7 +438,9 @@ def copy_file_from_remote(self, local, local_file_directory, file_system): ) self.result["copy_cmd"] = copy_cmd - pulled = self._connection.pull_file(command=copy_cmd, remotepassword=rserverpassword) + pulled = self._connection.pull_file( + command=copy_cmd, remotepassword=rserverpassword + ) if pulled: self.result[ "transfer_status" @@ -427,7 +451,9 @@ def copy_file_from_remote(self, local, local_file_directory, file_system): def run(self): self.result["failed"] = False remote_file = self._module.params["remote_file"] - local_file = self._module.params["local_file"] or remote_file.split("/")[-1] + local_file = ( + self._module.params["local_file"] or remote_file.split("/")[-1] + ) file_system = self._module.params["file_system"] # Note: This is the local file directory on the remote nxos device. local_file_dir = self._module.params["local_file_directory"] @@ -441,7 +467,9 @@ def run(self): else: dir = "" self.result["local_file"] = file_system + dir + "/" + local_file - self.result["remote_scp_server"] = self._module.params["remote_scp_server"] + self.result["remote_scp_server"] = self._module.params[ + "remote_scp_server" + ] self.result["file_system"] = self._module.params["file_system"] if not self.result["failed"]: @@ -474,7 +502,9 @@ def main(): module = AnsibleModule( argument_spec=argument_spec, - required_if=[("file_pull", True, ("remote_file", "remote_scp_server"))], + required_if=[ + ("file_pull", True, ("remote_file", "remote_scp_server")) + ], required_together=[("remote_scp_server", "remote_scp_server_user")], supports_check_mode=True, ) diff --git a/plugins/modules/nxos_gir.py b/plugins/modules/nxos_gir.py index c473ff5ac..1a35b7c69 100644 --- a/plugins/modules/nxos_gir.py +++ b/plugins/modules/nxos_gir.py @@ -203,11 +203,15 @@ def get_commands(module, state, mode): commands = list() if module.params["system_mode_maintenance"] is True and mode == "normal": commands.append("system mode maintenance") - elif module.params["system_mode_maintenance"] is False and mode == "maintenance": + elif ( + module.params["system_mode_maintenance"] is False + and mode == "maintenance" + ): commands.append("no system mode maintenance") elif ( - module.params["system_mode_maintenance_dont_generate_profile"] is True and mode == "normal" + module.params["system_mode_maintenance_dont_generate_profile"] is True + and mode == "normal" ): commands.append("system mode maintenance dont-generate-profile") elif ( @@ -218,46 +222,65 @@ def get_commands(module, state, mode): elif module.params["system_mode_maintenance_timeout"]: timeout = get_maintenance_timeout(module) - if state == "present" and timeout != module.params["system_mode_maintenance_timeout"]: + if ( + state == "present" + and timeout != module.params["system_mode_maintenance_timeout"] + ): commands.append( "system mode maintenance timeout {0}".format( module.params["system_mode_maintenance_timeout"], ), ) - elif state == "absent" and timeout == module.params["system_mode_maintenance_timeout"]: + elif ( + state == "absent" + and timeout == module.params["system_mode_maintenance_timeout"] + ): commands.append( "no system mode maintenance timeout {0}".format( module.params["system_mode_maintenance_timeout"], ), ) - elif module.params["system_mode_maintenance_shutdown"] and mode == "normal": + elif ( + module.params["system_mode_maintenance_shutdown"] and mode == "normal" + ): commands.append("system mode maintenance shutdown") - elif module.params["system_mode_maintenance_shutdown"] is False and mode == "maintenance": + elif ( + module.params["system_mode_maintenance_shutdown"] is False + and mode == "maintenance" + ): commands.append("no system mode maintenance") elif module.params["system_mode_maintenance_on_reload_reset_reason"]: reset_reasons = get_reset_reasons(module) if ( state == "present" - and module.params["system_mode_maintenance_on_reload_reset_reason"].lower() + and module.params[ + "system_mode_maintenance_on_reload_reset_reason" + ].lower() not in reset_reasons.lower() ): commands.append( "system mode maintenance on-reload " "reset-reason {0}".format( - module.params["system_mode_maintenance_on_reload_reset_reason"], + module.params[ + "system_mode_maintenance_on_reload_reset_reason" + ], ), ) elif ( state == "absent" - and module.params["system_mode_maintenance_on_reload_reset_reason"].lower() + and module.params[ + "system_mode_maintenance_on_reload_reset_reason" + ].lower() in reset_reasons.lower() ): commands.append( "no system mode maintenance on-reload " "reset-reason {0}".format( - module.params["system_mode_maintenance_on_reload_reset_reason"], + module.params[ + "system_mode_maintenance_on_reload_reset_reason" + ], ), ) @@ -269,7 +292,9 @@ def get_commands(module, state, mode): def main(): argument_spec = dict( system_mode_maintenance=dict(required=False, type="bool"), - system_mode_maintenance_dont_generate_profile=dict(required=False, type="bool"), + system_mode_maintenance_dont_generate_profile=dict( + required=False, type="bool" + ), system_mode_maintenance_timeout=dict(required=False, type="str"), system_mode_maintenance_shutdown=dict(required=False, type="bool"), system_mode_maintenance_on_reload_reset_reason=dict( @@ -287,7 +312,9 @@ def main(): "maintenance", ], ), - state=dict(choices=["absent", "present"], default="present", required=False), + state=dict( + choices=["absent", "present"], default="present", required=False + ), ) module = AnsibleModule( diff --git a/plugins/modules/nxos_gir_profile_management.py b/plugins/modules/nxos_gir_profile_management.py index 2ddf2ce60..5b42ad844 100644 --- a/plugins/modules/nxos_gir_profile_management.py +++ b/plugins/modules/nxos_gir_profile_management.py @@ -170,7 +170,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_hsrp.py b/plugins/modules/nxos_hsrp.py index ee59b7ddc..7427d5d1d 100644 --- a/plugins/modules/nxos_hsrp.py +++ b/plugins/modules/nxos_hsrp.py @@ -215,7 +215,9 @@ def get_hsrp_group(group, interface, module): if "sh_keystring_attr" not in hsrp_table: del hsrp_key["sh_keystring_attr"] if "unknown enum:" in str(hsrp_table): - hsrp_table = get_hsrp_group_unknown_enum(module, command, hsrp_table) + hsrp_table = get_hsrp_group_unknown_enum( + module, command, hsrp_table + ) except (AttributeError, IndexError, TypeError, KeyError): return {} @@ -253,7 +255,9 @@ def get_hsrp_group_unknown_enum(module, command, hsrp_table): if "unknown enum:" in hsrp_table["sh_preempt"]: cmd = {"output": "text", "command": command.split("|")[0]} out = run_commands(module, cmd)[0] - hsrp_table["sh_preempt"] = "enabled" if ("may preempt" in out) else "disabled" + hsrp_table["sh_preempt"] = ( + "enabled" if ("may preempt" in out) else "disabled" + ) return hsrp_table @@ -285,7 +289,9 @@ def get_commands_config_hsrp(delta, interface, args, existing): if priority: if priority == "default": - if existing and existing.get("priority") != PARAM_TO_DEFAULT_KEYMAP.get("priority"): + if existing and existing.get( + "priority" + ) != PARAM_TO_DEFAULT_KEYMAP.get("priority"): delta["priority"] = "no priority" else: del delta["priority"] @@ -294,7 +300,9 @@ def get_commands_config_hsrp(delta, interface, args, existing): if vip: if vip == "default": - if existing and existing.get("vip") != PARAM_TO_DEFAULT_KEYMAP.get("vip"): + if existing and existing.get("vip") != PARAM_TO_DEFAULT_KEYMAP.get( + "vip" + ): delta["vip"] = "no ip" else: del delta["vip"] @@ -320,13 +328,17 @@ def get_commands_config_hsrp(delta, interface, args, existing): auth_string = args["auth_string"] if auth_string != "default": if auth_type == "md5": - command = "authentication md5 key-string {0} {1}".format(auth_enc, auth_string) + command = "authentication md5 key-string {0} {1}".format( + auth_enc, auth_string + ) commands.append(command) elif auth_type == "text": command = "authentication text {0}".format(auth_string) commands.append(command) else: - if existing and existing.get("auth_string") != PARAM_TO_DEFAULT_KEYMAP.get( + if existing and existing.get( + "auth_string" + ) != PARAM_TO_DEFAULT_KEYMAP.get( "auth_string", ): commands.append("no authentication") @@ -370,7 +382,9 @@ def is_default(interface, module): def validate_config(body, vip, module): new_body = "".join(body) if "invalid ip address" in new_body.lower(): - module.fail_json(msg="Invalid VIP. Possible duplicate IP address.", vip=vip) + module.fail_json( + msg="Invalid VIP. Possible duplicate IP address.", vip=vip + ) def main(): @@ -379,14 +393,20 @@ def main(): interface=dict(required=True), version=dict(choices=["1", "2"], default="1", required=False), priority=dict(type="str", required=False), - preempt=dict(type="str", choices=["disabled", "enabled"], required=False), + preempt=dict( + type="str", choices=["disabled", "enabled"], required=False + ), vip=dict(type="str", required=False), auth_type=dict(choices=["text", "md5"], required=False), auth_string=dict(type="str", required=False), - state=dict(choices=["absent", "present"], required=False, default="present"), + state=dict( + choices=["absent", "present"], required=False, default="present" + ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = dict(changed=False, warnings=warnings) @@ -433,14 +453,16 @@ def main(): mode = get_interface_mode(interface, intf_type, module) if mode == "layer2": module.fail_json( - msg="That interface is a layer2 port.\nMake it " "a layer 3 port first.", + msg="That interface is a layer2 port.\nMake it " + "a layer 3 port first.", interface=interface, ) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json( - msg="When using auth parameters, you need BOTH " "auth_type AND auth_string.", + msg="When using auth parameters, you need BOTH " + "auth_type AND auth_string.", ) args = dict( @@ -461,19 +483,26 @@ def main(): # This will enforce better practice with md5 and hsrp version. if proposed.get("auth_type", None) == "md5": if proposed["version"] == "1": - module.fail_json(msg="It's recommended to use HSRP v2 " "when auth_type=md5") + module.fail_json( + msg="It's recommended to use HSRP v2 " "when auth_type=md5" + ) elif not proposed.get("auth_type", None) and existing: - if (proposed["version"] == "1" and existing["auth_type"] == "md5") and state == "present": + if ( + proposed["version"] == "1" and existing["auth_type"] == "md5" + ) and state == "present": module.fail_json( - msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5", + msg="Existing auth_type is md5. It's recommended " + "to use HSRP v2 when using md5", ) commands = [] if state == "present": delta = dict(set(proposed.items()).difference(existing.items())) if delta: - command = get_commands_config_hsrp(delta, interface, args, existing) + command = get_commands_config_hsrp( + delta, interface, args, existing + ) commands.extend(command) elif state == "absent": diff --git a/plugins/modules/nxos_igmp.py b/plugins/modules/nxos_igmp.py index 937706162..64ca218b2 100644 --- a/plugins/modules/nxos_igmp.py +++ b/plugins/modules/nxos_igmp.py @@ -94,7 +94,9 @@ def get_current(module): - output = run_commands(module, {"command": "show running-config", "output": "text"}) + output = run_commands( + module, {"command": "show running-config", "output": "text"} + ) return { "flush_routes": "ip igmp flush-routes" in output[0], "enforce_rtr_alert": "ip igmp enforce-router-alert" in output[0], @@ -116,7 +118,9 @@ def main(): state=dict(choices=["present", "default"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_igmp_interface.py b/plugins/modules/nxos_igmp_interface.py index 66a2a495e..8d6763f1e 100644 --- a/plugins/modules/nxos_igmp_interface.py +++ b/plugins/modules/nxos_igmp_interface.py @@ -278,7 +278,9 @@ def get_igmp_interface(module, interface): elif report_llg == "false": igmp["report_llg"] = False - immediate_leave = str(resource["ImmediateLeave"]).lower() # returns en or dis + immediate_leave = str( + resource["ImmediateLeave"] + ).lower() # returns en or dis if re.search(r"^en|^true|^enabled", immediate_leave): igmp["immediate_leave"] = True elif re.search(r"^dis|^false|^disabled", immediate_leave): @@ -289,12 +291,16 @@ def get_igmp_interface(module, interface): # or PREFIX source , etc. command = "show run interface {0} | inc oif".format(interface) - body = execute_show_command(command, module, command_type="cli_show_ascii")[0] + body = execute_show_command( + command, module, command_type="cli_show_ascii" + )[0] staticoif = [] if body: split_body = body.split("\n") - route_map_regex = r".*ip igmp static-oif route-map\s+(?P\S+).*" + route_map_regex = ( + r".*ip igmp static-oif route-map\s+(?P\S+).*" + ) prefix_source_regex = ( r".*ip igmp static-oif\s+(?P" r"((\d+.){3}\d+))(\ssource\s" @@ -310,7 +316,9 @@ def get_igmp_interface(module, interface): route_map = "" try: - match_prefix_source = re.match(prefix_source_regex, line, re.DOTALL) + match_prefix_source = re.match( + prefix_source_regex, line, re.DOTALL + ) prefix_source_group = match_prefix_source.groupdict() prefix = prefix_source_group["prefix"] source = prefix_source_group["source"] @@ -374,7 +382,9 @@ def config_igmp_interface(delta, existing, existing_oif_prefix_source): if "source" in each.keys(): src = each["source"] if src: - commands.append(CMDS.get("oif_prefix_source").format(pf, src)) + commands.append( + CMDS.get("oif_prefix_source").format(pf, src) + ) else: commands.append(CMDS.get("oif_prefix").format(pf)) if existing_oif_prefix_source: @@ -386,10 +396,13 @@ def config_igmp_interface(delta, existing, existing_oif_prefix_source): src = each["source"] if src: commands.append( - "no " + CMDS.get("oif_prefix_source").format(pf, src), + "no " + + CMDS.get("oif_prefix_source").format(pf, src), ) else: - commands.append("no " + CMDS.get("oif_prefix").format(pf)) + commands.append( + "no " + CMDS.get("oif_prefix").format(pf) + ) elif key == "oif_routemap": if value == "default": if existing.get(key): @@ -442,7 +455,9 @@ def get_igmp_interface_defaults(): immediate_leave=immediate_leave, ) - default = dict((param, value) for (param, value) in args.items() if value is not None) + default = dict( + (param, value) for (param, value) in args.items() if value is not None + ) return default @@ -470,7 +485,9 @@ def config_remove_oif(existing, existing_oif_prefix_source): command = None if existing.get("oif_routemap"): commands.append( - "no ip igmp static-oif route-map {0}".format(existing.get("oif_routemap")), + "no ip igmp static-oif route-map {0}".format( + existing.get("oif_routemap") + ), ) elif existing_oif_prefix_source: for each in existing_oif_prefix_source: @@ -480,7 +497,9 @@ def config_remove_oif(existing, existing_oif_prefix_source): each.get("source"), ) elif each.get("prefix"): - command = "no ip igmp static-oif {0}".format(each.get("prefix")) + command = "no ip igmp static-oif {0}".format( + each.get("prefix") + ) if command: commands.append(command) command = None @@ -491,7 +510,9 @@ def config_remove_oif(existing, existing_oif_prefix_source): def main(): argument_spec = dict( interface=dict(required=True, type="str"), - version=dict(required=False, type="str", choices=["2", "3", "default"]), + version=dict( + required=False, type="str", choices=["2", "3", "default"] + ), startup_query_interval=dict(required=False, type="str"), startup_query_count=dict(required=False, type="str"), robustness=dict(required=False, type="str"), @@ -506,7 +527,9 @@ def main(): oif_routemap=dict(required=False, type="str"), oif_ps=dict(required=False, type="raw"), restart=dict(type="bool", default=False), - state=dict(choices=["present", "absent", "default"], default="present"), + state=dict( + choices=["present", "absent", "default"], default="present" + ), ) mutually_exclusive = [("oif_ps", "oif_routemap")] @@ -570,7 +593,9 @@ def main(): changed = False commands = [] - proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) CANNOT_ABSENT = [ "version", @@ -591,7 +616,9 @@ def main(): for each in CANNOT_ABSENT: if each in proposed: module.fail_json( - msg="only params: " "oif_ps, oif_routemap can be used when " "state=absent", + msg="only params: " + "oif_ps, oif_routemap can be used when " + "state=absent", ) # delta check for all params except oif_ps @@ -605,7 +632,9 @@ def main(): if state == "present": if delta: - command = config_igmp_interface(delta, existing, existing_oif_prefix_source) + command = config_igmp_interface( + delta, existing, existing_oif_prefix_source + ) if command: commands.append(command) diff --git a/plugins/modules/nxos_igmp_snooping.py b/plugins/modules/nxos_igmp_snooping.py index 6d14ba17b..d0c27a640 100644 --- a/plugins/modules/nxos_igmp_snooping.py +++ b/plugins/modules/nxos_igmp_snooping.py @@ -160,7 +160,9 @@ def get_igmp_snooping(module): link_local_grp_supp = str(body.get("glinklocalgrpsup")).lower() if "none" in link_local_grp_supp: - link_local_grp_supp = str(body.get("GlobalLinkLocalGroupSupression")).lower() + link_local_grp_supp = str( + body.get("GlobalLinkLocalGroupSupression") + ).lower() if link_local_grp_supp == "true" or link_local_grp_supp == "enabled": existing["link_local_grp_supp"] = True else: @@ -198,7 +200,9 @@ def config_igmp_snooping(delta, existing, default=False): if value: if default and key == "group_timeout": if existing.get(key): - gt_command = "no " + CMDS.get(key).format(existing.get(key)) + gt_command = "no " + CMDS.get(key).format( + existing.get(key) + ) elif value == "default" and key == "group_timeout": if existing.get(key): command = "no " + CMDS.get(key).format(existing.get(key)) @@ -232,7 +236,9 @@ def get_igmp_snooping_defaults(): group_timeout=group_timeout, ) - default = dict((param, value) for (param, value) in args.items() if value is not None) + default = dict( + (param, value) for (param, value) in args.items() if value is not None + ) return default @@ -262,7 +268,9 @@ def main(): state=dict(choices=["present", "default"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} @@ -282,7 +290,9 @@ def main(): group_timeout=group_timeout, ) - proposed = dict((param, value) for (param, value) in args.items() if value is not None) + proposed = dict( + (param, value) for (param, value) in args.items() if value is not None + ) existing = get_igmp_snooping(module) diff --git a/plugins/modules/nxos_install_os.py b/plugins/modules/nxos_install_os.py index 9b64a8989..ecba9df36 100644 --- a/plugins/modules/nxos_install_os.py +++ b/plugins/modules/nxos_install_os.py @@ -431,7 +431,10 @@ def check_mode_legacy(module, issu, image, kick=None): if target_image["error"]: data["error"] = True data["raw"] = target_image["raw"] - if current["kickstart_ver_str"] != target_image["version"] and not data["error"]: + if ( + current["kickstart_ver_str"] != target_image["version"] + and not data["error"] + ): data["upgrade_needed"] = True data["disruptive"] = True upgrade_msg = "Switch upgraded: system: %s" % tsver @@ -444,7 +447,10 @@ def check_mode_legacy(module, issu, image, kick=None): if target_kick["error"]: data["error"] = True data["raw"] = target_kick["raw"] - if current["kickstart_ver_str"] != target_kick["version"] and not data["error"]: + if ( + current["kickstart_ver_str"] != target_kick["version"] + and not data["error"] + ): data["upgrade_needed"] = True data["disruptive"] = True upgrade_msg = upgrade_msg + " kickstart: %s" % tkver @@ -534,7 +540,9 @@ def do_install_all(module, issu, image, kick=None): if upgrade["invalid_command"] and "force" in commands[1]: # Not all platforms support the 'force' keyword. Check for this # condition and re-try without the 'force' keyword if needed. - commands = build_install_cmd_set(issu, image, kick, "install", False) + commands = build_install_cmd_set( + issu, image, kick, "install", False + ) upgrade = check_install_in_progress(module, commands, opts) upgrade["upgrade_cmd"] = commands @@ -566,7 +574,9 @@ def main(): issu=dict(choices=["required", "desired", "no", "yes"], default="no"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_lacp.py b/plugins/modules/nxos_lacp.py index 257c1384e..197853f61 100644 --- a/plugins/modules/nxos_lacp.py +++ b/plugins/modules/nxos_lacp.py @@ -246,7 +246,9 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lacp.lacp import ( LacpArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.lacp.lacp import Lacp +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.lacp.lacp import ( + Lacp, +) def main(): diff --git a/plugins/modules/nxos_logging.py b/plugins/modules/nxos_logging.py index a6e6ccfff..8ed8f13c6 100644 --- a/plugins/modules/nxos_logging.py +++ b/plugins/modules/nxos_logging.py @@ -266,10 +266,13 @@ def map_obj_to_commands(module, updates): if ( not w["dest"] and not w["facility_link_status"] - and w["facility"] not in DEFAULT_LOGGING_LEVEL[int(w["facility_level"])] + and w["facility"] + not in DEFAULT_LOGGING_LEVEL[int(w["facility_level"])] ): commands.append( - "no logging level {0} {1}".format(w["facility"], w["facility_level"]), + "no logging level {0} {1}".format( + w["facility"], w["facility_level"] + ), ) if w["facility_link_status"] and w["facility"] in ("ethpm"): @@ -287,7 +290,9 @@ def map_obj_to_commands(module, updates): commands.append("no logging {0}".format(w["dest"])) if w["dest"] == "server": - commands.append("no logging server {0}".format(w["remote_server"])) + commands.append( + "no logging server {0}".format(w["remote_server"]) + ) if w["interface"]: commands.append("no logging source-interface") @@ -305,7 +310,11 @@ def map_obj_to_commands(module, updates): if w["facility"] is None: if w["dest"]: if w["dest"] not in ("logfile", "server"): - commands.append("logging {0} {1}".format(w["dest"], w["dest_level"])) + commands.append( + "logging {0} {1}".format( + w["dest"], w["dest_level"] + ) + ) elif w["dest"] == "logfile": if w["file_size"]: @@ -318,7 +327,9 @@ def map_obj_to_commands(module, updates): ) else: commands.append( - "logging logfile {0} {1}".format(w["name"], w["dest_level"]), + "logging logfile {0} {1}".format( + w["name"], w["dest_level"] + ), ) elif w["dest"] == "server": @@ -348,7 +359,11 @@ def map_obj_to_commands(module, updates): ), ) else: - commands.append("logging server {0}".format(w["remote_server"])) + commands.append( + "logging server {0}".format( + w["remote_server"] + ) + ) if w["facility"]: if w["dest"] == "server": @@ -395,14 +410,20 @@ def map_obj_to_commands(module, updates): ), ) else: - if not match_facility_default(module, w["facility"], w["facility_level"]): + if not match_facility_default( + module, w["facility"], w["facility_level"] + ): commands.append( - "logging level {0} {1}".format(w["facility"], w["facility_level"]), + "logging level {0} {1}".format( + w["facility"], w["facility_level"] + ), ) if w["interface"]: commands.append( - "logging source-interface {0} {1}".format(*split_interface(w["interface"])), + "logging source-interface {0} {1}".format( + *split_interface(w["interface"]) + ), ) if w["event"] and w["event"] in STATIC_CLI: @@ -438,7 +459,11 @@ def match_facility_default(module, facility, want_level): facility_data = run_commands(module, cmd) for line in facility_data[0].split("\n"): mo = re.search(regexl, line) - if mo and int(mo.group(1)) == int(want_level) and int(mo.group(2)) == int(want_level): + if ( + mo + and int(mo.group(1)) == int(want_level) + and int(mo.group(2)) == int(want_level) + ): matches_default = True return matches_default @@ -454,7 +479,9 @@ def parse_facility_link_status(line, facility, status): facility_link_status = None if facility is not None: - match = re.search(r"logging level {0} {1} (\S+)".format(facility, status), line, re.M) + match = re.search( + r"logging level {0} {1} (\S+)".format(facility, status), line, re.M + ) if match: facility_link_status = status + "-" + match.group(1) @@ -464,7 +491,9 @@ def parse_facility_link_status(line, facility, status): def parse_event_status(line, event): status = None - match = re.search(r"logging event {0} (\S+)".format(event + "-status"), line, re.M) + match = re.search( + r"logging event {0} (\S+)".format(event + "-status"), line, re.M + ) if match: state = match.group(1) if state: @@ -490,7 +519,9 @@ def parse_event(line): def parse_message(line): message = None - match = re.search(r"logging message interface type ethernet description", line, re.M) + match = re.search( + r"logging message interface type ethernet description", line, re.M + ) if match: message = "add-interface-description" @@ -500,7 +531,9 @@ def parse_message(line): def parse_file_size(line, name, level): file_size = None - match = re.search(r"logging logfile {0} {1} size (\S+)".format(name, level), line, re.M) + match = re.search( + r"logging logfile {0} {1} size (\S+)".format(name, level), line, re.M + ) if match: file_size = match.group(1) if file_size == "8192" or file_size == "4194304": @@ -558,7 +591,9 @@ def parse_match(match): if dest and dest != "server": if dest == "logfile": - match = re.search(r"logging logfile {0} (\S+)".format(name), line, re.M) + match = re.search( + r"logging logfile {0} (\S+)".format(name), line, re.M + ) if match: dest_level = parse_match(match) @@ -583,7 +618,9 @@ def parse_facility_level(line, facility, dest): facility_level = match.group(1) elif facility is not None: - match = re.search(r"logging level {0} (\S+)".format(facility), line, re.M) + match = re.search( + r"logging level {0} (\S+)".format(facility), line, re.M + ) if match: facility_level = match.group(1) @@ -608,7 +645,9 @@ def parse_use_vrf(line, dest): use_vrf = None if dest and dest == "server": - match = re.search(r"logging server (?:\S+) (?:\d+) use-vrf (\S+)", line, re.M) + match = re.search( + r"logging server (?:\S+) (?:\d+) use-vrf (\S+)", line, re.M + ) if match: use_vrf = match.group(1) @@ -671,7 +710,9 @@ def map_config_to_obj(module): if level.isdigit(): facility_level = level else: - facility_link_status = parse_facility_link_status(line, facility, level) + facility_link_status = parse_facility_link_status( + line, facility, level + ) elif match.group(1) == "event" and state == "present": event = parse_event(line) @@ -727,7 +768,10 @@ def map_config_to_obj(module): if match.group(1) == "console" and match.group(2) == "critical": dest_level = "2" flag = True - elif match.group(1) == "monitor" and match.group(2) == "notifications": + elif ( + match.group(1) == "monitor" + and match.group(2) == "notifications" + ): dest_level = "5" flag = True if flag: @@ -926,7 +970,9 @@ def main(): save_module_context(module, merged_wants) if module.params.get("purge"): - pcommands = map_obj_to_commands(module, (outliers(have, merged_wants), have)) + pcommands = map_obj_to_commands( + module, (outliers(have, merged_wants), have) + ) if pcommands: if not module.check_mode: load_config(module, pcommands) diff --git a/plugins/modules/nxos_ntp.py b/plugins/modules/nxos_ntp.py index 046436d47..f1d596a55 100644 --- a/plugins/modules/nxos_ntp.py +++ b/plugins/modules/nxos_ntp.py @@ -150,7 +150,9 @@ def get_ntp_source(module): source_type = None source = None command = "show run | inc ntp.source" - output = execute_show_command(command, module, command_type="cli_show_ascii") + output = execute_show_command( + command, module, command_type="cli_show_ascii" + ) if output: try: @@ -169,7 +171,9 @@ def get_ntp_source(module): def get_ntp_peer(module): command = "show run | inc ntp.(server|peer)" ntp_peer_list = [] - response = execute_show_command(command, module, command_type="cli_show_ascii") + response = execute_show_command( + command, module, command_type="cli_show_ascii" + ) if response: if isinstance(response, list): @@ -301,17 +305,27 @@ def config_ntp(delta, existing): if peer_type: if existing.get("peer_type") and existing.get("address"): ntp_cmds.append( - "no ntp {0} {1}".format(existing.get("peer_type"), existing.get("address")), + "no ntp {0} {1}".format( + existing.get("peer_type"), existing.get("address") + ), ) - ntp_cmds.append(set_ntp_server_peer(peer_type, address, prefer, key_id, vrf_name)) + ntp_cmds.append( + set_ntp_server_peer(peer_type, address, prefer, key_id, vrf_name) + ) if source: existing_source_type = existing.get("source_type") existing_source = existing.get("source") if existing_source_type and source_type != existing_source_type: - ntp_cmds.append("no ntp {0} {1}".format(existing_source_type, existing_source)) + ntp_cmds.append( + "no ntp {0} {1}".format(existing_source_type, existing_source) + ) if source == "default": if existing_source_type and existing_source: - ntp_cmds.append("no ntp {0} {1}".format(existing_source_type, existing_source)) + ntp_cmds.append( + "no ntp {0} {1}".format( + existing_source_type, existing_source + ) + ) else: ntp_cmds.append("ntp {0} {1}".format(source_type, source)) @@ -403,7 +417,9 @@ def main(): elif state == "absent": if existing.get("peer_type") and existing.get("address"): - command = "no ntp {0} {1}".format(existing["peer_type"], existing["address"]) + command = "no ntp {0} {1}".format( + existing["peer_type"], existing["address"] + ) if command: commands.append([command]) @@ -415,7 +431,9 @@ def main(): if proposed_source_type: if proposed_source_type == existing_source_type: if proposed_source == existing_source: - command = "no ntp {0} {1}".format(existing_source_type, existing_source) + command = "no ntp {0} {1}".format( + existing_source_type, existing_source + ) if command: commands.append([command]) diff --git a/plugins/modules/nxos_ntp_auth.py b/plugins/modules/nxos_ntp_auth.py index 3e5643812..df3f7ee4f 100644 --- a/plugins/modules/nxos_ntp_auth.py +++ b/plugins/modules/nxos_ntp_auth.py @@ -165,9 +165,7 @@ def get_ntp_trusted_key(module): def get_ntp_auth_key(key_id, module): authentication_key = {} command = "show run | inc ntp.authentication-key.{0}".format(key_id) - auth_regex = ( - r".*ntp\sauthentication-key\s(?P\d+)\smd5\s(?P\S+)\s(?P\S+).*" - ) + auth_regex = r".*ntp\sauthentication-key\s(?P\d+)\smd5\s(?P\S+)\s(?P\S+).*" body = execute_show_command(command, module)[0] @@ -211,12 +209,16 @@ def auth_type_to_num(auth_type): return "0" -def set_ntp_auth_key(key_id, md5string, auth_type, trusted_key, authentication): +def set_ntp_auth_key( + key_id, md5string, auth_type, trusted_key, authentication +): ntp_auth_cmds = [] if key_id and md5string: auth_type_num = auth_type_to_num(auth_type) ntp_auth_cmds.append( - "ntp authentication-key {0} md5 {1} {2}".format(key_id, md5string, auth_type_num), + "ntp authentication-key {0} md5 {1} {2}".format( + key_id, md5string, auth_type_num + ), ) if trusted_key == "true": @@ -232,12 +234,16 @@ def set_ntp_auth_key(key_id, md5string, auth_type, trusted_key, authentication): return ntp_auth_cmds -def remove_ntp_auth_key(key_id, md5string, auth_type, trusted_key, authentication): +def remove_ntp_auth_key( + key_id, md5string, auth_type, trusted_key, authentication +): auth_remove_cmds = [] if key_id: auth_type_num = auth_type_to_num(auth_type) auth_remove_cmds.append( - "no ntp authentication-key {0} md5 {1} {2}".format(key_id, md5string, auth_type_num), + "no ntp authentication-key {0} md5 {1} {2}".format( + key_id, md5string, auth_type_num + ), ) if authentication: @@ -255,7 +261,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() @@ -304,7 +312,9 @@ def main(): auth_toggle = True if not existing.get("key_id"): key_id = None - command = remove_ntp_auth_key(key_id, md5string, auth_type, trusted_key, auth_toggle) + command = remove_ntp_auth_key( + key_id, md5string, auth_type, trusted_key, auth_toggle + ) if command: commands.append(command) diff --git a/plugins/modules/nxos_ntp_options.py b/plugins/modules/nxos_ntp_options.py index 28fd1aac6..260ebb3ea 100644 --- a/plugins/modules/nxos_ntp_options.py +++ b/plugins/modules/nxos_ntp_options.py @@ -118,7 +118,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_nxapi.py b/plugins/modules/nxos_nxapi.py index 400a7a5f5..6bac79609 100644 --- a/plugins/modules/nxos_nxapi.py +++ b/plugins/modules/nxos_nxapi.py @@ -165,7 +165,9 @@ load_config, run_commands, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import Version +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( + Version, +) def check_args(module, warnings, capabilities): @@ -250,11 +252,15 @@ def needs_update(x): commands["sandbox"] = "no %s" % commands["sandbox"] if os_platform and os_version: - if (os_platform == "N9K" or os_platform == "N3K") and Version(os_version) >= "9.2": + if (os_platform == "N9K" or os_platform == "N3K") and Version( + os_version + ) >= "9.2": if needs_update("ssl_strong_ciphers"): commands["ssl_strong_ciphers"] = "nxapi ssl ciphers weak" if want["ssl_strong_ciphers"] is True: - commands["ssl_strong_ciphers"] = "no nxapi ssl ciphers weak" + commands[ + "ssl_strong_ciphers" + ] = "no nxapi ssl ciphers weak" have_ssl_protocols = "" want_ssl_protocols = "" @@ -265,7 +271,9 @@ def needs_update(x): }.items(): if needs_update(key): if want.get(key) is True: - want_ssl_protocols = " ".join([want_ssl_protocols, value]) + want_ssl_protocols = " ".join( + [want_ssl_protocols, value] + ) elif have.get(key) is True: have_ssl_protocols = " ".join([have_ssl_protocols, value]) @@ -312,7 +320,9 @@ def parse_https(data): def parse_sandbox(data): - sandbox = [item for item in data.split("\n") if re.search(r".*sandbox.*", item)] + sandbox = [ + item for item in data.split("\n") if re.search(r".*sandbox.*", item) + ] value = False if sandbox and sandbox[0] == "nxapi sandbox": value = True @@ -393,13 +403,19 @@ def main(): tlsv1_2=dict(type="bool", default=False), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() - warning_msg = "Module nxos_nxapi currently defaults to configure 'http port 80'. " + warning_msg = ( + "Module nxos_nxapi currently defaults to configure 'http port 80'. " + ) warning_msg += "Default behavior is changing to configure 'https port 443'" warning_msg += " when params 'http, http_port, https, https_port' are not set in the playbook" - module.deprecate(msg=warning_msg, date="2022-06-01", collection_name="cisco.nxos") + module.deprecate( + msg=warning_msg, date="2022-06-01", collection_name="cisco.nxos" + ) capabilities = get_capabilities(module) diff --git a/plugins/modules/nxos_overlay_global.py b/plugins/modules/nxos_overlay_global.py index 70b25246a..2a41cac9b 100644 --- a/plugins/modules/nxos_overlay_global.py +++ b/plugins/modules/nxos_overlay_global.py @@ -70,7 +70,9 @@ ) -PARAM_TO_COMMAND_KEYMAP = {"anycast_gateway_mac": "fabric forwarding anycast-gateway-mac"} +PARAM_TO_COMMAND_KEYMAP = { + "anycast_gateway_mac": "fabric forwarding anycast-gateway-mac" +} def get_existing(module, args): @@ -79,7 +81,9 @@ def get_existing(module, args): for arg in args: command = PARAM_TO_COMMAND_KEYMAP[arg] - has_command = re.findall(r"(?:{0}\s)(?P.*)$".format(command), config, re.M) + has_command = re.findall( + r"(?:{0}\s)(?P.*)$".format(command), config, re.M + ) value = "" if has_command: value = has_command[0] @@ -154,7 +158,9 @@ def normalize_mac(proposed_mac, module): else: raise ValueError except ValueError: - module.fail_json(msg="Invalid MAC address format", proposed_mac=proposed_mac) + module.fail_json( + msg="Invalid MAC address format", proposed_mac=proposed_mac + ) joined_mac = "".join(splitted_mac) # fmt: off @@ -166,7 +172,9 @@ def normalize_mac(proposed_mac, module): def main(): argument_spec = dict(anycast_gateway_mac=dict(required=True, type="str")) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() result = {"changed": False, "commands": [], "warnings": warnings} @@ -174,7 +182,9 @@ def main(): args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) - proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) candidate = CustomNetworkConfig(indent=3) get_commands(module, existing, proposed, candidate) diff --git a/plugins/modules/nxos_pim.py b/plugins/modules/nxos_pim.py index d9fc6f469..b49a96fa1 100644 --- a/plugins/modules/nxos_pim.py +++ b/plugins/modules/nxos_pim.py @@ -157,10 +157,14 @@ def get_commands(module, existing, proposed, candidate): def main(): argument_spec = dict( bfd=dict(required=False, type="str", choices=["enable", "disable"]), - ssm_range=dict(required=False, type="list", default=[], elements="str"), + ssm_range=dict( + required=False, type="list", default=[], elements="str" + ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() result = {"changed": False, "commands": [], "warnings": warnings} diff --git a/plugins/modules/nxos_pim_interface.py b/plugins/modules/nxos_pim_interface.py index 4d0f1052b..d9e31d6f9 100644 --- a/plugins/modules/nxos_pim_interface.py +++ b/plugins/modules/nxos_pim_interface.py @@ -315,9 +315,13 @@ def get_pim_interface(module, interface): elif "sparse-mode" in each: pim_interface["sparse"] = True elif "bfd-instance" in each: - m = re.search(r"ip pim bfd-instance(?P disable)?", each) + m = re.search( + r"ip pim bfd-instance(?P disable)?", each + ) if m: - pim_interface["bfd"] = "disable" if m.group("disable") else "enable" + pim_interface["bfd"] = ( + "disable" if m.group("disable") else "enable" + ) elif "border" in each: pim_interface["border"] = True elif "hello-interval" in each: @@ -326,7 +330,9 @@ def get_pim_interface(module, interface): body, ).group(1) elif "dr-priority" in each: - pim_interface["dr_prio"] = re.search(r"ip pim dr-priority (\d+)", body).group(1) + pim_interface["dr_prio"] = re.search( + r"ip pim dr-priority (\d+)", body + ).group(1) return pim_interface @@ -334,7 +340,10 @@ def get_pim_interface(module, interface): def fix_delta(delta, existing): for key in list(delta): if key in ["dr_prio", "hello_interval", "sparse", "border"]: - if delta.get(key) == PARAM_TO_DEFAULT_KEYMAP.get(key) and existing.get(key) is None: + if ( + delta.get(key) == PARAM_TO_DEFAULT_KEYMAP.get(key) + and existing.get(key) is None + ): delta.pop(key) return delta @@ -348,9 +357,13 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): if jp_bidir: if delta.get("jp_policy_in") or delta.get("jp_policy_out"): if existing.get("jp_type_in") == "prefix": - command = "no ip pim jp-policy prefix-list {0}".format(existing.get("jp_policy_in")) + command = "no ip pim jp-policy prefix-list {0}".format( + existing.get("jp_policy_in") + ) else: - command = "no ip pim jp-policy {0}".format(existing.get("jp_policy_in")) + command = "no ip pim jp-policy {0}".format( + existing.get("jp_policy_in") + ) if command: commands.append(command) @@ -382,7 +395,9 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): "neighbor_type", ]: if k in ["neighbor_policy", "neighbor_type"]: - temp = delta.get("neighbor_policy") or existing.get("neighbor_policy") + temp = delta.get("neighbor_policy") or existing.get( + "neighbor_policy" + ) if delta.get("neighbor_type") == "prefix": command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp) elif delta.get("neighbor_type") == "routemap": @@ -392,7 +407,9 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): elif existing.get("neighbor_type") == "routemap": command = "ip pim neighbor-policy {0}".format(temp) elif k in ["jp_policy_in", "jp_type_in"]: - temp = delta.get("jp_policy_in") or existing.get("jp_policy_in") + temp = delta.get("jp_policy_in") or existing.get( + "jp_policy_in" + ) if delta.get("jp_type_in") == "prefix": command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp) elif delta.get("jp_type_in") == "routemap": @@ -402,7 +419,9 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): elif existing.get("jp_type_in") == "routemap": command = "ip pim jp-policy {0} in".format(temp) elif k in ["jp_policy_out", "jp_type_out"]: - temp = delta.get("jp_policy_out") or existing.get("jp_policy_out") + temp = delta.get("jp_policy_out") or existing.get( + "jp_policy_out" + ) if delta.get("jp_type_out") == "prefix": command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp) elif delta.get("jp_type_out") == "routemap": @@ -432,7 +451,9 @@ def get_pim_interface_defaults(): hello_auth_key=PARAM_TO_DEFAULT_KEYMAP.get("hello_auth_key"), ) - default = dict((param, value) for (param, value) in args.items() if value is not None) + default = dict( + (param, value) for (param, value) in args.items() if value is not None + ) return default @@ -443,7 +464,9 @@ def default_pim_interface_policies(existing, jp_bidir): if jp_bidir: if existing.get("jp_policy_in") or existing.get("jp_policy_out"): if existing.get("jp_type_in") == "prefix": - command = "no ip pim jp-policy prefix-list {0}".format(existing.get("jp_policy_in")) + command = "no ip pim jp-policy prefix-list {0}".format( + existing.get("jp_policy_in") + ) if command: commands.append(command) @@ -453,16 +476,22 @@ def default_pim_interface_policies(existing, jp_bidir): if k == "jp_policy_in": if existing.get("jp_policy_in"): if existing.get("jp_type_in") == "prefix": - command = "no ip pim jp-policy prefix-list {0} in".format( - existing.get("jp_policy_in"), + command = ( + "no ip pim jp-policy prefix-list {0} in".format( + existing.get("jp_policy_in"), + ) ) else: - command = "no ip pim jp-policy {0} in".format(existing.get("jp_policy_in")) + command = "no ip pim jp-policy {0} in".format( + existing.get("jp_policy_in") + ) elif k == "jp_policy_out": if existing.get("jp_policy_out"): if existing.get("jp_type_out") == "prefix": - command = "no ip pim jp-policy prefix-list {0} out".format( - existing.get("jp_policy_out"), + command = ( + "no ip pim jp-policy prefix-list {0} out".format( + existing.get("jp_policy_out"), + ) ) else: command = "no ip pim jp-policy {0} out".format( @@ -556,19 +585,27 @@ def main(): if jp_policy_in: if not jp_type_in: - module.fail_json(msg="jp_type_in required when using jp_policy_in.") + module.fail_json( + msg="jp_type_in required when using jp_policy_in." + ) if jp_policy_out: if not jp_type_out: - module.fail_json(msg="jp_type_out required when using jp_policy_out.") + module.fail_json( + msg="jp_type_out required when using jp_policy_out." + ) if neighbor_policy: if not neighbor_type: - module.fail_json(msg="neighbor_type required when using neighbor_policy.") + module.fail_json( + msg="neighbor_type required when using neighbor_policy." + ) get_existing = get_pim_interface(module, interface) existing, jp_bidir, isauth = local_existing(get_existing) args = PARAM_TO_COMMAND_KEYMAP.keys() - proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) normalize_proposed_values(proposed, module) delta = dict(set(proposed.items()).difference(existing.items())) diff --git a/plugins/modules/nxos_pim_rp_address.py b/plugins/modules/nxos_pim_rp_address.py index fe9989ed9..a6feb8c98 100644 --- a/plugins/modules/nxos_pim_rp_address.py +++ b/plugins/modules/nxos_pim_rp_address.py @@ -144,7 +144,9 @@ def state_present(module, existing, proposed, candidate): def build_command(param_dict, command): for param in ["group_list", "prefix_list", "route_map"]: if param_dict.get(param): - command += " {0} {1}".format(param.replace("_", "-"), param_dict.get(param)) + command += " {0} {1}".format( + param.replace("_", "-"), param_dict.get(param) + ) if param_dict.get("bidir"): command += " bidir" return [command] @@ -187,7 +189,9 @@ def main(): prefix_list=dict(required=False, type="str"), route_map=dict(required=False, type="str"), bidir=dict(required=False, type="bool"), - state=dict(choices=["present", "absent"], default="present", required=False), + state=dict( + choices=["present", "absent"], default="present", required=False + ), ) module = AnsibleModule( @@ -207,7 +211,9 @@ def main(): args = ["rp_address", "group_list", "prefix_list", "route_map", "bidir"] - proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed_args = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) if module.params["group_list"]: existing = get_existing(module, args, True) diff --git a/plugins/modules/nxos_ping.py b/plugins/modules/nxos_ping.py index 31c8517a7..c1c8a9685 100644 --- a/plugins/modules/nxos_ping.py +++ b/plugins/modules/nxos_ping.py @@ -132,7 +132,9 @@ """ from ansible.module_utils.basic import AnsibleModule -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( + run_commands, +) def get_summary(results_list, reference_point): @@ -202,7 +204,9 @@ def get_ping_results(command, module): splitted_ping = ping.split("\n") reference_point = get_statistics_summary_line(splitted_ping) summary, ping_pass = get_summary(splitted_ping, reference_point) - rtt = get_rtt(splitted_ping, summary["packet_loss"], reference_point + 2) + rtt = get_rtt( + splitted_ping, summary["packet_loss"], reference_point + 2 + ) return (summary, rtt, ping_pass) @@ -215,10 +219,14 @@ def main(): source=dict(required=False), size=dict(required=False, type="int"), df_bit=dict(required=False, default=False, type="bool"), - state=dict(required=False, choices=["present", "absent"], default="present"), + state=dict( + required=False, choices=["present", "absent"], default="present" + ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) destination = module.params["dest"] state = module.params["state"] diff --git a/plugins/modules/nxos_reboot.py b/plugins/modules/nxos_reboot.py index 51d0d70af..5f917438e 100644 --- a/plugins/modules/nxos_reboot.py +++ b/plugins/modules/nxos_reboot.py @@ -60,7 +60,9 @@ from ansible.module_utils.basic import AnsibleModule -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import load_config +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( + load_config, +) def reboot(module): @@ -72,7 +74,9 @@ def reboot(module): def main(): argument_spec = dict(confirm=dict(default=False, type="bool")) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = dict(changed=False, warnings=warnings) diff --git a/plugins/modules/nxos_rollback.py b/plugins/modules/nxos_rollback.py index 4b26919d1..ebd6519bd 100644 --- a/plugins/modules/nxos_rollback.py +++ b/plugins/modules/nxos_rollback.py @@ -77,7 +77,9 @@ from ansible.module_utils.basic import AnsibleModule -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( + run_commands, +) def checkpoint(filename, module): @@ -99,7 +101,9 @@ def rollback(filename, module): def main(): - argument_spec = dict(checkpoint_file=dict(required=False), rollback_to=dict(required=False)) + argument_spec = dict( + checkpoint_file=dict(required=False), rollback_to=dict(required=False) + ) module = AnsibleModule( argument_spec=argument_spec, diff --git a/plugins/modules/nxos_rpm.py b/plugins/modules/nxos_rpm.py index 7d7ab4db4..1f4896828 100644 --- a/plugins/modules/nxos_rpm.py +++ b/plugins/modules/nxos_rpm.py @@ -202,7 +202,8 @@ def activate_reload(module, pkg, flag): if "socket is closed" in msg[0].lower(): return cmd if ( - "another install operation is in progress" in msg[0].lower() + "another install operation is in progress" + in msg[0].lower() or "failed" in msg[0].lower() ): time.sleep(2) @@ -261,7 +262,11 @@ def install_remove_rpm(module, full_pkg, file_system, state): active_body = execute_show_command(show_active, module) if pkg not in inactive_body and pkg not in active_body: - commands.append(add_operation(module, show_inactive, file_system, full_pkg, pkg)) + commands.append( + add_operation( + module, show_inactive, file_system, full_pkg, pkg + ) + ) patch_type_body = execute_show_command(show_pkg_info, module) if patch_type_body and "Patch Type : reload" in patch_type_body: @@ -280,9 +285,13 @@ def install_remove_rpm(module, full_pkg, file_system, state): patch_body = execute_show_command(show_patches, module) if pkg in patch_body: # This is smu/patch rpm - commands.append(commit_operation(module, show_commit, pkg, False)) + commands.append( + commit_operation(module, show_commit, pkg, False) + ) else: - err = 'Operation "install activate {0} forced" Failed'.format(pkg) + err = 'Operation "install activate {0} forced" Failed'.format( + pkg + ) module.fail_json(msg=err) else: @@ -299,11 +308,15 @@ def install_remove_rpm(module, full_pkg, file_system, state): commands.append(activate_reload(module, pkg, False)) return commands else: - commands.append(deactivate_operation(module, show_active, pkg, True)) + commands.append( + deactivate_operation(module, show_active, pkg, True) + ) commit_body = execute_show_command(show_commit, module) if pkg in commit_body: # This is smu/patch rpm - commands.append(commit_operation(module, show_commit, pkg, True)) + commands.append( + commit_operation(module, show_commit, pkg, True) + ) commands.extend(remove_operation(module, show_inactive, pkg)) elif pkg in commit_body: @@ -317,7 +330,9 @@ def install_remove_rpm(module, full_pkg, file_system, state): commands.append(activate_reload(module, pkg, False)) return commands else: - commands.append(deactivate_operation(module, show_inactive, pkg, False)) + commands.append( + deactivate_operation(module, show_inactive, pkg, False) + ) commands.extend(remove_operation(module, show_inactive, pkg)) else: @@ -341,7 +356,9 @@ def main(): # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) - argument_spec = dict(aggregate=dict(type="list", elements="dict", options=aggregate_spec)) + argument_spec = dict( + aggregate=dict(type="list", elements="dict", options=aggregate_spec) + ) argument_spec.update(element_spec) required_one_of = [["pkg", "aggregate"]] @@ -378,12 +395,18 @@ def main(): for obj in objects: if obj["state"] == "present": - remote_exists = remote_file_exists(module, obj["pkg"], file_system=obj["file_system"]) + remote_exists = remote_file_exists( + module, obj["pkg"], file_system=obj["file_system"] + ) if not remote_exists: - module.fail_json(msg="The requested package doesn't exist on the device") + module.fail_json( + msg="The requested package doesn't exist on the device" + ) - cmds = install_remove_rpm(module, obj["pkg"], obj["file_system"], obj["state"]) + cmds = install_remove_rpm( + module, obj["pkg"], obj["file_system"], obj["state"] + ) if cmds: results["changed"] = True diff --git a/plugins/modules/nxos_snapshot.py b/plugins/modules/nxos_snapshot.py index 7d59810a8..2479b69de 100644 --- a/plugins/modules/nxos_snapshot.py +++ b/plugins/modules/nxos_snapshot.py @@ -290,7 +290,9 @@ def action_delete(module, existing_snapshots): exist = True if exist: - commands.append("snapshot delete {0}".format(module.params["snapshot_name"])) + commands.append( + "snapshot delete {0}".format(module.params["snapshot_name"]) + ) return commands @@ -369,7 +371,11 @@ def main(): comparison_results_file = module.params["comparison_results_file"] if not os.path.isdir(module.params["path"]): - module.fail_json(msg="{0} is not a valid directory name.".format(module.params["path"])) + module.fail_json( + msg="{0} is not a valid directory name.".format( + module.params["path"] + ) + ) existing_snapshots = invoke("get_existing", module) action_results = invoke("action_%s" % action, module, existing_snapshots) @@ -384,7 +390,9 @@ def main(): snapshot1 = module.params["snapshot1"] snapshot2 = module.params["snapshot2"] compare_option = module.params["compare_option"] - command = "show snapshot compare {0} {1}".format(snapshot1, snapshot2) + command = "show snapshot compare {0} {1}".format( + snapshot1, snapshot2 + ) if compare_option: command += " {0}".format(compare_option) content = execute_show_command(command, module)[0] @@ -401,10 +409,14 @@ def main(): and module.params["path"] and module.params["save_snapshot_locally"] ): - command = "show snapshot dump {0} | json".format(module.params["snapshot_name"]) + command = "show snapshot dump {0} | json".format( + module.params["snapshot_name"] + ) content = execute_show_command(command, module)[0] if content: - write_on_file(str(content), module.params["snapshot_name"], module) + write_on_file( + str(content), module.params["snapshot_name"], module + ) module.exit_json(**result) diff --git a/plugins/modules/nxos_snmp_community.py b/plugins/modules/nxos_snmp_community.py index 4e94b1f00..fd5f9c43e 100644 --- a/plugins/modules/nxos_snmp_community.py +++ b/plugins/modules/nxos_snmp_community.py @@ -214,7 +214,9 @@ def main(): configured_groups = get_snmp_groups(module) if group not in configured_groups: - module.fail_json(msg="Group not on switch. Please add before moving forward") + module.fail_json( + msg="Group not on switch. Please add before moving forward" + ) existing = get_snmp_community(module, community) args = dict(group=group, acl=acl) diff --git a/plugins/modules/nxos_snmp_contact.py b/plugins/modules/nxos_snmp_contact.py index 49dbc8a83..9a540e7cd 100644 --- a/plugins/modules/nxos_snmp_contact.py +++ b/plugins/modules/nxos_snmp_contact.py @@ -116,7 +116,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} diff --git a/plugins/modules/nxos_snmp_host.py b/plugins/modules/nxos_snmp_host.py index 5899472e2..b982313fd 100644 --- a/plugins/modules/nxos_snmp_host.py +++ b/plugins/modules/nxos_snmp_host.py @@ -202,7 +202,11 @@ def get_snmp_host(host, udp, module): vrf_filt = each.get("TABLE_vrf_filters") if vrf_filt: - vrf_filter = vrf_filt["ROW_vrf_filters"]["vrf_filter"].split(":")[1].split(",") + vrf_filter = ( + vrf_filt["ROW_vrf_filters"]["vrf_filter"] + .split(":")[1] + .split(",") + ) filters = [vrf.strip() for vrf in vrf_filter] host_resource["vrf_filter"] = filters @@ -219,14 +223,18 @@ def get_snmp_host(host, udp, module): resource_table = [resource_table] for each in resource_table: - key = str(each["address"]) + "_" + str(each["port"]).strip() + key = ( + str(each["address"]) + "_" + str(each["port"]).strip() + ) src = each.get("src_intf") host_resource = apply_key_map(host_map_5k, each) if src: host_resource["src_intf"] = src if re.search(r"interface:", src): - host_resource["src_intf"] = src.split(":")[1].strip() + host_resource["src_intf"] = src.split(":")[ + 1 + ].strip() vrf = each.get("use_vrf_name") if vrf: @@ -234,7 +242,9 @@ def get_snmp_host(host, udp, module): vrf_filt = each.get("TABLE_filter_vrf") if vrf_filt: - vrf_filter = vrf_filt["ROW_filter_vrf"]["filter_vrf_name"].split(",") + vrf_filter = vrf_filt["ROW_filter_vrf"][ + "filter_vrf_name" + ].split(",") filters = [vrf.strip() for vrf in vrf_filter] host_resource["vrf_filter"] = filters @@ -407,7 +417,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} @@ -445,7 +457,10 @@ def main(): module.fail_json(msg="inform requires snmp v2c or v3") if (version == "v1" or version == "v2c") and v3: - module.fail_json(msg='param: "v3" should not be used when ' "using version v1 or v2c") + module.fail_json( + msg='param: "v3" should not be used when ' + "using version v1 or v2c" + ) if not any([vrf_filter, vrf, src_intf]): if not all([snmp_type, version, community, udp]): @@ -494,7 +509,9 @@ def main(): if proposed.get("vrf"): commands.append(remove_vrf(snmp_host, udp, proposed, existing)) if proposed.get("vrf_filter"): - commands.append(remove_filter(snmp_host, udp, proposed, existing)) + commands.append( + remove_filter(snmp_host, udp, proposed, existing) + ) elif state == "present": delta = dict(set(proposed.items()).difference(existing.items())) diff --git a/plugins/modules/nxos_snmp_location.py b/plugins/modules/nxos_snmp_location.py index d7526a9ee..ad4cd1d28 100644 --- a/plugins/modules/nxos_snmp_location.py +++ b/plugins/modules/nxos_snmp_location.py @@ -121,7 +121,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} diff --git a/plugins/modules/nxos_snmp_traps.py b/plugins/modules/nxos_snmp_traps.py index fce1a8a20..27d4dfd9a 100644 --- a/plugins/modules/nxos_snmp_traps.py +++ b/plugins/modules/nxos_snmp_traps.py @@ -177,7 +177,9 @@ def get_snmp_traps(group, module): ] if "all" in group and "N3K-C35" in get_platform_id(module): - module.warn("Platform does not support bfd traps; bfd ignored for 'group: all' request") + module.warn( + "Platform does not support bfd traps; bfd ignored for 'group: all' request" + ) feature_list.remove("bfd") for each in feature_list: @@ -225,13 +227,17 @@ def get_trap_commands(group, state, existing, module): if state == "disabled": for feature in existing: if existing[feature]: - trap_command = "no snmp-server enable traps {0}".format(feature) + trap_command = "no snmp-server enable traps {0}".format( + feature + ) commands.append(trap_command) elif state == "enabled": for feature in existing: if existing[feature] is False: - trap_command = "snmp-server enable traps {0}".format(feature) + trap_command = "snmp-server enable traps {0}".format( + feature + ) commands.append(trap_command) else: @@ -242,11 +248,15 @@ def get_trap_commands(group, state, existing, module): disabled = True if state == "disabled" and enabled: - commands.append(["no snmp-server enable traps {0}".format(group)]) + commands.append( + ["no snmp-server enable traps {0}".format(group)] + ) elif state == "enabled" and disabled: commands.append(["snmp-server enable traps {0}".format(group)]) else: - module.fail_json(msg="{0} is not a currently " "enabled feature.".format(group)) + module.fail_json( + msg="{0} is not a currently " "enabled feature.".format(group) + ) return commands @@ -291,7 +301,9 @@ def main(): ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} diff --git a/plugins/modules/nxos_snmp_user.py b/plugins/modules/nxos_snmp_user.py index a3b0b5fa8..55f099721 100644 --- a/plugins/modules/nxos_snmp_user.py +++ b/plugins/modules/nxos_snmp_user.py @@ -252,7 +252,9 @@ def get_non_structured_snmp_user(body_text): return resource resource["user"] = m.group("user") resource["auth"] = m.group("auth") - resource["encrypt"] = "aes-128" if "aes" in str(m.group("priv")) else "none" + resource["encrypt"] = ( + "aes-128" if "aes" in str(m.group("priv")) else "none" + ) resource["group"] = [m.group("group")] more_groups = re.findall(r"^\s+([\w\d-]+)\s*$", output, re.M) @@ -331,7 +333,8 @@ def main(): if privacy and encrypt: if not pwd and authentication: module.fail_json( - msg="pwd and authentication must be provided " "when using privacy and encrypt", + msg="pwd and authentication must be provided " + "when using privacy and encrypt", ) if group and group not in get_snmp_groups(module): diff --git a/plugins/modules/nxos_system.py b/plugins/modules/nxos_system.py index dafbf9f1f..a405038a5 100644 --- a/plugins/modules/nxos_system.py +++ b/plugins/modules/nxos_system.py @@ -373,7 +373,9 @@ def main(): state=dict(default="present", choices=["present", "absent"]), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_telemetry.py b/plugins/modules/nxos_telemetry.py index 89a58e2d2..0a52db82d 100644 --- a/plugins/modules/nxos_telemetry.py +++ b/plugins/modules/nxos_telemetry.py @@ -327,7 +327,9 @@ def main(): :returns: the result form module invocation """ - module = AnsibleModule(argument_spec=TelemetryArgs.argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=TelemetryArgs.argument_spec, supports_check_mode=True + ) result = Telemetry(module).execute_module() module.exit_json(**result) diff --git a/plugins/modules/nxos_udld.py b/plugins/modules/nxos_udld.py index 83955e151..09921df32 100644 --- a/plugins/modules/nxos_udld.py +++ b/plugins/modules/nxos_udld.py @@ -147,11 +147,17 @@ def get_commands_config_udld_global(delta, reset, existing): commands = [] for param, value in delta.items(): if param == "aggressive": - command = "udld aggressive" if value == "enabled" else "no udld aggressive" + command = ( + "udld aggressive" + if value == "enabled" + else "no udld aggressive" + ) commands.append(command) elif param == "msg_time": if value == "default": - if existing.get("msg_time") != PARAM_TO_DEFAULT_KEYMAP.get("msg_time"): + if existing.get("msg_time") != PARAM_TO_DEFAULT_KEYMAP.get( + "msg_time" + ): commands.append("no udld message-time") else: commands.append("udld message-time " + value) @@ -196,7 +202,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() @@ -220,7 +228,9 @@ def main(): commands = [] if state == "present": if delta: - command = get_commands_config_udld_global(dict(delta), reset, existing) + command = get_commands_config_udld_global( + dict(delta), reset, existing + ) commands.append(command) elif state == "absent": diff --git a/plugins/modules/nxos_udld_interface.py b/plugins/modules/nxos_udld_interface.py index b78ed5c7a..ce48089c2 100644 --- a/plugins/modules/nxos_udld_interface.py +++ b/plugins/modules/nxos_udld_interface.py @@ -143,7 +143,9 @@ def get_udld_interface(module, interface): mode = None mode_str = None try: - body = run_commands(module, [{"command": command, "output": "text"}])[0] + body = run_commands(module, [{"command": command, "output": "text"}])[ + 0 + ] if "aggressive" in body: mode = "aggressive" mode_str = "aggressive" @@ -227,12 +229,16 @@ def get_commands_remove_udld_interface(delta, interface, module, existing): def main(): argument_spec = dict( - mode=dict(choices=["enabled", "disabled", "aggressive"], required=True), + mode=dict( + choices=["enabled", "disabled", "aggressive"], required=True + ), interface=dict(type="str", required=True), state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() @@ -251,7 +257,9 @@ def main(): cmds = [] if state == "present": if delta: - command = get_commands_config_udld_interface1(delta, interface, module, existing) + command = get_commands_config_udld_interface1( + delta, interface, module, existing + ) commands.append(command) cmds = flatten_list(commands) if module.check_mode: @@ -262,7 +270,9 @@ def main(): if delta["mode"] == "enabled" or delta["mode"] == "disabled": commands = [] - command = get_commands_config_udld_interface2(delta, interface, module, existing) + command = get_commands_config_udld_interface2( + delta, interface, module, existing + ) commands.append(command) cmds = flatten_list(commands) if module.check_mode: @@ -273,7 +283,9 @@ def main(): else: common = set(proposed.items()).intersection(existing.items()) if common: - command = get_commands_remove_udld_interface(dict(common), interface, module, existing) + command = get_commands_remove_udld_interface( + dict(common), interface, module, existing + ) cmds = flatten_list(commands) if module.check_mode: module.exit_json(changed=True, commands=cmds) diff --git a/plugins/modules/nxos_user.py b/plugins/modules/nxos_user.py index d3e847359..aff3269d2 100644 --- a/plugins/modules/nxos_user.py +++ b/plugins/modules/nxos_user.py @@ -320,7 +320,9 @@ def parse_roles(data): def map_config_to_obj(module): - out = run_commands(module, [{"command": "show user-account", "output": "json"}]) + out = run_commands( + module, [{"command": "show user-account", "output": "json"}] + ) data = out[0] objects = list() @@ -418,7 +420,9 @@ def main(): name=dict(), configured_password=dict(no_log=True), hashed_password=dict(no_log=True), - update_password=dict(default="always", choices=["on_create", "always"]), + update_password=dict( + default="always", choices=["on_create", "always"] + ), roles=dict(type="list", aliases=["role"], elements="str"), sshkey=dict(no_log=False), state=dict(default="present", choices=["present", "absent"]), @@ -441,7 +445,10 @@ def main(): argument_spec.update(element_spec) - mutually_exclusive = [("name", "aggregate"), ("configured_password", "hashed_password")] + mutually_exclusive = [ + ("name", "aggregate"), + ("configured_password", "hashed_password"), + ] module = AnsibleModule( argument_spec=argument_spec, @@ -473,7 +480,9 @@ def main(): # check if provided hashed password is infact a hash if module.params["hashed_password"] is not None: - if not re.match(r"^\$5\$......\$.*$", module.params["hashed_password"]): + if not re.match( + r"^\$5\$......\$.*$", module.params["hashed_password"] + ): module.fail_json(msg="Provided hash is not valid") if commands: @@ -484,7 +493,11 @@ def main(): module.fail_json(msg=resp) else: result["warnings"].extend( - [x[9:] for x in resp.splitlines() if x.startswith("WARNING: ")], + [ + x[9:] + for x in resp.splitlines() + if x.startswith("WARNING: ") + ], ) result["changed"] = True diff --git a/plugins/modules/nxos_vlans.py b/plugins/modules/nxos_vlans.py index 4116f524b..958dead17 100644 --- a/plugins/modules/nxos_vlans.py +++ b/plugins/modules/nxos_vlans.py @@ -429,7 +429,9 @@ def main(): :returns: the result form module invocation """ - module = AnsibleModule(argument_spec=VlansArgs.argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=VlansArgs.argument_spec, supports_check_mode=True + ) result = Vlans(module).execute_module() module.exit_json(**result) diff --git a/plugins/modules/nxos_vpc.py b/plugins/modules/nxos_vpc.py index f660efc10..8d81d8e93 100644 --- a/plugins/modules/nxos_vpc.py +++ b/plugins/modules/nxos_vpc.py @@ -388,7 +388,9 @@ def main(): auto_recovery = module.params["auto_recovery"] auto_recovery_reload_delay = module.params["auto_recovery_reload_delay"] delay_restore = module.params["delay_restore"] - delay_restore_interface_vlan = module.params["delay_restore_interface_vlan"] + delay_restore_interface_vlan = module.params[ + "delay_restore_interface_vlan" + ] delay_restore_orphan_port = module.params["delay_restore_orphan_port"] state = module.params["state"] @@ -409,15 +411,20 @@ def main(): if not pkl_dest: if pkl_src: - module.fail_json(msg="dest IP for peer-keepalive is required" " when src IP is present") + module.fail_json( + msg="dest IP for peer-keepalive is required" + " when src IP is present" + ) elif pkl_vrf: if pkl_vrf != "management": module.fail_json( - msg="dest and src IP for peer-keepalive are required" " when vrf is present", + msg="dest and src IP for peer-keepalive are required" + " when vrf is present", ) else: module.fail_json( - msg="dest IP for peer-keepalive is required" " when vrf is present", + msg="dest IP for peer-keepalive is required" + " when vrf is present", ) if pkl_vrf: if pkl_vrf.lower() not in get_vrf_list(module): @@ -441,13 +448,16 @@ def main(): if delta: pkl_dependencies(module, delta, existing) - command = get_commands_to_config_vpc(module, delta, domain, existing) + command = get_commands_to_config_vpc( + module, delta, domain, existing + ) commands.append(command) elif state == "absent": if existing: if domain != existing["domain"]: module.fail_json( - msg="You are trying to remove a domain that " "does not exist on the device", + msg="You are trying to remove a domain that " + "does not exist on the device", ) else: commands.append("terminal dont-ask") diff --git a/plugins/modules/nxos_vpc_interface.py b/plugins/modules/nxos_vpc_interface.py index 5e3184578..de4d0b92a 100644 --- a/plugins/modules/nxos_vpc_interface.py +++ b/plugins/modules/nxos_vpc_interface.py @@ -197,7 +197,9 @@ def get_portchannel_vpc_config(module, portchannel): return config -def get_commands_to_config_vpc_interface(portchannel, delta, config_value, existing): +def get_commands_to_config_vpc_interface( + portchannel, delta, config_value, existing +): commands = [] if not delta.get("peer-link") and existing.get("peer-link"): @@ -219,7 +221,9 @@ def get_commands_to_config_vpc_interface(portchannel, delta, config_value, exist def state_present(portchannel, delta, config_value, existing): commands = [] - command = get_commands_to_config_vpc_interface(portchannel, delta, config_value, existing) + command = get_commands_to_config_vpc_interface( + portchannel, delta, config_value, existing + ) commands.append(command) return commands @@ -266,7 +270,9 @@ def main(): active_peer_link = None if portchannel not in get_portchannel_list(module): - if not portchannel.isdigit() or int(portchannel) not in get_portchannel_list(module): + if not portchannel.isdigit() or int( + portchannel + ) not in get_portchannel_list(module): module.fail_json( msg="The portchannel you are trying to make a" " VPC or PL is not created yet. " @@ -308,7 +314,8 @@ def main(): if active_peer_link != portchannel: if peer_link: module.fail_json( - msg="A peer link already exists on" " the device. Remove it first", + msg="A peer link already exists on" + " the device. Remove it first", current_peer_link="Po{0}".format(active_peer_link), ) config_value = "peer-link" @@ -319,7 +326,9 @@ def main(): if state == "present": delta = dict(set(proposed.items()).difference(existing.items())) if delta: - commands = state_present(portchannel, delta, config_value, existing) + commands = state_present( + portchannel, delta, config_value, existing + ) elif state == "absent" and existing: commands = state_absent(portchannel, existing) diff --git a/plugins/modules/nxos_vrf.py b/plugins/modules/nxos_vrf.py index 6017d3c88..6b0e158b7 100644 --- a/plugins/modules/nxos_vrf.py +++ b/plugins/modules/nxos_vrf.py @@ -339,8 +339,12 @@ def map_obj_to_commands(updates, module): else: # If vni is already configured on vrf, unconfigure it first. if vni: - if obj_in_have.get("vni") and vni != obj_in_have.get("vni"): - commands.append("no vni {0}".format(obj_in_have.get("vni"))) + if obj_in_have.get("vni") and vni != obj_in_have.get( + "vni" + ): + commands.append( + "no vni {0}".format(obj_in_have.get("vni")) + ) for item in args: candidate = w.get(item) @@ -351,7 +355,9 @@ def map_obj_to_commands(updates, module): elif candidate and candidate != obj_in_have.get(item): cmd = item + " " + str(candidate) commands.append(cmd) - if admin_state and admin_state != obj_in_have.get("admin_state"): + if admin_state and admin_state != obj_in_have.get( + "admin_state" + ): if admin_state == "up": commands.append("no shutdown") elif admin_state == "down": @@ -435,7 +441,9 @@ def validate_vrf(name, module): if name == "default": module.fail_json(msg="cannot use default as name of a VRF") elif len(name) > 32: - module.fail_json(msg="VRF name exceeded max length of 32", name=name) + module.fail_json( + msg="VRF name exceeded max length of 32", name=name + ) else: return name @@ -462,7 +470,9 @@ def map_params_to_obj(module): "admin_state": module.params["admin_state"], "state": module.params["state"], "interfaces": module.params["interfaces"], - "associated_interfaces": module.params["associated_interfaces"], + "associated_interfaces": module.params[ + "associated_interfaces" + ], }, ) return obj @@ -544,7 +554,8 @@ def check_declarative_intent_params(want, module, element_spec, result): interfaces = obj_in_have.get("interfaces") if interfaces is not None and i not in interfaces: module.fail_json( - msg="Interface %s not configured on vrf %s" % (i, w["name"]), + msg="Interface %s not configured on vrf %s" + % (i, w["name"]), ) @@ -554,9 +565,13 @@ def vrf_error_check(module, commands, responses): if re.search(pattern, str(responses)): # Allow delay/retry for VRF changes time.sleep(15) - responses = load_config(module, commands, opts={"catch_clierror": True}) + responses = load_config( + module, commands, opts={"catch_clierror": True} + ) if re.search(pattern, str(responses)): - module.fail_json(msg="VRF config (and retry) failure: %s " % responses) + module.fail_json( + msg="VRF config (and retry) failure: %s " % responses + ) module.warn("VRF config delayed by VRF deletion - passed on retry") @@ -571,7 +586,9 @@ def main(): interfaces=dict(type="list", elements="str"), associated_interfaces=dict(type="list", elements="str"), delay=dict(type="int", default=10), - state=dict(type="str", default="present", choices=["present", "absent"]), + state=dict( + type="str", default="present", choices=["present", "absent"] + ), ) aggregate_spec = deepcopy(element_spec) @@ -607,7 +624,9 @@ def main(): result["commands"] = commands if commands and not module.check_mode: - responses = load_config(module, commands, opts={"catch_clierror": True}) + responses = load_config( + module, commands, opts={"catch_clierror": True} + ) vrf_error_check(module, commands, responses) result["changed"] = True diff --git a/plugins/modules/nxos_vrf_af.py b/plugins/modules/nxos_vrf_af.py index 5bd043706..713bb5d24 100644 --- a/plugins/modules/nxos_vrf_af.py +++ b/plugins/modules/nxos_vrf_af.py @@ -192,13 +192,17 @@ def main(): elements="dict", options=dict( rt=dict(type="str", required=True), - direction=dict(choices=["import", "export", "both"], default="both"), + direction=dict( + choices=["import", "export", "both"], default="both" + ), state=dict(choices=["present", "absent"], default="present"), ), ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() @@ -239,9 +243,13 @@ def main(): if module.params["route_targets"] is not None: for rt in module.params["route_targets"]: if rt.get("direction") == "both" or not rt.get("direction"): - platform = get_capabilities(module)["device_info"]["network_os_platform"] + platform = get_capabilities(module)["device_info"][ + "network_os_platform" + ] if platform.startswith("N9K") and rt.get("rt") == "auto": - rt_commands = match_current_rt(rt, "both", current, rt_commands) + rt_commands = match_current_rt( + rt, "both", current, rt_commands + ) else: rt_commands = match_current_rt( rt, @@ -267,7 +275,9 @@ def main(): commands.extend(rt_commands) if commands and current: - commands.insert(0, "address-family %s unicast" % module.params["afi"]) + commands.insert( + 0, "address-family %s unicast" % module.params["afi"] + ) if commands: commands.insert(0, "vrf context %s" % module.params["vrf"]) diff --git a/plugins/modules/nxos_vrf_interface.py b/plugins/modules/nxos_vrf_interface.py index 9e9a0cef2..59b09ccec 100644 --- a/plugins/modules/nxos_vrf_interface.py +++ b/plugins/modules/nxos_vrf_interface.py @@ -181,10 +181,14 @@ def main(): argument_spec = dict( vrf=dict(required=True), interface=dict(type="str", required=True), - state=dict(default="present", choices=["present", "absent"], required=False), + state=dict( + default="present", choices=["present", "absent"], required=False + ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} @@ -198,7 +202,9 @@ def main(): current_vrfs = get_vrf_list(module) if vrf not in current_vrfs: - warnings.append("The VRF is not present/active on the device. Use nxos_vrf to fix this.") + warnings.append( + "The VRF is not present/active on the device. Use nxos_vrf to fix this." + ) intf_type = get_interface_type(interface) if intf_type != "ethernet" and network_api == "cliconf": diff --git a/plugins/modules/nxos_vrrp.py b/plugins/modules/nxos_vrrp.py index b5a026c4b..ce3608d4f 100644 --- a/plugins/modules/nxos_vrrp.py +++ b/plugins/modules/nxos_vrrp.py @@ -327,7 +327,8 @@ def validate_params(param, module): raise ValueError except ValueError: module.fail_json( - msg="Warning! 'priority' must be an integer " "between 1 and 254", + msg="Warning! 'priority' must be an integer " + "between 1 and 254", priority=value, ) @@ -347,9 +348,13 @@ def main(): default="shutdown", ), authentication=dict(required=False, type="str", no_log=True), - state=dict(choices=["absent", "present"], required=False, default="present"), + state=dict( + choices=["absent", "present"], required=False, default="present" + ), + ) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = {"changed": False, "commands": [], "warnings": warnings} @@ -386,7 +391,8 @@ def main(): mode, name = get_interface_mode(interface, intf_type, module) if mode == "layer2": module.fail_json( - msg="That interface is a layer2 port.\nMake it " "a layer 3 port first.", + msg="That interface is a layer2 port.\nMake it " + "a layer 3 port first.", interface=interface, ) diff --git a/plugins/modules/nxos_vsan.py b/plugins/modules/nxos_vsan.py index 70f9b50ee..60e1f8646 100644 --- a/plugins/modules/nxos_vsan.py +++ b/plugins/modules/nxos_vsan.py @@ -202,7 +202,9 @@ def main(): vsan=dict(type="list", elements="dict", options=vsan_element_spec), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() messages = list() commands_executed = list() @@ -223,7 +225,8 @@ def main(): if int(vsanid) < 1 or int(vsanid) >= 4095: module.fail_json( - msg=vsanid + " - This is an invalid vsan. Supported vsan range is 1-4094", + msg=vsanid + + " - This is an invalid vsan. Supported vsan range is 1-4094", ) if vsanid in dictSwVsanObjs.keys(): @@ -241,7 +244,8 @@ def main(): # Negative case: if vsanid == "4079" or vsanid == "4094": messages.append( - str(vsanid) + " is a reserved vsan, hence cannot be removed", + str(vsanid) + + " is a reserved vsan, hence cannot be removed", ) continue if vsanid == sw_vsanid: @@ -258,7 +262,8 @@ def main(): # Negative case: if vsanid == "4079" or vsanid == "4094": messages.append( - str(vsanid) + " is a reserved vsan, and always present on the switch", + str(vsanid) + + " is a reserved vsan, and always present on the switch", ) else: if vsanid == sw_vsanid: @@ -287,16 +292,22 @@ def main(): + " Hence there is nothing to configure", ) else: - commands.append("vsan " + str(vsanid) + " name " + vsanname) + commands.append( + "vsan " + str(vsanid) + " name " + vsanname + ) messages.append( - "setting vsan name to " + vsanname + " for vsan " + str(vsanid), + "setting vsan name to " + + vsanname + + " for vsan " + + str(vsanid), ) if vsansuspend: # Negative case: if vsanid == "4079" or vsanid == "4094": messages.append( - str(vsanid) + " is a reserved vsan, and cannot be suspended", + str(vsanid) + + " is a reserved vsan, and cannot be suspended", ) else: if sw_vsanstate == "suspended": @@ -333,14 +344,25 @@ def main(): ) else: commands.append( - "vsan " + str(vsanid) + " interface " + each_interface_name, + "vsan " + + str(vsanid) + + " interface " + + each_interface_name, ) messages.append( - "adding interface " + each_interface_name + " to vsan " + str(vsanid), + "adding interface " + + each_interface_name + + " to vsan " + + str(vsanid), ) if len(commands) != 0: - commands = ["terminal dont-ask"] + ["vsan database"] + commands + ["no terminal dont-ask"] + commands = ( + ["terminal dont-ask"] + + ["vsan database"] + + commands + + ["no terminal dont-ask"] + ) cmds = flatten_list(commands) commands_executed = cmds diff --git a/plugins/modules/nxos_vtp_domain.py b/plugins/modules/nxos_vtp_domain.py index d1e3c39fd..6f25968f4 100644 --- a/plugins/modules/nxos_vtp_domain.py +++ b/plugins/modules/nxos_vtp_domain.py @@ -170,7 +170,9 @@ def get_vtp_password(module): def main(): argument_spec = dict(domain=dict(type="str", required=True)) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_vtp_password.py b/plugins/modules/nxos_vtp_password.py index c6e9cabdb..846edfb44 100644 --- a/plugins/modules/nxos_vtp_password.py +++ b/plugins/modules/nxos_vtp_password.py @@ -200,7 +200,9 @@ def main(): state=dict(choices=["absent", "present"], default="present"), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() @@ -238,7 +240,10 @@ def main(): ) else: if not existing.get("domain"): - module.fail_json(msg="Cannot remove a vtp password " "before vtp domain is set.") + module.fail_json( + msg="Cannot remove a vtp password " + "before vtp domain is set." + ) elif existing["vtp_password"] != ("\\"): commands.append(["no vtp password"]) @@ -246,7 +251,9 @@ def main(): elif state == "present": if delta: if not existing.get("domain"): - module.fail_json(msg="Cannot set vtp password " "before vtp domain is set.") + module.fail_json( + msg="Cannot set vtp password " "before vtp domain is set." + ) else: commands.append(["vtp password {0}".format(vtp_password)]) diff --git a/plugins/modules/nxos_vtp_version.py b/plugins/modules/nxos_vtp_version.py index a98bff904..c981d3dc0 100644 --- a/plugins/modules/nxos_vtp_version.py +++ b/plugins/modules/nxos_vtp_version.py @@ -161,9 +161,13 @@ def get_vtp_password(module): def main(): - argument_spec = dict(version=dict(type="str", choices=["1", "2", "3"], required=True)) + argument_spec = dict( + version=dict(type="str", choices=["1", "2", "3"], required=True) + ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() diff --git a/plugins/modules/nxos_vxlan_vtep.py b/plugins/modules/nxos_vxlan_vtep.py index f62b995c0..86ae45f22 100644 --- a/plugins/modules/nxos_vxlan_vtep.py +++ b/plugins/modules/nxos_vxlan_vtep.py @@ -177,8 +177,12 @@ def get_value(arg, config, module): if arg in BOOL_PARAMS: - REGEX = re.compile(r"\s+{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M) - NO_REGEX = re.compile(r"\s+no\s{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M) + REGEX = re.compile( + r"\s+{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M + ) + NO_REGEX = re.compile( + r"\s+no\s{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M + ) NO_SHUT_REGEX = re.compile(r"\s+no shutdown\s*$", re.M) value = False if arg == "shutdown": @@ -208,7 +212,9 @@ def get_value(arg, config, module): r"(?:{0}\s)(?P.*)$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M, ) - NO_DESC_REGEX = re.compile(r"\s+{0}\s*$".format("no description"), re.M) + NO_DESC_REGEX = re.compile( + r"\s+{0}\s*$".format("no description"), re.M + ) SOURCE_INTF_REGEX = re.compile( r"(?:{0}\s)(?P\S+)$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M, @@ -223,7 +229,11 @@ def get_value(arg, config, module): for line in config.splitlines(): try: if PARAM_TO_COMMAND_KEYMAP[arg] in config: - value = SOURCE_INTF_REGEX.search(config).group("value").strip() + value = ( + SOURCE_INTF_REGEX.search(config) + .group("value") + .strip() + ) break except AttributeError: value = "" @@ -247,7 +257,11 @@ def get_value(arg, config, module): for line in config.splitlines(): try: if PARAM_TO_COMMAND_KEYMAP[arg] in config: - value = SOURCE_INTF_REGEX.search(config).group("value").strip() + value = ( + SOURCE_INTF_REGEX.search(config) + .group("value") + .strip() + ) break except AttributeError: value = "" @@ -259,9 +273,13 @@ def get_value(arg, config, module): def get_existing(module, args): existing = {} - netcfg = CustomNetworkConfig(indent=2, contents=get_config(module, flags=["all"])) + netcfg = CustomNetworkConfig( + indent=2, contents=get_config(module, flags=["all"]) + ) - interface_string = "interface {0}".format(module.params["interface"].lower()) + interface_string = "interface {0}".format( + module.params["interface"].lower() + ) parents = [interface_string] config = netcfg.get_section(parents) @@ -337,7 +355,9 @@ def gsa_tcam_check(module): This method checks the current TCAM allocation. Note that changing tcam_size requires a switch reboot to take effect. """ - cmds = [{"command": "show hardware access-list tcam region", "output": "json"}] + cmds = [ + {"command": "show hardware access-list tcam region", "output": "json"} + ] body = run_commands(module, cmds) if body: tcam_region = body[0]["TCAM_Region"]["TABLE_Sizes"]["ROW_Sizes"] @@ -345,7 +365,8 @@ def gsa_tcam_check(module): [ i for i in tcam_region - if i["type"].startswith("Ingress ARP-Ether ACL") and i["tcam_size"] == "0" + if i["type"].startswith("Ingress ARP-Ether ACL") + and i["tcam_size"] == "0" ], ): msg = ( @@ -392,7 +413,9 @@ def state_present(module, existing, proposed, candidate): candidate.add(commands, parents=parents) else: if not existing and module.params["interface"]: - commands = ["interface {0}".format(module.params["interface"].lower())] + commands = [ + "interface {0}".format(module.params["interface"].lower()) + ] candidate.add(commands, parents=[]) @@ -413,12 +436,16 @@ def main(): shutdown=dict(required=False, type="bool"), source_interface=dict(required=False, type="str"), source_interface_hold_down_time=dict(required=False, type="str"), - state=dict(choices=["present", "absent"], default="present", required=False), + state=dict( + choices=["present", "absent"], default="present", required=False + ), multisite_border_gateway_interface=dict(required=False, type="str"), advertise_virtual_rmac=dict(required=False, type="bool"), ) - mutually_exclusive = [("global_ingress_replication_bgp", "global_mcast_group_L2")] + mutually_exclusive = [ + ("global_ingress_replication_bgp", "global_mcast_group_L2") + ] module = AnsibleModule( argument_spec=argument_spec, @@ -434,7 +461,9 @@ def main(): args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) - proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed_args = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) proposed = {} for key, value in proposed_args.items(): if key != "interface": diff --git a/plugins/modules/nxos_vxlan_vtep_vni.py b/plugins/modules/nxos_vxlan_vtep_vni.py index d58bd6c95..0dd65c6e7 100644 --- a/plugins/modules/nxos_vxlan_vtep_vni.py +++ b/plugins/modules/nxos_vxlan_vtep_vni.py @@ -147,7 +147,9 @@ def get_value(arg, config, module): command = PARAM_TO_COMMAND_KEYMAP[arg] - command_val_re = re.compile(r"(?:{0}\s)(?P.*)$".format(command), re.M) + command_val_re = re.compile( + r"(?:{0}\s)(?P.*)$".format(command), re.M + ) if arg in BOOL_PARAMS: command_re = re.compile(r"\s+{0}\s*$".format(command), re.M) @@ -195,8 +197,13 @@ def get_existing(module, args): parents = ["interface {0}".format(interface_exist)] temp_config = netcfg.get_section(parents) - if "member vni {0} associate-vrf".format(module.params["vni"]) in temp_config: - parents.append("member vni {0} associate-vrf".format(module.params["vni"])) + if ( + "member vni {0} associate-vrf".format(module.params["vni"]) + in temp_config + ): + parents.append( + "member vni {0} associate-vrf".format(module.params["vni"]) + ) config = netcfg.get_section(parents) elif "member vni {0}".format(module.params["vni"]) in temp_config: parents.append("member vni {0}".format(module.params["vni"])) @@ -244,12 +251,19 @@ def state_present(module, existing, proposed, candidate): vni_command = "member vni {0}".format(module.params["vni"]) if vni_command not in commands: commands.append("member vni {0}".format(module.params["vni"])) - if value != PARAM_TO_DEFAULT_KEYMAP.get("multicast_group", "default"): + if value != PARAM_TO_DEFAULT_KEYMAP.get( + "multicast_group", "default" + ): commands.append("{0} {1}".format(key, value)) - elif key == "ingress-replication protocol" and value != existing_commands.get(key): + elif ( + key == "ingress-replication protocol" + and value != existing_commands.get(key) + ): evalue = existing_commands.get(key) - dvalue = PARAM_TO_DEFAULT_KEYMAP.get("ingress_replication", "default") + dvalue = PARAM_TO_DEFAULT_KEYMAP.get( + "ingress_replication", "default" + ) if value != dvalue: if evalue and evalue != dvalue: commands.append("no {0} {1}".format(key, evalue)) @@ -273,7 +287,10 @@ def state_present(module, existing, proposed, candidate): else: if key.replace(" ", "_").replace("-", "_") in BOOL_PARAMS: commands.append("no {0}".format(key.lower())) - elif key == "multisite ingress-replication" and value != existing_commands.get(key): + elif ( + key == "multisite ingress-replication" + and value != existing_commands.get(key) + ): vni_command = "member vni {0}".format(module.params["vni"]) if vni_command not in commands: commands.append("member vni {0}".format(module.params["vni"])) @@ -294,7 +311,9 @@ def state_present(module, existing, proposed, candidate): vni_command = "member vni {0}".format(module.params["vni"]) ingress_replications_command = "ingress-replication protocol static" ingress_replicationb_command = "ingress-replication protocol bgp" - ingress_replicationns_command = "no ingress-replication protocol static" + ingress_replicationns_command = ( + "no ingress-replication protocol static" + ) ingress_replicationnb_command = "no ingress-replication protocol bgp" interface_command = "interface {0}".format(module.params["interface"]) @@ -333,7 +352,9 @@ def state_present(module, existing, proposed, candidate): def state_absent(module, existing, proposed, candidate): if existing["assoc_vrf"]: - commands = ["no member vni {0} associate-vrf".format(module.params["vni"])] + commands = [ + "no member vni {0} associate-vrf".format(module.params["vni"]) + ] else: commands = ["no member vni {0}".format(module.params["vni"])] parents = ["interface {0}".format(module.params["interface"])] @@ -349,8 +370,12 @@ def main(): peer_list=dict(required=False, type="list", elements="str"), suppress_arp=dict(required=False, type="bool"), suppress_arp_disable=dict(required=False, type="bool"), - ingress_replication=dict(required=False, type="str", choices=["bgp", "static", "default"]), - state=dict(choices=["present", "absent"], default="present", required=False), + ingress_replication=dict( + required=False, type="str", choices=["bgp", "static", "default"] + ), + state=dict( + choices=["present", "absent"], default="present", required=False + ), multisite_ingress_replication=dict( required=False, type="str", @@ -380,7 +405,8 @@ def main(): and module.params["ingress_replication"] != "static" ): module.fail_json( - msg="ingress_replication=static is required " "when using peer_list param", + msg="ingress_replication=static is required " + "when using peer_list param", ) else: peer_list = module.params["peer_list"] @@ -410,7 +436,9 @@ def main(): msg="The proposed NVE interface does not exist. Use nxos_interface to create it first.", ) elif interface_exist != module.params["interface"]: - module.fail_json(msg="Only 1 NVE interface is allowed on the switch.") + module.fail_json( + msg="Only 1 NVE interface is allowed on the switch." + ) elif state == "absent": if interface_exist != module.params["interface"]: module.exit_json(**result) @@ -422,7 +450,9 @@ def main(): existing_vni=existing["vni"], ) - proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) + proposed_args = dict( + (k, v) for k, v in module.params.items() if v is not None and k in args + ) proposed = {} for key, value in proposed_args.items(): diff --git a/plugins/modules/nxos_zone_zoneset.py b/plugins/modules/nxos_zone_zoneset.py index 5d519150f..b19b67fd7 100644 --- a/plugins/modules/nxos_zone_zoneset.py +++ b/plugins/modules/nxos_zone_zoneset.py @@ -240,7 +240,9 @@ def __init__(self, module, vsan): self.parseCmdOutput() def execute_show_zoneset_active_cmd(self): - command = "show zoneset active vsan " + str(self.vsan) + " | grep zoneset" + command = ( + "show zoneset active vsan " + str(self.vsan) + " | grep zoneset" + ) output = execute_show_command(command, self.module)[0] return output @@ -461,7 +463,9 @@ def main(): zoneset_spec = dict( name=dict(type="str", required=True), - members=dict(type="list", elements="dict", options=zoneset_member_spec), + members=dict( + type="list", elements="dict", options=zoneset_member_spec + ), remove=dict(type="bool", default=False), action=dict(type="str", choices=["activate", "deactivate"]), ) @@ -483,7 +487,9 @@ def main(): ), ) - module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) warnings = list() messages = list() @@ -513,7 +519,9 @@ def main(): if shZoneStatusObj.isVsanAbsent(): module.fail_json( - msg="Vsan " + str(vsan) + " is not present in the switch. Hence cannot procced.", + msg="Vsan " + + str(vsan) + + " is not present in the switch. Hence cannot procced.", ) if shZoneStatusObj.isLocked(): @@ -554,13 +562,17 @@ def main(): if op_mode is not None: if op_mode != sw_mode: if op_mode == "enhanced": - commands_executed.append("zone mode enhanced vsan " + str(vsan)) + commands_executed.append( + "zone mode enhanced vsan " + str(vsan) + ) messages.append( "zone mode configuration changed from basic to enhanced for vsan " + str(vsan), ) else: - commands_executed.append("no zone mode enhanced vsan " + str(vsan)) + commands_executed.append( + "no zone mode enhanced vsan " + str(vsan) + ) messages.append( "zone mode configuration changed from enhanced to basic for vsan " + str(vsan), @@ -580,12 +592,16 @@ def main(): commands_executed.append( "zone smart-zoning enable vsan " + str(vsan), ) - messages.append("smart-zoning enabled for vsan " + str(vsan)) + messages.append( + "smart-zoning enabled for vsan " + str(vsan) + ) else: commands_executed.append( "no zone smart-zoning enable vsan " + str(vsan), ) - messages.append("smart-zoning disabled for vsan " + str(vsan)) + messages.append( + "smart-zoning disabled for vsan " + str(vsan) + ) else: messages.append( "smart-zoning is already set to " @@ -606,7 +622,10 @@ def main(): if removeflag: if shZoneObj.isZonePresent(zname): messages.append( - "zone '" + zname + "' is removed from vsan " + str(vsan), + "zone '" + + zname + + "' is removed from vsan " + + str(vsan), ) commands_executed.append( "no zone name " + zname + " vsan " + str(vsan), @@ -623,29 +642,46 @@ def main(): if zmembers is None: if shZoneObj.isZonePresent(zname): messages.append( - "zone '" + zname + "' is already present in vsan " + str(vsan), + "zone '" + + zname + + "' is already present in vsan " + + str(vsan), ) else: commands_executed.append( "zone name " + zname + " vsan " + str(vsan), ) messages.append( - "zone '" + zname + "' is created in vsan " + str(vsan), + "zone '" + + zname + + "' is created in vsan " + + str(vsan), ) else: cmdmemlist = [] for eachmem in zmembers: - memtype = getMemType(supported_choices, eachmem.keys()) - cmd = memtype.replace("_", "-") + " " + eachmem[memtype] + memtype = getMemType( + supported_choices, eachmem.keys() + ) + cmd = ( + memtype.replace("_", "-") + + " " + + eachmem[memtype] + ) if op_smart_zoning or sw_smart_zoning_bool: if eachmem["devtype"] is not None: cmd = cmd + " " + eachmem["devtype"] if eachmem["remove"]: if shZoneObj.isZonePresent(zname): - if shZoneObj.isZoneMemberPresent(zname, cmd): + if shZoneObj.isZoneMemberPresent( + zname, cmd + ): cmd = "no member " + cmd cmdmemlist.append(cmd) - if op_smart_zoning and eachmem["devtype"] is not None: + if ( + op_smart_zoning + and eachmem["devtype"] is not None + ): messages.append( "removing zone member '" + eachmem[memtype] @@ -666,7 +702,10 @@ def main(): + str(vsan), ) else: - if op_smart_zoning and eachmem["devtype"] is not None: + if ( + op_smart_zoning + and eachmem["devtype"] is not None + ): messages.append( "zone member '" + eachmem[memtype] @@ -699,7 +738,10 @@ def main(): else: if shZoneObj.isZoneMemberPresent(zname, cmd): - if op_smart_zoning and eachmem["devtype"] is not None: + if ( + op_smart_zoning + and eachmem["devtype"] is not None + ): messages.append( "zone member '" + eachmem[memtype] @@ -724,7 +766,10 @@ def main(): else: cmd = "member " + cmd cmdmemlist.append(cmd) - if op_smart_zoning and eachmem["devtype"] is not None: + if ( + op_smart_zoning + and eachmem["devtype"] is not None + ): messages.append( "adding zone member '" + eachmem[memtype] @@ -764,10 +809,16 @@ def main(): if removeflag: if shZonesetObj.isZonesetPresent(zsetname): messages.append( - "zoneset '" + zsetname + "' is removed from vsan " + str(vsan), + "zoneset '" + + zsetname + + "' is removed from vsan " + + str(vsan), ) commands_executed.append( - "no zoneset name " + zsetname + " vsan " + str(vsan), + "no zoneset name " + + zsetname + + " vsan " + + str(vsan), ) else: messages.append( @@ -835,7 +886,10 @@ def main(): ) if len(cmdmemlist) != 0: commands_executed.append( - "zoneset name " + zsetname + " vsan " + str(vsan), + "zoneset name " + + zsetname + + " vsan " + + str(vsan), ) commands_executed = commands_executed + cmdmemlist else: @@ -848,20 +902,32 @@ def main(): ) else: commands_executed.append( - "zoneset name " + zsetname + " vsan " + str(vsan), + "zoneset name " + + zsetname + + " vsan " + + str(vsan), ) messages.append( - "zoneset '" + zsetname + "' is created in vsan " + str(vsan), + "zoneset '" + + zsetname + + "' is created in vsan " + + str(vsan), ) # Process zoneset activate options if actionflag == "deactivate": if shZonesetActiveObj.isZonesetActive(zsetname): messages.append( - "deactivating zoneset '" + zsetname + "' in vsan " + str(vsan), + "deactivating zoneset '" + + zsetname + + "' in vsan " + + str(vsan), ) dactcmd.append( - "no zoneset activate name " + zsetname + " vsan " + str(vsan), + "no zoneset activate name " + + zsetname + + " vsan " + + str(vsan), ) else: messages.append( @@ -874,10 +940,16 @@ def main(): elif actionflag == "activate": if commands_executed: messages.append( - "activating zoneset '" + zsetname + "' in vsan " + str(vsan), + "activating zoneset '" + + zsetname + + "' in vsan " + + str(vsan), ) actcmd.append( - "zoneset activate name " + zsetname + " vsan " + str(vsan), + "zoneset activate name " + + zsetname + + " vsan " + + str(vsan), ) else: messages.append( @@ -897,7 +969,11 @@ def main(): commands_executed.append("zone commit vsan " + str(vsan)) if commands_executed: - commands_executed = ["terminal dont-ask"] + commands_executed + ["no terminal dont-ask"] + commands_executed = ( + ["terminal dont-ask"] + + commands_executed + + ["no terminal dont-ask"] + ) cmds = flatten_list(commands_executed) if cmds: diff --git a/plugins/netconf/nxos.py b/plugins/netconf/nxos.py index fcbee7952..f6c46b7b0 100644 --- a/plugins/netconf/nxos.py +++ b/plugins/netconf/nxos.py @@ -39,7 +39,9 @@ """ from ansible.plugins.netconf import NetconfBase -from ansible_collections.ansible.netcommon.plugins.plugin_utils.netconf_base import NetconfBase +from ansible_collections.ansible.netcommon.plugins.plugin_utils.netconf_base import ( + NetconfBase, +) class Netconf(NetconfBase): diff --git a/plugins/terminal/nxos.py b/plugins/terminal/nxos.py index 0df2956fb..e8be13977 100644 --- a/plugins/terminal/nxos.py +++ b/plugins/terminal/nxos.py @@ -26,7 +26,9 @@ from ansible.errors import AnsibleConnectionFailure from ansible.module_utils._text import to_bytes, to_text -from ansible_collections.ansible.netcommon.plugins.plugin_utils.terminal_base import TerminalBase +from ansible_collections.ansible.netcommon.plugins.plugin_utils.terminal_base import ( + TerminalBase, +) class TerminalModule(TerminalBase): @@ -56,7 +58,9 @@ class TerminalModule(TerminalBase): rb"[B|b]aud rate of console should be.* (\d*) to increase [a-z]* level", re.I, ), - re.compile(rb"cannot apply non-existing acl policy to interface", re.I), + re.compile( + rb"cannot apply non-existing acl policy to interface", re.I + ), re.compile(rb"Duplicate sequence number", re.I), re.compile( rb"Cannot apply ACL to an interface that is a port-channel member", @@ -87,16 +91,21 @@ def on_become(self, passwd=None): cmd = {"command": "enable"} if passwd: - cmd["prompt"] = to_text(r"(?i)[\r\n]?Password: $", errors="surrogate_or_strict") + cmd["prompt"] = to_text( + r"(?i)[\r\n]?Password: $", errors="surrogate_or_strict" + ) cmd["answer"] = passwd cmd["prompt_retry_check"] = True try: - self._exec_cli_command(to_bytes(json.dumps(cmd), errors="surrogate_or_strict")) + self._exec_cli_command( + to_bytes(json.dumps(cmd), errors="surrogate_or_strict") + ) prompt = self._get_prompt() if prompt is None or not prompt.strip().endswith(b"enable#"): raise AnsibleConnectionFailure( - "failed to elevate privilege to enable mode still at prompt [%s]" % prompt, + "failed to elevate privilege to enable mode still at prompt [%s]" + % prompt, ) except AnsibleConnectionFailure as e: prompt = self._get_prompt() diff --git a/pyproject.toml b/pyproject.toml index de2ce5e95..c547b3fd7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,4 +6,4 @@ testpaths = ["tests"] filterwarnings = [ 'ignore:AnsibleCollectionFinder has already been configured', 'ignore:_AnsibleCollectionFinder.find_spec().*', -] \ No newline at end of file +] diff --git a/test-requirements.txt b/test-requirements.txt index ab7aa6672..a42e5fcf7 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -3,4 +3,4 @@ black==23.3.0 flake8 yamllint coverage==4.5.4 -virl2-client==2.6.1 \ No newline at end of file +virl2-client==2.6.1 diff --git a/tests/integration/labs/single.yaml b/tests/integration/labs/single.yaml index 753abacaf..7c943e5bd 100644 --- a/tests/integration/labs/single.yaml +++ b/tests/integration/labs/single.yaml @@ -1,6 +1,6 @@ lab: - description: '' - notes: '' + description: "" + notes: "" title: nxos test version: 0.2.0 links: @@ -238,4 +238,4 @@ nodes: label: port slot: 0 type: physical -annotations: [] \ No newline at end of file +annotations: [] diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py index 48c9a4df1..9be926294 100644 --- a/tests/integration/test_integration.py +++ b/tests/integration/test_integration.py @@ -1,7 +1,7 @@ +import logging import os import subprocess -import logging import pytest diff --git a/tests/unit/compat/mock.py b/tests/unit/compat/mock.py index 50583cd6f..3b6fdcd61 100644 --- a/tests/unit/compat/mock.py +++ b/tests/unit/compat/mock.py @@ -104,7 +104,9 @@ def _readline_side_effect(): if file_spec is None: import _io - file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) + file_spec = list( + set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))) + ) if mock is None: mock = MagicMock(name="open", spec=open) diff --git a/tests/unit/mock/path.py b/tests/unit/mock/path.py index d15430fde..78733631d 100644 --- a/tests/unit/mock/path.py +++ b/tests/unit/mock/path.py @@ -7,4 +7,6 @@ from ansible_collections.cisco.nxos.tests.unit.compat.mock import MagicMock -mock_unfrackpath_noop = MagicMock(spec_set=unfrackpath, side_effect=lambda x, *args, **kwargs: x) +mock_unfrackpath_noop = MagicMock( + spec_set=unfrackpath, side_effect=lambda x, *args, **kwargs: x +) diff --git a/tests/unit/mock/vault_helper.py b/tests/unit/mock/vault_helper.py index 6006ba965..7a39b007b 100644 --- a/tests/unit/mock/vault_helper.py +++ b/tests/unit/mock/vault_helper.py @@ -37,4 +37,6 @@ def __init__(self, text, encoding=None, errors=None, _bytes=None): @property def bytes(self): """The text encoded with encoding, unless we specifically set _bytes.""" - return self._bytes or to_bytes(self.text, encoding=self.encoding, errors=self.errors) + return self._bytes or to_bytes( + self.text, encoding=self.encoding, errors=self.errors + ) diff --git a/tests/unit/mock/yaml_helper.py b/tests/unit/mock/yaml_helper.py index 2e857592a..e973f2642 100644 --- a/tests/unit/mock/yaml_helper.py +++ b/tests/unit/mock/yaml_helper.py @@ -17,7 +17,8 @@ class YamlTestUtils(object): def _loader(self, stream): """Vault related tests will want to override this. - Vault cases should setup a AnsibleLoader that has the vault password.""" + Vault cases should setup a AnsibleLoader that has the vault password. + """ return AnsibleLoader(stream) def _dump_stream(self, obj, stream, dumper=None): @@ -46,7 +47,9 @@ def _dump_load_cycle(self, obj): obj_2 = loader.get_data() # dump the gen 2 objects directory to strings - string_from_object_dump_2 = self._dump_string(obj_2, dumper=AnsibleDumper) + string_from_object_dump_2 = self._dump_string( + obj_2, dumper=AnsibleDumper + ) # The gen 1 and gen 2 yaml strings self.assertEqual(string_from_object_dump, string_from_object_dump_2) @@ -58,7 +61,9 @@ def _dump_load_cycle(self, obj): loader_3 = self._loader(stream_3) obj_3 = loader_3.get_data() - string_from_object_dump_3 = self._dump_string(obj_3, dumper=AnsibleDumper) + string_from_object_dump_3 = self._dump_string( + obj_3, dumper=AnsibleDumper + ) self.assertEqual(obj, obj_3) # should be transitive, but... @@ -90,8 +95,12 @@ def _old_dump_load_cycle(self, obj): stream_obj_from_string = io.StringIO() if PY3: - yaml.dump(obj_from_stream, stream_obj_from_stream, Dumper=AnsibleDumper) - yaml.dump(obj_from_stream, stream_obj_from_string, Dumper=AnsibleDumper) + yaml.dump( + obj_from_stream, stream_obj_from_stream, Dumper=AnsibleDumper + ) + yaml.dump( + obj_from_stream, stream_obj_from_string, Dumper=AnsibleDumper + ) else: yaml.dump( obj_from_stream, @@ -113,8 +122,12 @@ def _old_dump_load_cycle(self, obj): stream_obj_from_string.seek(0) if PY3: - yaml_string_obj_from_stream = yaml.dump(obj_from_stream, Dumper=AnsibleDumper) - yaml_string_obj_from_string = yaml.dump(obj_from_string, Dumper=AnsibleDumper) + yaml_string_obj_from_stream = yaml.dump( + obj_from_stream, Dumper=AnsibleDumper + ) + yaml_string_obj_from_string = yaml.dump( + obj_from_string, Dumper=AnsibleDumper + ) else: yaml_string_obj_from_stream = yaml.dump( obj_from_stream, @@ -128,7 +141,11 @@ def _old_dump_load_cycle(self, obj): ) assert yaml_string == yaml_string_obj_from_stream - assert yaml_string == yaml_string_obj_from_stream == yaml_string_obj_from_string + assert ( + yaml_string + == yaml_string_obj_from_stream + == yaml_string_obj_from_string + ) assert ( yaml_string == yaml_string_obj_from_stream diff --git a/tests/unit/modules/conftest.py b/tests/unit/modules/conftest.py index 41465c300..ee6bfa03a 100644 --- a/tests/unit/modules/conftest.py +++ b/tests/unit/modules/conftest.py @@ -22,11 +22,20 @@ def patch_ansible_module(request, mocker): if "ANSIBLE_MODULE_ARGS" not in request.param: request.param = {"ANSIBLE_MODULE_ARGS": request.param} if "_ansible_remote_tmp" not in request.param["ANSIBLE_MODULE_ARGS"]: - request.param["ANSIBLE_MODULE_ARGS"]["_ansible_remote_tmp"] = "/tmp" - if "_ansible_keep_remote_files" not in request.param["ANSIBLE_MODULE_ARGS"]: - request.param["ANSIBLE_MODULE_ARGS"]["_ansible_keep_remote_files"] = False + request.param["ANSIBLE_MODULE_ARGS"][ + "_ansible_remote_tmp" + ] = "/tmp" + if ( + "_ansible_keep_remote_files" + not in request.param["ANSIBLE_MODULE_ARGS"] + ): + request.param["ANSIBLE_MODULE_ARGS"][ + "_ansible_keep_remote_files" + ] = False args = json.dumps(request.param) else: - raise Exception("Malformed data to the patch_ansible_module pytest fixture") + raise Exception( + "Malformed data to the patch_ansible_module pytest fixture" + ) mocker.patch("ansible.module_utils.basic._ANSIBLE_ARGS", to_bytes(args)) diff --git a/tests/unit/modules/network/nxos/nxos_module.py b/tests/unit/modules/network/nxos/nxos_module.py index 99e324da0..a65988d62 100644 --- a/tests/unit/modules/network/nxos/nxos_module.py +++ b/tests/unit/modules/network/nxos/nxos_module.py @@ -84,11 +84,15 @@ def execute_module_devices( retvals = {} for model in models: - retvals[model] = self.execute_module(failed, changed, commands, sort, device=model) + retvals[model] = self.execute_module( + failed, changed, commands, sort, device=model + ) return retvals - def execute_module(self, failed=False, changed=False, commands=None, sort=True, device=""): + def execute_module( + self, failed=False, changed=False, commands=None, sort=True, device="" + ): self.load_fixtures(commands, device=device) if failed: @@ -105,7 +109,9 @@ def execute_module(self, failed=False, changed=False, commands=None, sort=True, result["commands"], ) else: - self.assertEqual(commands, result["commands"], result["commands"]) + self.assertEqual( + commands, result["commands"], result["commands"] + ) return result diff --git a/tests/unit/modules/network/nxos/test_nxos.py b/tests/unit/modules/network/nxos/test_nxos.py index fd5cdb36f..19450314b 100644 --- a/tests/unit/modules/network/nxos/test_nxos.py +++ b/tests/unit/modules/network/nxos/test_nxos.py @@ -112,13 +112,17 @@ def test_get_device_info_mds(self): def test_get_command_with_output_nxos(self): """Test _get_command_with_output for nxos""" self._prepare() - cmd = self._cliconf._get_command_with_output(command="show version", output="json") + cmd = self._cliconf._get_command_with_output( + command="show version", output="json" + ) self.assertEqual(cmd, "show version | json") def test_get_command_with_output_mds(self): """Test _get_command_with_output for mds""" self._prepare(platform="mds") - cmd = self._cliconf._get_command_with_output(command="show version", output="json") + cmd = self._cliconf._get_command_with_output( + command="show version", output="json" + ) self.assertEqual(cmd, "show version | json native") diff --git a/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py index ae56208fd..37b806800 100644 --- a/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py @@ -10,7 +10,9 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_acl_interfaces from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import set_module_args +from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( + set_module_args, +) from .nxos_module import TestNxosModule @@ -34,12 +36,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acl_interfaces.acl_interfaces.Acl_interfaces.edit_config", @@ -257,14 +263,18 @@ def test_nxos_acl_interfaces_overridden_idempotent(self): self.execute_module(changed=False, commands=[]) def test_nxos_acl_interfaces_deletedname(self): - set_module_args(dict(config=[dict(name="Ethernet1/2")], state="deleted")) + set_module_args( + dict(config=[dict(name="Ethernet1/2")], state="deleted") + ) commands = ["interface Ethernet1/2", "no ip access-group ACL1v4 out"] self.execute_module(changed=True, commands=commands) def test_nxos_acl_interfaces_deletedafi(self): set_module_args( dict( - config=[dict(name="Ethernet1/2", access_groups=[dict(afi="ipv4")])], + config=[ + dict(name="Ethernet1/2", access_groups=[dict(afi="ipv4")]) + ], state="deleted", ), ) @@ -330,7 +340,9 @@ def test_nxos_acl_interfaces_rendered(self): "ipv6 port traffic-filter ACL2v6 in", ] result = self.execute_module(changed=False) - self.assertEqual(sorted(result["rendered"]), sorted(commands), result["rendered"]) + self.assertEqual( + sorted(result["rendered"]), sorted(commands), result["rendered"] + ) def test_nxos_acl_interfaces_parsed(self): set_module_args( @@ -354,7 +366,9 @@ def test_nxos_acl_interfaces_parsed(self): { "access_groups": [ { - "acls": [{"direction": "in", "name": "ACL2v6", "port": True}], + "acls": [ + {"direction": "in", "name": "ACL2v6", "port": True} + ], "afi": "ipv6", }, ], @@ -379,7 +393,9 @@ def test_nxos_acl_interfaces_gathered(self): { "access_groups": [ { - "acls": [{"direction": "in", "name": "ACL2v6", "port": True}], + "acls": [ + {"direction": "in", "name": "ACL2v6", "port": True} + ], "afi": "ipv6", }, ], diff --git a/tests/unit/modules/network/nxos/test_nxos_acls.py b/tests/unit/modules/network/nxos/test_nxos_acls.py index 75087f082..5a331e728 100644 --- a/tests/unit/modules/network/nxos/test_nxos_acls.py +++ b/tests/unit/modules/network/nxos/test_nxos_acls.py @@ -12,7 +12,9 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_acls from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import set_module_args +from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( + set_module_args, +) from .nxos_module import TestNxosModule @@ -36,12 +38,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acls.acls.Acls.edit_config", @@ -83,7 +89,9 @@ def test_nxos_acls_merged(self): fragments=True, sequence=20, protocol="tcp", - protocol_options=dict(tcp=dict(ack=True)), + protocol_options=dict( + tcp=dict(ack=True) + ), ), dict( destination=dict( @@ -101,7 +109,9 @@ def test_nxos_acls_merged(self): ), dict( grant="deny", - destination=dict(prefix="2002:2:2:2::/64"), + destination=dict( + prefix="2002:2:2:2::/64" + ), source=dict(prefix="2002:1:1:1::/64"), sequence=30, protocol="icmp", @@ -196,7 +206,9 @@ def test_nxos_acls_replaced(self): sequence=50, protocol="icmp", protocol_options=dict( - icmp=dict(administratively_prohibited=True), + icmp=dict( + administratively_prohibited=True + ), ), ), ], @@ -284,7 +296,9 @@ def test_nxos_acls_overridden(self): sequence=50, protocol="icmp", protocol_options=dict( - icmp=dict(administratively_prohibited=True), + icmp=dict( + administratively_prohibited=True + ), ), ), dict(remark="Overridden ACL"), @@ -536,7 +550,12 @@ def test_nxos_acls_gathered(self): "protocol": "tcp", "source": { "any": True, - "port_protocol": {"range": {"start": "1024", "end": "65500"}}, + "port_protocol": { + "range": { + "start": "1024", + "end": "65500", + } + }, }, "destination": { "address": "192.168.0.0", @@ -726,7 +745,9 @@ def test_nxos_acls_parse_remark(self): "sequence": 20, "grant": "permit", "protocol": "ipv6", - "source": {"host": "2001:db8:85a3::8a2e:370:7334"}, + "source": { + "host": "2001:db8:85a3::8a2e:370:7334" + }, "destination": {"any": True}, }, ], @@ -780,11 +801,16 @@ def test_nxos_acls_parse_remark(self): "sequence": 11, "grant": "permit", "protocol": "tcp", - "protocol_options": {"tcp": {"established": True}}, + "protocol_options": { + "tcp": {"established": True} + }, "source": { "host": "1.1.1.1", "port_protocol": { - "range": {"end": "9111", "start": "7111"}, + "range": { + "end": "9111", + "start": "7111", + }, }, }, "destination": {"prefix": "192.168.0.0/24"}, diff --git a/tests/unit/modules/network/nxos/test_nxos_bfd_global.py b/tests/unit/modules/network/nxos/test_nxos_bfd_global.py index e0e48ac7a..438d0ad76 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bfd_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_bfd_global.py @@ -208,7 +208,9 @@ def test_bfd_defaults_n7k(self): def test_bfd_existing_n9k(self): module_name = self.module.__name__.rsplit(".", 1)[1] - self.execute_show_command.return_value = load_fixture(module_name, "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + module_name, "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -244,7 +246,9 @@ def test_bfd_existing_n9k(self): def test_bfd_idempotence_n9k(self): module_name = self.module.__name__.rsplit(".", 1)[1] - self.execute_show_command.return_value = load_fixture(module_name, "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + module_name, "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -265,7 +269,9 @@ def test_bfd_idempotence_n9k(self): def test_bfd_existing_n7k(self): module_name = self.module.__name__.rsplit(".", 1)[1] - self.execute_show_command.return_value = load_fixture(module_name, "N7K.cfg") + self.execute_show_command.return_value = load_fixture( + module_name, "N7K.cfg" + ) self.get_platform_shortname.return_value = "N7K" set_module_args( dict( @@ -305,7 +311,9 @@ def test_bfd_existing_n7k(self): def test_bfd_idempotence_n7k(self): module_name = self.module.__name__.rsplit(".", 1)[1] - self.execute_show_command.return_value = load_fixture(module_name, "N7K.cfg") + self.execute_show_command.return_value = load_fixture( + module_name, "N7K.cfg" + ) self.get_platform_shortname.return_value = "N7K" set_module_args( dict( diff --git a/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py index e40f5fc2e..306faa991 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py @@ -47,12 +47,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.bfd_interfaces.bfd_interfaces.Bfd_interfaces.edit_config", @@ -99,7 +103,9 @@ def test_1(self): interface Ethernet1/3 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="Ethernet1/1", bfd="disable", echo="disable"), @@ -148,7 +154,9 @@ def test_2(self): no bfd echo """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="Ethernet1/1", bfd="enable", echo="disable"), @@ -213,7 +221,9 @@ def test_3(self): no bfd echo """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict(config=[dict(name="Ethernet1/1")]) # Expected result commands for each 'state' merged = [] @@ -254,8 +264,12 @@ def test_4(self): no bfd """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} - playbook = dict(config=[dict(name="Ethernet1/1.42", bfd="enable", echo="disable")]) + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } + playbook = dict( + config=[dict(name="Ethernet1/1.42", bfd="enable", echo="disable")] + ) # Expected result commands for each 'state' merged = ["interface Ethernet1/1.42", "bfd", "no bfd echo"] deleted = [] @@ -295,7 +309,9 @@ def test_5(self): interface Ethernet1/2 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="Ethernet1/1", bfd="disable", echo="disable"), diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py b/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py index d9c6c2357..cc562607a 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py @@ -24,7 +24,9 @@ from textwrap import dedent -from ansible_collections.cisco.nxos.plugins.modules import nxos_bgp_address_family +from ansible_collections.cisco.nxos.plugins.modules import ( + nxos_bgp_address_family, +) from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch from .nxos_module import TestNxosModule, set_module_args @@ -53,7 +55,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_address_family.bgp_address_family.Bgp_address_familyFacts.get_config", @@ -151,7 +155,9 @@ def test_nxos_bgp_additional_paths_replaced(self): dict( afi="ipv4", safi="multicast", - additional_paths=dict(selection=dict(route_map="rmap1")), + additional_paths=dict( + selection=dict(route_map="rmap1") + ), ), dict( vrf="site-1", @@ -230,7 +236,9 @@ def test_nxos_bgp_l2vpn_keys_replaced(self): dict( config=dict( as_number="65563", - address_family=[dict(afi="l2vpn", safi="evpn", advertise_pip=True)], + address_family=[ + dict(afi="l2vpn", safi="evpn", advertise_pip=True) + ], ), state="replaced", ), @@ -351,7 +359,9 @@ def test_nxos_bgp_aggregate_address_merged(self): afi="ipv4", safi="multicast", aggregate_address=[ - dict(prefix="192.168.1.0/24", summary_only=True), + dict( + prefix="192.168.1.0/24", summary_only=True + ), dict( prefix="192.168.2.0/24", advertise_map="rmap1", @@ -482,7 +492,9 @@ def test_nxos_bgp_dampen_igp_metric_merged(self): config=dict( as_number="65563", address_family=[ - dict(afi="ipv4", safi="multicast", dampen_igp_metric=300), + dict( + afi="ipv4", safi="multicast", dampen_igp_metric=300 + ), dict( vrf="site-1", afi="ipv4", @@ -830,7 +842,9 @@ def test_nxos_bgp_default_metric_merged(self): config=dict( as_number="65563", address_family=[ - dict(afi="ipv4", safi="multicast", default_metric=7200), + dict( + afi="ipv4", safi="multicast", default_metric=7200 + ), dict( vrf="site-1", afi="ipv4", @@ -912,13 +926,17 @@ def test_nxos_bgp_distance_merged(self): dict( afi="ipv4", safi="multicast", - distance=dict(ebgp_routes=25, ibgp_routes=12, local_routes=4), + distance=dict( + ebgp_routes=25, ibgp_routes=12, local_routes=4 + ), ), dict( vrf="site-1", afi="ipv4", safi="unicast", - distance=dict(ebgp_routes=20, ibgp_routes=18, local_routes=3), + distance=dict( + ebgp_routes=20, ibgp_routes=18, local_routes=3 + ), ), ], ), @@ -961,7 +979,9 @@ def test_nxos_bgp_distance_replaced(self): vrf="site-1", afi="ipv4", safi="unicast", - distance=dict(ebgp_routes=20, ibgp_routes=18, local_routes=2), + distance=dict( + ebgp_routes=20, ibgp_routes=18, local_routes=2 + ), ), ], ), @@ -1161,7 +1181,9 @@ def test_nxos_bgp_inject_map_replaced(self): dict( afi="ipv4", safi="multicast", - inject_map=[dict(route_map="rmap1", exist_map="rmap3")], + inject_map=[ + dict(route_map="rmap1", exist_map="rmap3") + ], ), dict( vrf="site-1", @@ -1210,7 +1232,9 @@ def test_nxos_bgp_maximum_paths_merged(self): dict( afi="ipv4", safi="multicast", - maximum_paths=dict(parallel_paths=15, ibgp=dict(parallel_paths=64)), + maximum_paths=dict( + parallel_paths=15, ibgp=dict(parallel_paths=64) + ), ), dict( vrf="site-1", @@ -1273,7 +1297,9 @@ def test_nxos_bgp_maximum_paths_replaced(self): dict( afi="ipv4", safi="multicast", - maximum_paths=dict(parallel_paths=15, ibgp=dict(parallel_paths=64)), + maximum_paths=dict( + parallel_paths=15, ibgp=dict(parallel_paths=64) + ), ), dict( vrf="site-1", @@ -1318,9 +1344,13 @@ def test_nxos_bgp_network_merged(self): afi="ipv4", safi="multicast", networks=[ - dict(prefix="192.168.1.0/24", route_map="rmap2"), + dict( + prefix="192.168.1.0/24", route_map="rmap2" + ), dict(prefix="192.168.2.0/24"), - dict(prefix="192.168.3.0/24", route_map="rmap3"), + dict( + prefix="192.168.3.0/24", route_map="rmap3" + ), ], ), dict( @@ -1376,13 +1406,19 @@ def test_nxos_bgp_network_replaced(self): dict( afi="ipv4", safi="multicast", - networks=[dict(prefix="192.168.3.0/24", route_map="rmap4")], + networks=[ + dict( + prefix="192.168.3.0/24", route_map="rmap4" + ) + ], ), dict( vrf="site-1", afi="ipv4", safi="unicast", - networks=[dict(prefix="11.0.0.0/8", route_map="rmap2")], + networks=[ + dict(prefix="11.0.0.0/8", route_map="rmap2") + ], ), ], ), @@ -1424,7 +1460,9 @@ def test_nxos_bgp_nexthop_merged(self): safi="multicast", nexthop=dict( route_map="rmap1", - trigger_delay=dict(critical_delay=120, non_critical_delay=180), + trigger_delay=dict( + critical_delay=120, non_critical_delay=180 + ), ), ), dict( @@ -1432,7 +1470,9 @@ def test_nxos_bgp_nexthop_merged(self): afi="ipv4", safi="unicast", nexthop=dict( - trigger_delay=dict(critical_delay=110, non_critical_delay=170), + trigger_delay=dict( + critical_delay=110, non_critical_delay=170 + ), ), ), ], @@ -1482,7 +1522,9 @@ def test_nxos_bgp_nexthop_replaced(self): afi="ipv4", safi="unicast", nexthop=dict( - trigger_delay=dict(critical_delay=110, non_critical_delay=170), + trigger_delay=dict( + critical_delay=110, non_critical_delay=170 + ), ), ), ], @@ -1896,7 +1938,9 @@ def test_nxos_bgp_timers_merged(self): afi="ipv4", safi="multicast", timers=dict( - bestpath_defer=dict(defer_time=120, maximum_defer_time=380), + bestpath_defer=dict( + defer_time=120, maximum_defer_time=380 + ), ), ), dict( @@ -1904,7 +1948,9 @@ def test_nxos_bgp_timers_merged(self): afi="ipv4", safi="unicast", timers=dict( - bestpath_defer=dict(defer_time=110, maximum_defer_time=350), + bestpath_defer=dict( + defer_time=110, maximum_defer_time=350 + ), ), ), ], @@ -1945,7 +1991,9 @@ def test_nxos_bgp_timers_replaced(self): afi="ipv4", safi="multicast", timers=dict( - bestpath_defer=dict(defer_time=120, maximum_defer_time=380), + bestpath_defer=dict( + defer_time=120, maximum_defer_time=380 + ), ), ), dict(vrf="site-1", afi="ipv4", safi="unicast"), @@ -2076,7 +2124,11 @@ def test_nxos_bgp_af_parsed(self): vrf="site-1", afi="ipv4", safi="unicast", - timers=dict(bestpath_defer=dict(defer_time=100, maximum_defer_time=350)), + timers=dict( + bestpath_defer=dict( + defer_time=100, maximum_defer_time=350 + ) + ), ), ], ) @@ -2111,7 +2163,11 @@ def test_nxos_bgp_af_gathered(self): vrf="site-1", afi="ipv4", safi="unicast", - timers=dict(bestpath_defer=dict(defer_time=100, maximum_defer_time=350)), + timers=dict( + bestpath_defer=dict( + defer_time=100, maximum_defer_time=350 + ) + ), ), ], ) diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_global.py b/tests/unit/modules/network/nxos/test_nxos_bgp_global.py index 22c9378eb..02ae4d914 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_global.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_global.bgp_global.Bgp_globalFacts.get_config", @@ -87,7 +89,9 @@ def test_nxos_bgp_global_merged(self): dict( neighbor_address="198.51.100.21", remote_as="65537", - password=dict(encryption=7, key="12090404011C03162E"), + password=dict( + encryption=7, key="12090404011C03162E" + ), ), dict( neighbor_address="2001:4000:4000:fff1::/64", @@ -358,7 +362,9 @@ def test_nxos_bgp_global_merged_idempotent(self): dict( neighbor_address="198.51.100.21", remote_as="65537", - password=dict(encryption=7, key="12090404011C03162E"), + password=dict( + encryption=7, key="12090404011C03162E" + ), ), dict( neighbor_address="2001:4000:4000:fff1::/64", @@ -767,7 +773,9 @@ def test_nxos_bgp_global_replaced_failed_2(self): dict( neighbor_address="198.51.100.21", remote_as="65537", - password=dict(encryption=7, key="12090404011C03162E"), + password=dict( + encryption=7, key="12090404011C03162E" + ), ), ], vrfs=[ @@ -836,7 +844,9 @@ def test_nxos_bgp_global_replaced_failed_3(self): dict( neighbor_address="198.51.100.21", remote_as="65537", - password=dict(encryption=7, key="12090404011C03162E"), + password=dict( + encryption=7, key="12090404011C03162E" + ), ), ], vrfs=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py b/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py index b3943f370..8bec07416 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py @@ -24,7 +24,9 @@ from textwrap import dedent -from ansible_collections.cisco.nxos.plugins.modules import nxos_bgp_neighbor_address_family +from ansible_collections.cisco.nxos.plugins.modules import ( + nxos_bgp_neighbor_address_family, +) from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch from .nxos_module import TestNxosModule, set_module_args @@ -53,7 +55,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_neighbor_address_family." @@ -90,7 +94,9 @@ def test_nxos_bgp_nbr_af_advertise_map_merged(self): dict( afi="ipv4", safi="multicast", - advertise_map=dict(route_map="rmap1", exist_map="rmap2"), + advertise_map=dict( + route_map="rmap1", exist_map="rmap2" + ), ), ], ), @@ -168,7 +174,9 @@ def test_nxos_bgp_nbr_af_advertise_map_replaced(self): dict( afi="ipv4", safi="multicast", - advertise_map=dict(route_map="rmap1", exist_map="rmap3"), + advertise_map=dict( + route_map="rmap1", exist_map="rmap3" + ), ), ], ), @@ -584,7 +592,9 @@ def test_nxos_bgp_nbr_af_as_override_replaced(self): neighbors=[ dict( neighbor_address="10.0.0.2", - address_family=[dict(afi="ipv4", safi="multicast")], + address_family=[ + dict(afi="ipv4", safi="multicast") + ], ), ], vrfs=[ @@ -650,7 +660,9 @@ def test_nxos_bgp_nbr_af_capability_merged(self): afi="ipv4", safi="multicast", capability=dict( - additional_paths=dict(receive="enable", send="enable"), + additional_paths=dict( + receive="enable", send="enable" + ), ), ), ], @@ -741,7 +753,9 @@ def test_nxos_bgp_nbr_af_capability_replaced(self): dict( afi="ipv4", safi="multicast", - capability=dict(additional_paths=dict(send="enable")), + capability=dict( + additional_paths=dict(send="enable") + ), ), ], ), @@ -840,7 +854,9 @@ def test_nxos_bgp_nbr_af_originate_peer_as_merged(self): dict( afi="ipv4", safi="multicast", - default_originate=dict(route_map="rmap2"), + default_originate=dict( + route_map="rmap2" + ), ), ], ), @@ -971,8 +987,12 @@ def test_nxos_bgp_nbr_af_filter_list_inherit_merged(self): dict( afi="ipv4", safi="multicast", - filter_list=dict(inbound="rmap3", outbound="rmap4"), - inherit=dict(template="template-2", sequence=200), + filter_list=dict( + inbound="rmap3", outbound="rmap4" + ), + inherit=dict( + template="template-2", sequence=200 + ), ), ], ), @@ -1065,7 +1085,9 @@ def test_nxos_bgp_nbr_af_filter_list_inherit_replaced(self): afi="ipv4", safi="multicast", filter_list=dict(inbound="rmap3"), - inherit=dict(template="template-2", sequence=200), + inherit=dict( + template="template-2", sequence=200 + ), ), ], ), @@ -1184,7 +1206,9 @@ def test_nxos_bgp_nbr_af_maximum_prefix_merged(self): dict( afi="ipv4", safi="multicast", - maximum_prefix=dict(max_prefix_limit=28), + maximum_prefix=dict( + max_prefix_limit=28 + ), ), dict( afi="ipv4", @@ -1290,7 +1314,9 @@ def test_nxos_bgp_nbr_af_maximum_prefix_replaced(self): dict( afi="ipv4", safi="multicast", - maximum_prefix=dict(max_prefix_limit=28), + maximum_prefix=dict( + max_prefix_limit=28 + ), ), dict( afi="ipv4", @@ -1382,12 +1408,16 @@ def test_nxos_bgp_nbr_af_next_hop_merged(self): dict( afi="ipv4", safi="multicast", - next_hop_self=dict(all_routes=True), + next_hop_self=dict( + all_routes=True + ), ), dict( afi="ipv6", safi="multicast", - next_hop_self=dict(all_routes=True), + next_hop_self=dict( + all_routes=True + ), ), ], ), @@ -1467,7 +1497,9 @@ def test_nxos_bgp_nbr_af_next_hop_replaced(self): dict( afi="ipv4", safi="multicast", - next_hop_self=dict(all_routes=True), + next_hop_self=dict( + all_routes=True + ), ), ], ), @@ -1518,7 +1550,9 @@ def test_nxos_bgp_nbr_af_prefix_list_merged(self): dict( afi="ipv4", safi="multicast", - prefix_list=dict(inbound="rmap3", outbound="rmap4"), + prefix_list=dict( + inbound="rmap3", outbound="rmap4" + ), ), ], ), @@ -1669,7 +1703,9 @@ def test_nxos_bgp_nbr_af_rewrite_evpn_route_map_merged(self): dict( afi="ipv4", safi="multicast", - route_map=dict(inbound="rmap3", outbound="rmap4"), + route_map=dict( + inbound="rmap3", outbound="rmap4" + ), rewrite_evpn_rt_asn=True, ), ], @@ -1969,7 +2005,9 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_merged(self): dict( afi="ipv4", safi="multicast", - soft_reconfiguration_inbound=dict(set=True), + soft_reconfiguration_inbound=dict( + set=True + ), soo="73:43", ), ], @@ -1985,13 +2023,17 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_merged(self): dict( afi="ipv4", safi="unicast", - soft_reconfiguration_inbound=dict(always=True), + soft_reconfiguration_inbound=dict( + always=True + ), soo="65:28", ), dict( afi="ipv4", safi="multicast", - soft_reconfiguration_inbound=dict(always=True), + soft_reconfiguration_inbound=dict( + always=True + ), ), ], ), @@ -2046,7 +2088,9 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_replaced(self): dict( afi="ipv4", safi="multicast", - soft_reconfiguration_inbound=dict(set=True), + soft_reconfiguration_inbound=dict( + set=True + ), ), ], ), @@ -2061,7 +2105,9 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_replaced(self): dict( afi="ipv4", safi="unicast", - soft_reconfiguration_inbound=dict(always=True), + soft_reconfiguration_inbound=dict( + always=True + ), soo="65:28", ), dict(afi="ipv4", safi="multicast"), @@ -2197,7 +2243,9 @@ def test_nxos_bgp_nbr_af_suppress_inactive_unsuppress_replaced(self): neighbors=[ dict( neighbor_address="10.0.0.2", - address_family=[dict(afi="ipv4", safi="multicast")], + address_family=[ + dict(afi="ipv4", safi="multicast") + ], ), ], vrfs=[ @@ -2381,7 +2429,9 @@ def test_nxos_bgp_nbr_af_overridden(self): neighbors=[ dict( neighbor_address="192.168.1.1", - address_family=[dict(afi="ipv4", safi="multicast")], + address_family=[ + dict(afi="ipv4", safi="multicast") + ], ), ], ), @@ -2439,7 +2489,9 @@ def test_nxos_bgp_nbr_af_gathered(self): neighbors=[ dict( neighbor_address="192.168.1.1", - address_family=[dict(afi="ipv4", safi="multicast")], + address_family=[ + dict(afi="ipv4", safi="multicast") + ], ), ], ), @@ -2484,7 +2536,9 @@ def test_nxos_bgp_nbr_af_parsed(self): neighbors=[ dict( neighbor_address="192.168.1.1", - address_family=[dict(afi="ipv4", safi="multicast")], + address_family=[ + dict(afi="ipv4", safi="multicast") + ], ), ], ), @@ -2602,7 +2656,9 @@ def test_nxos_bgp_nbr_af_no_cmd(self): neighbors=[ dict( neighbor_address="10.0.0.2", - address_family=[dict(afi="ipv4", safi="multicast")], + address_family=[ + dict(afi="ipv4", safi="multicast") + ], ), ], ), diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py b/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py index 8d2fd74b5..fe9d92440 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_templates.bgp_templates.Bgp_templatesFacts.get_config", @@ -340,7 +342,9 @@ def test_nxos_bgp_templates_deleted_single(self): ) set_module_args( dict( - config=dict(as_number="65536", neighbor=[dict(name="tmplt_1")]), + config=dict( + as_number="65536", neighbor=[dict(name="tmplt_1")] + ), state="deleted", ), ignore_provider_arg, @@ -372,7 +376,11 @@ def test_nxos_bgp_templates_deleted_all(self): ), ignore_provider_arg, ) - commands = ["router bgp 65536", "no template peer tmplt_1", "no template peer tmplt_2"] + commands = [ + "router bgp 65536", + "no template peer tmplt_1", + "no template peer tmplt_2", + ] result = self.execute_module(changed=True) self.assertEqual(set(result["commands"]), set(commands)) diff --git a/tests/unit/modules/network/nxos/test_nxos_command.py b/tests/unit/modules/network/nxos/test_nxos_command.py index cb7c40ba9..84bf5b133 100644 --- a/tests/unit/modules/network/nxos/test_nxos_command.py +++ b/tests/unit/modules/network/nxos/test_nxos_command.py @@ -87,7 +87,9 @@ def test_nxos_command_wait_for_fails(self): def test_nxos_command_retries(self): wait_for = 'result[0] contains "test string"' - set_module_args(dict(commands=["show version"], wait_for=wait_for, retries=2)) + set_module_args( + dict(commands=["show version"], wait_for=wait_for, retries=2) + ) self.execute_module(failed=True) self.assertEqual(self.run_commands.call_count, 3) @@ -101,7 +103,9 @@ def test_nxos_command_match_any(self): 'result[0] contains "Cisco"', 'result[0] contains "test string"', ] - set_module_args(dict(commands=["show version"], wait_for=wait_for, match="any")) + set_module_args( + dict(commands=["show version"], wait_for=wait_for, match="any") + ) self.execute_module() def test_nxos_command_match_all(self): @@ -109,7 +113,9 @@ def test_nxos_command_match_all(self): 'result[0] contains "Cisco"', 'result[0] contains "image file"', ] - set_module_args(dict(commands=["show version"], wait_for=wait_for, match="all")) + set_module_args( + dict(commands=["show version"], wait_for=wait_for, match="all") + ) self.execute_module() def test_nxos_command_match_all_failure(self): @@ -118,5 +124,7 @@ def test_nxos_command_match_all_failure(self): 'result[0] contains "test string"', ] commands = ["show version", "show version"] - set_module_args(dict(commands=commands, wait_for=wait_for, match="all")) + set_module_args( + dict(commands=commands, wait_for=wait_for, match="all") + ) self.execute_module(failed=True) diff --git a/tests/unit/modules/network/nxos/test_nxos_config.py b/tests/unit/modules/network/nxos/test_nxos_config.py index ce5c987c7..a1f79899a 100644 --- a/tests/unit/modules/network/nxos/test_nxos_config.py +++ b/tests/unit/modules/network/nxos/test_nxos_config.py @@ -24,7 +24,10 @@ from ansible_collections.cisco.nxos.plugins.cliconf.nxos import Cliconf from ansible_collections.cisco.nxos.plugins.modules import nxos_config -from ansible_collections.cisco.nxos.tests.unit.compat.mock import MagicMock, patch +from ansible_collections.cisco.nxos.tests.unit.compat.mock import ( + MagicMock, + patch, +) from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -74,14 +77,18 @@ def tearDown(self): self.mock_get_connection.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("nxos_config", "config.cfg") + self.get_config.return_value = load_fixture( + "nxos_config", "config.cfg" + ) self.load_config.return_value = None def test_nxos_config_no_change(self): lines = ["hostname localhost"] args = dict(lines=lines) self.conn.get_diff = MagicMock( - return_value=self.cliconf_obj.get_diff("\n".join(lines), self.running_config), + return_value=self.cliconf_obj.get_diff( + "\n".join(lines), self.running_config + ), ) set_module_args(args) result = self.execute_module() @@ -103,7 +110,9 @@ def test_nxos_config_src(self): "ip routing", ] - self.assertEqual(sorted(config), sorted(result["commands"]), result["commands"]) + self.assertEqual( + sorted(config), sorted(result["commands"]), result["commands"] + ) def test_nxos_config_replace_src(self): set_module_args(dict(replace_src="bootflash:config", replace="config")) @@ -115,33 +124,43 @@ def test_nxos_config_replace_src(self): ), ) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["config replace bootflash:config"]) + self.assertEqual( + result["commands"], ["config replace bootflash:config"] + ) def test_nxos_config_lines(self): lines = ["hostname switch01", "ip domain-name eng.ansible.com"] args = dict(lines=lines) self.conn.get_diff = MagicMock( - return_value=self.cliconf_obj.get_diff("\n".join(lines), self.running_config), + return_value=self.cliconf_obj.get_diff( + "\n".join(lines), self.running_config + ), ) set_module_args(args) result = self.execute_module(changed=True) config = ["hostname switch01"] - self.assertEqual(sorted(config), sorted(result["commands"]), result["commands"]) + self.assertEqual( + sorted(config), sorted(result["commands"]), result["commands"] + ) def test_nxos_config_before(self): lines = ["hostname switch01", "ip domain-name eng.ansible.com"] args = dict(lines=lines, before=["before command"]) self.conn.get_diff = MagicMock( - return_value=self.cliconf_obj.get_diff("\n".join(lines), self.running_config), + return_value=self.cliconf_obj.get_diff( + "\n".join(lines), self.running_config + ), ) set_module_args(args) result = self.execute_module(changed=True) config = ["before command", "hostname switch01"] - self.assertEqual(sorted(config), sorted(result["commands"]), result["commands"]) + self.assertEqual( + sorted(config), sorted(result["commands"]), result["commands"] + ) self.assertEqual("before command", result["commands"][0]) def test_nxos_config_after(self): @@ -149,14 +168,18 @@ def test_nxos_config_after(self): args = dict(lines=lines, after=["after command"]) self.conn.get_diff = MagicMock( - return_value=self.cliconf_obj.get_diff("\n".join(lines), self.running_config), + return_value=self.cliconf_obj.get_diff( + "\n".join(lines), self.running_config + ), ) set_module_args(args) result = self.execute_module(changed=True) config = ["after command", "hostname switch01"] - self.assertEqual(sorted(config), sorted(result["commands"]), result["commands"]) + self.assertEqual( + sorted(config), sorted(result["commands"]), result["commands"] + ) self.assertEqual("after command", result["commands"][-1]) def test_nxos_config_parents(self): @@ -198,7 +221,9 @@ def test_nxos_replace_block_src(self): "ip routing", ] - self.assertEqual(sorted(config), sorted(result["commands"]), result["commands"]) + self.assertEqual( + sorted(config), sorted(result["commands"]), result["commands"] + ) def test_nxos_replace_block_lines(self): lines = ["ip address 1.2.3.4/5", "no shutdown"] @@ -302,13 +327,17 @@ def test_nxos_config_defaults_true(self): self.assertEqual(self.get_config.call_args[1], dict(flags=["all"])) def test_nxos_config_defaults_false_backup_true(self): - set_module_args(dict(lines=["hostname localhost"], defaults=False, backup=True)) + set_module_args( + dict(lines=["hostname localhost"], defaults=False, backup=True) + ) result = self.execute_module(changed=True) self.assertEqual(self.get_config.call_count, 1) self.assertEqual(self.get_config.call_args[1], dict(flags=[])) def test_nxos_config_defaults_true_backup_true(self): - set_module_args(dict(lines=["hostname localhost"], defaults=True, backup=True)) + set_module_args( + dict(lines=["hostname localhost"], defaults=True, backup=True) + ) result = self.execute_module(changed=True) self.assertEqual(self.get_config.call_count, 1) self.assertEqual(self.get_config.call_args[1], dict(flags=["all"])) diff --git a/tests/unit/modules/network/nxos/test_nxos_devicealias.py b/tests/unit/modules/network/nxos/test_nxos_devicealias.py index 640bcd150..ebd754ff9 100644 --- a/tests/unit/modules/network/nxos/test_nxos_devicealias.py +++ b/tests/unit/modules/network/nxos/test_nxos_devicealias.py @@ -11,7 +11,9 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_devicealias from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import AnsibleFailJson +from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( + AnsibleFailJson, +) from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -21,12 +23,16 @@ class TestNxosDeviceAliasModule(TestNxosModule): def setUp(self): super(TestNxosDeviceAliasModule, self).setUp() - module_path = "ansible_collections.cisco.nxos.plugins.modules.nxos_devicealias." + module_path = ( + "ansible_collections.cisco.nxos.plugins.modules.nxos_devicealias." + ) self.mock_run_commands = patch(module_path + "run_commands") self.run_commands = self.mock_run_commands.start() - self.mock_execute_show_cmd = patch(module_path + "showDeviceAliasStatus.execute_show_cmd") + self.mock_execute_show_cmd = patch( + module_path + "showDeviceAliasStatus.execute_show_cmd" + ) self.execute_show_cmd = self.mock_execute_show_cmd.start() self.mock_execute_show_cmd_1 = patch( @@ -51,7 +57,9 @@ def test_da_mode_1(self): # Playbook mode is basic # Switch has mode as enahnced set_module_args(dict(mode="basic"), True) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -67,7 +75,9 @@ def test_da_mode_2(self): # Playbook mode is enhanced # Switch has mode as enahnced set_module_args(dict(mode="enhanced"), True) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -75,7 +85,9 @@ def test_da_distribute_1(self): # Playbook mode is enhanced , distrbute = True # Switch has mode as enahnced, distrbute = True set_module_args(dict(distribute=True, mode="enhanced"), True) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -83,7 +95,9 @@ def test_da_distribute_2(self): # Playbook mode is enhanced , distrbute = False # Switch has mode as enhanced, distrbute = True set_module_args(dict(distribute=False, mode="enhanced"), True) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) result = self.execute_module(changed=True) self.assertEqual(result["commands"], ["no device-alias distribute"]) @@ -91,7 +105,9 @@ def test_da_distribute_3(self): # Playbook mode is basic , distrbute = False # Switch has mode as enahnced, distrbute = True set_module_args(dict(distribute=False, mode="basic"), True) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -112,8 +128,12 @@ def test_da_add_1(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -138,8 +158,12 @@ def test_da_add_2(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -154,8 +178,12 @@ def test_da_add_3(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False, failed=True) def test_da_add_4(self): @@ -169,8 +197,12 @@ def test_da_add_4(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False, failed=True) def test_da_remove_1(self): @@ -190,8 +222,12 @@ def test_da_remove_1(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -221,8 +257,12 @@ def test_da_remove_2(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -242,7 +282,9 @@ def test_da_lock(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatuslock.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatuslock.cfg" + ) self.execute_module(failed=True) def test_da_paramete_not_supported(self): @@ -262,8 +304,12 @@ def test_da_paramete_not_supported(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] @@ -280,8 +326,12 @@ def test_da_name_parameter_missing(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] @@ -299,8 +349,12 @@ def test_da_rename_1(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -325,8 +379,12 @@ def test_da_rename_2(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False, failed=True) self.assertEqual(result["commands"], []) @@ -336,7 +394,9 @@ def test_da_mansi(self): "nxos_devicealias", "shdastatus_mansi.cfg", ) - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -360,8 +420,12 @@ def test_da_add_bad(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False, failed=True) assert "it must start with a letter" in str(result["msg"]) @@ -377,8 +441,12 @@ def test_da_add_bad_1(self): ), True, ) - self.execute_show_cmd.return_value = load_fixture("nxos_devicealias", "shdastatus.cfg") - self.execute_show_cmd_1.return_value = load_fixture("nxos_devicealias", "shdadatabse.cfg") + self.execute_show_cmd.return_value = load_fixture( + "nxos_devicealias", "shdastatus.cfg" + ) + self.execute_show_cmd_1.return_value = load_fixture( + "nxos_devicealias", "shdadatabse.cfg" + ) result = self.execute_module(changed=False, failed=True) assert "and can only contain these characters" in str(result["msg"]) diff --git a/tests/unit/modules/network/nxos/test_nxos_evpn_global.py b/tests/unit/modules/network/nxos/test_nxos_evpn_global.py index c9fa7911e..77303e4bc 100644 --- a/tests/unit/modules/network/nxos/test_nxos_evpn_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_evpn_global.py @@ -60,11 +60,15 @@ def load_fixtures(self, commands=None, device=""): self.load_config.return_value = None def start_configured(self, *args, **kwargs): - self.get_config.return_value = load_fixture("nxos_evpn_global", "configured.cfg") + self.get_config.return_value = load_fixture( + "nxos_evpn_global", "configured.cfg" + ) return self.execute_module(*args, **kwargs) def start_unconfigured(self, *args, **kwargs): - self.get_config.return_value = load_fixture("nxos_evpn_global", "unconfigured.cfg") + self.get_config.return_value = load_fixture( + "nxos_evpn_global", "unconfigured.cfg" + ) return self.execute_module(*args, **kwargs) def test_nxos_evpn_global_enable(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py b/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py index 0211a5a31..f648edcf4 100644 --- a/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py +++ b/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py @@ -50,11 +50,15 @@ def tearDown(self): self.mock_get_config.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("", "nxos_evpn_vni_config.cfg") + self.get_config.return_value = load_fixture( + "", "nxos_evpn_vni_config.cfg" + ) self.load_config.return_value = None def test_nxos_evpn_vni_present(self): - set_module_args(dict(vni="6000", route_target_import="5000:10", state="present")) + set_module_args( + dict(vni="6000", route_target_import="5000:10", state="present") + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], diff --git a/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py index 098a5b7ff..a2e26478d 100644 --- a/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py @@ -644,7 +644,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.fc_interfaces.fc_interfaces.Fc_interfacesFacts.get_interfaces_data", @@ -705,7 +707,9 @@ def test_gathered(self): def test_parsed(self): # test parsed for config - set_module_args(dict(state="parsed", running_config=sh_run), ignore_provider_arg) + set_module_args( + dict(state="parsed", running_config=sh_run), ignore_provider_arg + ) result = self.execute_module(changed=False) self.assertEqual(result["parsed"], gath_val) @@ -759,7 +763,11 @@ def test_analytics_all_to_scsi_replaced(self): result = self.execute_module(changed=True) self.assertEqual( result["commands"], - ["interface fc18/12", "no analytics type fc-all", "analytics type fc-scsi"], + [ + "interface fc18/12", + "no analytics type fc-all", + "analytics type fc-scsi", + ], ) def test_analytics_all_to_nvme(self): @@ -803,7 +811,11 @@ def test_analytics_all_to_nvme_replaced(self): result = self.execute_module(changed=True) self.assertEqual( result["commands"], - ["interface fc18/12", "no analytics type fc-all", "analytics type fc-nvme"], + [ + "interface fc18/12", + "no analytics type fc-all", + "analytics type fc-nvme", + ], ) def test_analytics_all_to_none_checkthis(self): @@ -841,7 +853,10 @@ def test_analytics_all_to_none_desc_change(self): ) set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface fc18/12", "switchport description 2"]) + self.assertEqual( + result["commands"], + ["interface fc18/12", "switchport description 2"], + ) def test_analytics_scsi_to_nvme(self): args = dict( @@ -884,7 +899,11 @@ def test_analytics_scsi_to_nvme_replaced(self): result = self.execute_module(changed=True) self.assertEqual( result["commands"], - ["interface fc18/11", "no analytics type fc-all", "analytics type fc-nvme"], + [ + "interface fc18/11", + "no analytics type fc-all", + "analytics type fc-nvme", + ], ) def test_analytics_scsi_to_all(self): @@ -904,7 +923,9 @@ def test_analytics_scsi_to_all(self): ) set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface fc18/11", "analytics type fc-all"]) + self.assertEqual( + result["commands"], ["interface fc18/11", "analytics type fc-all"] + ) def test_analytics_scsi_to_all_replaced(self): args = dict( @@ -1043,7 +1064,9 @@ def test_analytics_none_to_scsi(self): ) set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface fc1/1", "analytics type fc-scsi"]) + self.assertEqual( + result["commands"], ["interface fc1/1", "analytics type fc-scsi"] + ) def test_analytics_none_to_scsi_replaced(self): args = dict( @@ -1082,7 +1105,9 @@ def test_analytics_none_to_nvme(self): ) set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface fc1/1", "analytics type fc-nvme"]) + self.assertEqual( + result["commands"], ["interface fc1/1", "analytics type fc-nvme"] + ) def test_analytics_none_to_nvme_replaced(self): args = dict( @@ -1228,7 +1253,9 @@ def test_analytics_none_to_all(self): ) set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface fc1/1", "analytics type fc-all"]) + self.assertEqual( + result["commands"], ["interface fc1/1", "analytics type fc-all"] + ) def test_analytics_none_to_all_replaced(self): args = dict( @@ -1465,7 +1492,10 @@ def test_speed_combinations(self): cmds = [] else: changed = True - cmds = [f"interface {port_name}", f"switchport speed {each_speed}"] + cmds = [ + f"interface {port_name}", + f"switchport speed {each_speed}", + ] set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=changed) @@ -1492,7 +1522,10 @@ def test_port_mode_combinations(self): cmds = [] else: changed = True - cmds = [f"interface {port_name}", f"switchport mode {each_mode}"] + cmds = [ + f"interface {port_name}", + f"switchport mode {each_mode}", + ] set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=changed) diff --git a/tests/unit/modules/network/nxos/test_nxos_feature.py b/tests/unit/modules/network/nxos/test_nxos_feature.py index 1c79537f1..f37fa7c14 100644 --- a/tests/unit/modules/network/nxos/test_nxos_feature.py +++ b/tests/unit/modules/network/nxos/test_nxos_feature.py @@ -85,12 +85,16 @@ def load_from_file(*args, **kwargs): def test_nxos_feature_enable(self): set_module_args(dict(feature="nve", state="enabled")) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["terminal dont-ask", "feature nv overlay"]) + self.assertEqual( + result["commands"], ["terminal dont-ask", "feature nv overlay"] + ) def test_nxos_feature_disable(self): set_module_args(dict(feature="ospf", state="disabled")) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["terminal dont-ask", "no feature ospf"]) + self.assertEqual( + result["commands"], ["terminal dont-ask", "no feature ospf"] + ) class TestNxosFeatureModuleMDS(TestNxosModule): @@ -154,12 +158,16 @@ def load_from_file(*args, **kwargs): def test_nxos_feature_enable(self): set_module_args(dict(feature="fcrxbbcredit", state="enabled")) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["terminal dont-ask", "feature fcrxbbcredit"]) + self.assertEqual( + result["commands"], ["terminal dont-ask", "feature fcrxbbcredit"] + ) def test_nxos_feature_disable(self): set_module_args(dict(feature="port-track", state="disabled")) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["terminal dont-ask", "no feature port-track"]) + self.assertEqual( + result["commands"], ["terminal dont-ask", "no feature port-track"] + ) def test_nxos_feature_enable_already_enabled(self): set_module_args(dict(feature="analytics", state="enabled")) diff --git a/tests/unit/modules/network/nxos/test_nxos_hostname.py b/tests/unit/modules/network/nxos/test_nxos_hostname.py index 732f59e7a..20c071ad5 100644 --- a/tests/unit/modules/network/nxos/test_nxos_hostname.py +++ b/tests/unit/modules/network/nxos/test_nxos_hostname.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.hostname.hostname.HostnameFacts.get_config", @@ -154,7 +156,9 @@ def test_nxos_hostname_parsed(self): hostname NXOSv-9k """, ) - set_module_args(dict(running_config=cfg, state="parsed"), ignore_provider_arg) + set_module_args( + dict(running_config=cfg, state="parsed"), ignore_provider_arg + ) parsed = {"hostname": "NXOSv-9k"} result = self.execute_module(changed=False) self.assertEqual(result["parsed"], parsed) diff --git a/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py index e4f21a825..0dc6baeb2 100644 --- a/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py @@ -47,12 +47,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.hsrp_interfaces.hsrp_interfaces.Hsrp_interfaces.edit_config", @@ -97,7 +101,9 @@ def test_1(self): interface Ethernet1/3 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="Ethernet1/1", bfd="enable"), @@ -138,7 +144,9 @@ def test_2(self): hsrp bfd """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="Ethernet1/1", bfd="disable"), @@ -198,8 +206,12 @@ def test_3(self): hsrp bfd """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} - playbook = dict(config=[dict(name="Ethernet1/1"), dict(name="Ethernet1/2")]) + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } + playbook = dict( + config=[dict(name="Ethernet1/1"), dict(name="Ethernet1/2")] + ) # Expected result commands for each 'state' merged = [] deleted = [ @@ -249,7 +261,9 @@ def test_4(self): hsrp bfd """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict(config=[dict(name="Ethernet1/1.42", bfd="enable")]) # Expected result commands for each 'state' merged = ["interface Ethernet1/1.42", "hsrp bfd"] @@ -289,7 +303,9 @@ def test_5(self): interface Ethernet1/2 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="Ethernet1/1", bfd="enable"), diff --git a/tests/unit/modules/network/nxos/test_nxos_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_interfaces.py index a1d491af1..c58dd8123 100644 --- a/tests/unit/modules/network/nxos/test_nxos_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_interfaces.py @@ -47,12 +47,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.interfaces.interfaces.Interfaces.edit_config", @@ -123,7 +127,9 @@ def test_1(self): description test-loopback """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( @@ -281,7 +287,9 @@ def test_2(self): shutdown """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( @@ -423,7 +431,9 @@ def test_3(self): shutdown """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( @@ -486,7 +496,9 @@ def test_3(self): "no shutdown", "interface Ethernet1/4.101", ] - self.execute_module(changed=True, commands=merged_legacy, device="legacy") + self.execute_module( + changed=True, commands=merged_legacy, device="legacy" + ) deleted = [ "interface Ethernet1/2", @@ -597,7 +609,9 @@ def test_4(self): shutdown """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( @@ -631,7 +645,9 @@ def test_5(self): no shutdown """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict() @@ -671,7 +687,9 @@ def test_6_gathered(self): interface loopback1 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict() @@ -712,7 +730,9 @@ def test_7_purged(self): description sub-intf """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( @@ -751,7 +771,9 @@ def test_vlan_enabled(self): interface Vlan10 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( @@ -790,7 +812,9 @@ def test_mode_mtu(self): mtu 9216 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_RUN_INTF: intf} + self.get_resource_connection_facts.return_value = { + self.SHOW_RUN_INTF: intf + } self.get_system_defaults.return_value = sysdefs playbook = dict( diff --git a/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py index 289c36ffd..d96b82772 100644 --- a/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py @@ -28,7 +28,10 @@ L3_interfaces, ) from ansible_collections.cisco.nxos.plugins.modules import nxos_l3_interfaces -from ansible_collections.cisco.nxos.tests.unit.compat.mock import PropertyMock, patch +from ansible_collections.cisco.nxos.tests.unit.compat.mock import ( + PropertyMock, + patch, +) from .nxos_module import TestNxosModule, set_module_args @@ -50,12 +53,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.l3_interfaces.l3_interfaces.L3_interfaces.edit_config", @@ -109,14 +116,20 @@ def test_2(self): no ipv6 redirects """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="mgmt0", ipv4=[{"address": "10.0.0.254/24"}]), dict(name="Ethernet1/1", ipv4=[{"address": "192.168.1.1/24"}]), dict(name="Ethernet1/2"), dict(name="port-channel355", ipv6_redirects=False), - dict(name="port-channel336", ipv6_redirects=False, ipv6=[{"address": "10::5/128"}]), + dict( + name="port-channel336", + ipv6_redirects=False, + ipv6=[{"address": "10::5/128"}], + ), # Eth1/3 not present! Thus overridden should set Eth1/3 to defaults; # replaced should ignore Eth1/3. ], @@ -201,7 +214,9 @@ def test_3(self): ipv6 address 10::5/128 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="mgmt0", ipv4=[{"address": "10.0.0.254/24"}]), @@ -306,7 +321,9 @@ def test_4(self): ip address 10.25.25.25/24 secondary """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="mgmt0", ipv4=[{"address": "10.0.0.254/24"}]), @@ -446,7 +463,9 @@ def test_5(self): ipv6 address 10::13/128 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict( @@ -531,7 +550,9 @@ def test_6(self): no ip redirects """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict( @@ -541,7 +562,9 @@ def test_6(self): ipv4=[{"address": "192.168.1.1/24"}], ), dict(name="Ethernet1/2"), - dict(name="Ethernet1/3", redirects=True, unreachables=False), # defaults + dict( + name="Ethernet1/3", redirects=True, unreachables=False + ), # defaults dict(name="Ethernet1/4", redirects=False, unreachables=True), ], ) @@ -613,7 +636,9 @@ def test_7(self): interface Ethernet1/2 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict( @@ -661,7 +686,9 @@ def test_7(self): interface Ethernet1/2 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook["state"] = "deleted" set_module_args(playbook, ignore_provider_arg) self.execute_module(changed=False) @@ -674,7 +701,9 @@ def test_8(self): ip address 10.1.1.1/24 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict() for i in ["merged", "replaced", "overridden"]: @@ -700,8 +729,12 @@ def test_9(self): ip address 10.25.25.25/24 secondary """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} - playbook = dict(config=[dict(name="Ethernet1/3"), dict(name="Ethernet1/5")]) + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } + playbook = dict( + config=[dict(name="Ethernet1/3"), dict(name="Ethernet1/5")] + ) # Expected result commands for each 'state' deleted = [ "interface Ethernet1/3", @@ -758,7 +791,9 @@ def test_10(self): evpn multisite dci-tracking """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="mgmt0", ipv4=[{"address": "10.0.0.254/24"}]), @@ -838,7 +873,9 @@ def test_11(self): evpn multisite fabric-tracking """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict(name="mgmt0", ipv4=[{"address": "10.0.0.254/24"}]), @@ -981,12 +1018,16 @@ def test_12(self): ip address 192.168.1.1/24 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict( name="Vlan99", - ipv4=[{"address": "192.168.1.1/24", "tag": 500}], # adding a tag + ipv4=[ + {"address": "192.168.1.1/24", "tag": 500} + ], # adding a tag ), ], state="replaced", @@ -1010,7 +1051,9 @@ def test_12_gathered(self): interface loopback1 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict(state="gathered") gathered_facts = [ {"name": "nve1"}, @@ -1029,7 +1072,9 @@ def test_replaced_tag(self): ip address 192.168.1.10/24 tag 20 """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict( diff --git a/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py index e6850278a..b3b9bf1c6 100644 --- a/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py @@ -47,12 +47,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.l3_interfaces.l3_interfaces.L3_interfaces.edit_config", @@ -84,7 +88,9 @@ def test_lacp_mode_parse(self): no lacp graceful-convergence """, ) - self.get_resource_connection_facts.return_value = {self.SHOW_CMD: existing} + self.get_resource_connection_facts.return_value = { + self.SHOW_CMD: existing + } playbook = dict( config=[ dict( diff --git a/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py index c2acfcc49..b2f8b222d 100644 --- a/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py @@ -10,7 +10,9 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_lldp_interfaces from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import set_module_args +from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( + set_module_args, +) from .nxos_module import TestNxosModule @@ -34,12 +36,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.lldp_interfaces.lldp_interfaces.Lldp_interfaces.edit_config", @@ -150,7 +156,9 @@ def test_nxos_lldp_interfaces_replaced_idempotent(self): def test_nxos_lldp_interfaces_overridden(self): set_module_args( dict( - config=[dict(name="Ethernet1/4", receive=True, transmit=False)], + config=[ + dict(name="Ethernet1/4", receive=True, transmit=False) + ], state="overridden", ), ) @@ -184,7 +192,9 @@ def test_nxos_lldp_interfaces_overridden_idempotent(self): self.execute_module(changed=False, commands=[]) def test_nxos_lldp_interfaces_deleted_intf(self): - set_module_args(dict(config=[dict(name="Ethernet1/2")], state="deleted")) + set_module_args( + dict(config=[dict(name="Ethernet1/2")], state="deleted") + ) commands = [ "interface Ethernet1/2", "lldp receive", @@ -227,7 +237,9 @@ def test_nxos_lldp_interfaces_rendered(self): "lldp tlv-set vlan 12", ] result = self.execute_module(changed=False) - self.assertEqual(sorted(result["rendered"]), sorted(commands), result["rendered"]) + self.assertEqual( + sorted(result["rendered"]), sorted(commands), result["rendered"] + ) def test_nxos_lldp_interfaces_parsed(self): set_module_args( diff --git a/tests/unit/modules/network/nxos/test_nxos_logging_global.py b/tests/unit/modules/network/nxos/test_nxos_logging_global.py index aea13fc94..a6d1cd1bf 100644 --- a/tests/unit/modules/network/nxos/test_nxos_logging_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_logging_global.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.logging_global.logging_global.Logging_globalFacts.get_config", @@ -236,7 +238,9 @@ def test_nxos_logging_global_linear_merged_3(self): origin_id=dict(hostname=True), ip=dict( access_list=dict( - cache=dict(entries=16384, interval=200, threshold=80), + cache=dict( + entries=16384, interval=200, threshold=80 + ), detailed=True, include=dict(sgt=True), ), @@ -281,7 +285,9 @@ def test_nxos_logging_global_linear_merged_3_idempotent(self): origin_id=dict(hostname=True), ip=dict( access_list=dict( - cache=dict(entries=16384, interval=200, threshold=80), + cache=dict( + entries=16384, interval=200, threshold=80 + ), detailed=True, include=dict(sgt=True), ), @@ -314,7 +320,11 @@ def test_nxos_logging_global_linear_replaced_3(self): dict( config=dict( origin_id=dict(ip="192.168.1.1"), - ip=dict(access_list=dict(cache=dict(entries=16384, interval=210))), + ip=dict( + access_list=dict( + cache=dict(entries=16384, interval=210) + ) + ), source_interface="Ethernet1/120", ), state="replaced", @@ -520,7 +530,9 @@ def test_nxos_logging_global_event_replaced(self): self.assertEqual(set(result["commands"]), set(commands)) def test_nxos_logging_global_gathered_empty(self): - set_module_args(dict(running_config="", state="gathered"), ignore_provider_arg) + set_module_args( + dict(running_config="", state="gathered"), ignore_provider_arg + ) result = self.execute_module(changed=False) self.assertEqual(result["gathered"], {}) @@ -548,7 +560,9 @@ def test_nxos_logging_global_gathered(self): "rate_limit": "disabled", "rfc_strict": True, "origin_id": {"string": "nodeA"}, - "facilities": [{"facility": "vlan_mgr", "severity": "notification"}], + "facilities": [ + {"facility": "vlan_mgr", "severity": "notification"} + ], } result = self.execute_module(changed=False) self.assertEqual(result["gathered"], gathered) @@ -567,7 +581,9 @@ def test_nxos_logging_global_parsed(self): logging origin-id string nodeA """, ) - set_module_args(dict(running_config=cfg, state="parsed"), ignore_provider_arg) + set_module_args( + dict(running_config=cfg, state="parsed"), ignore_provider_arg + ) parsed = { "console": {"severity": "alert"}, "module": {"severity": "notification"}, @@ -596,7 +612,9 @@ def test_nxos_logging_global_hosts_merged(self): facility="auth", port=5891, use_vrf="default", - secure=dict(trustpoint=dict(client_identity="test")), + secure=dict( + trustpoint=dict(client_identity="test") + ), ), dict(host="192.168.1.2"), dict(host="192.168.1.3", severity="critical"), @@ -633,7 +651,9 @@ def test_nxos_logging_global_hosts_replaced(self): facility="auth", port=5891, use_vrf="default", - secure=dict(trustpoint=dict(client_identity="test")), + secure=dict( + trustpoint=dict(client_identity="test") + ), ), dict( host="192.168.1.3", @@ -719,7 +739,9 @@ def test_nxos_logging_global_event_replaced_2(self): ) set_module_args( dict( - config=dict(event=dict(trunk_status=dict(enable=False, default=True))), + config=dict( + event=dict(trunk_status=dict(enable=False, default=True)) + ), state="replaced", ), ignore_provider_arg, diff --git a/tests/unit/modules/network/nxos/test_nxos_ntp_global.py b/tests/unit/modules/network/nxos/test_nxos_ntp_global.py index 7c49d8668..dd05f62e8 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ntp_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_ntp_global.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ntp_global.ntp_global.Ntp_globalFacts.get_config", @@ -326,7 +328,9 @@ def test_nxos_ntp_global_complex_2_merged(self): prefer=True, ), dict(peer="192.168.1.2", key_id=3, use_vrf="siteB"), - dict(peer="192.168.1.3", maxpoll=10, use_vrf="default"), + dict( + peer="192.168.1.3", maxpoll=10, use_vrf="default" + ), ], servers=[ dict( @@ -338,7 +342,9 @@ def test_nxos_ntp_global_complex_2_merged(self): prefer=True, ), dict(server="203.0.113.2", key_id=3, use_vrf="siteB"), - dict(server="203.0.113.3", maxpoll=10, use_vrf="default"), + dict( + server="203.0.113.3", maxpoll=10, use_vrf="default" + ), ], ), state="merged", @@ -560,7 +566,9 @@ def test_nxos_ntp_global_complex_3_replaced(self): self.assertEqual(set(result["commands"]), set(commands)) def test_nxos_ntp_global_gathered_empty(self): - set_module_args(dict(running_config="", state="gathered"), ignore_provider_arg) + set_module_args( + dict(running_config="", state="gathered"), ignore_provider_arg + ) result = self.execute_module(changed=False) self.assertEqual(result["gathered"], {}) @@ -594,7 +602,9 @@ def test_nxos_ntp_global_parsed(self): ntp source-interface 192.168.1.100 """, ) - set_module_args(dict(running_config=cfg, state="parsed"), ignore_provider_arg) + set_module_args( + dict(running_config=cfg, state="parsed"), ignore_provider_arg + ) parsed = { "trusted_keys": [ {"key_id": 1001}, diff --git a/tests/unit/modules/network/nxos/test_nxos_nxapi.py b/tests/unit/modules/network/nxos/test_nxos_nxapi.py index 7eb12a21c..e9f8e8b6c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_nxapi.py +++ b/tests/unit/modules/network/nxos/test_nxos_nxapi.py @@ -90,7 +90,9 @@ def test_nxos_nxapi_no_change(self): def test_nxos_nxapi_disable(self): set_module_args(dict(state="absent")) - self.execute_module_devices(changed=True, commands=["no feature nxapi"]) + self.execute_module_devices( + changed=True, commands=["no feature nxapi"] + ) def test_nxos_nxapi_no_http(self): set_module_args(dict(https=True, http=False, https_port=8443)) diff --git a/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py index f22889574..c89edc747 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py @@ -50,7 +50,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ospf_interfaces.ospf_interfaces.Ospf_interfacesFacts.get_config", @@ -397,13 +399,19 @@ def test_nxos_ospf_interfaces_af_multiareas_merged(self): dict( name="Ethernet1/1", address_family=[ - dict(afi="ipv4", multi_areas=["1.1.1.1", "1.1.1.3"]), - dict(afi="ipv6", multi_areas=["3.3.3.3", "4.4.4.4"]), + dict( + afi="ipv4", multi_areas=["1.1.1.1", "1.1.1.3"] + ), + dict( + afi="ipv6", multi_areas=["3.3.3.3", "4.4.4.4"] + ), ], ), dict( name="Ethernet1/2", - address_family=[dict(afi="ipv6", multi_areas=["5.5.5.6"])], + address_family=[ + dict(afi="ipv6", multi_areas=["5.5.5.6"]) + ], ), ], state="merged", @@ -446,8 +454,12 @@ def test_nxos_ospf_interfaces_af_multiareas_replaced(self): dict( name="Ethernet1/1", address_family=[ - dict(afi="ipv4", multi_areas=["1.1.1.1", "1.1.1.3"]), - dict(afi="ipv6", multi_areas=["3.3.3.3", "4.4.4.4"]), + dict( + afi="ipv4", multi_areas=["1.1.1.1", "1.1.1.3"] + ), + dict( + afi="ipv6", multi_areas=["3.3.3.3", "4.4.4.4"] + ), ], ), dict(name="Ethernet1/2"), @@ -495,21 +507,31 @@ def test_nxos_ospf_interfaces_authentication_merged(self): address_family=[ dict( afi="ipv4", - authentication=dict(key_chain="test-1", message_digest=True), + authentication=dict( + key_chain="test-1", message_digest=True + ), ), ], ), dict( name="Ethernet1/2", - address_family=[dict(afi="ipv4", authentication=dict(null_auth=True))], + address_family=[ + dict( + afi="ipv4", authentication=dict(null_auth=True) + ) + ], ), dict( name="Ethernet1/3", - address_family=[dict(afi="ipv4", authentication=dict(enable=True))], + address_family=[ + dict(afi="ipv4", authentication=dict(enable=True)) + ], ), dict( name="Ethernet1/4", - address_family=[dict(afi="ipv4", authentication=dict(enable=False))], + address_family=[ + dict(afi="ipv4", authentication=dict(enable=False)) + ], ), ], state="merged", @@ -553,11 +575,17 @@ def test_nxos_ospf_interfaces_authentication_replaced(self): dict(name="Ethernet1/1"), dict( name="Ethernet1/2", - address_family=[dict(afi="ipv4", authentication=dict(null_auth=True))], + address_family=[ + dict( + afi="ipv4", authentication=dict(null_auth=True) + ) + ], ), dict( name="Ethernet1/3", - address_family=[dict(afi="ipv4", authentication=dict(enable=True))], + address_family=[ + dict(afi="ipv4", authentication=dict(enable=True)) + ], ), ], state="replaced", @@ -600,7 +628,9 @@ def test_nxos_ospf_interfaces_authentication_key_merged(self): address_family=[ dict( afi="ipv4", - authentication_key=dict(encryption=3, key="77840f9d4d882176"), + authentication_key=dict( + encryption=3, key="77840f9d4d882176" + ), ), ], ), @@ -609,7 +639,9 @@ def test_nxos_ospf_interfaces_authentication_key_merged(self): address_family=[ dict( afi="ipv4", - authentication_key=dict(encryption=0, key="password"), + authentication_key=dict( + encryption=0, key="password" + ), ), ], ), @@ -618,7 +650,9 @@ def test_nxos_ospf_interfaces_authentication_key_merged(self): address_family=[ dict( afi="ipv4", - authentication_key=dict(encryption=7, key="712090404011C031628"), + authentication_key=dict( + encryption=7, key="712090404011C031628" + ), ), ], ), @@ -664,7 +698,9 @@ def test_nxos_ospf_interfaces_authentication_key_replaced(self): address_family=[ dict( afi="ipv4", - authentication_key=dict(encryption=0, key="password"), + authentication_key=dict( + encryption=0, key="password" + ), ), ], ), @@ -719,7 +755,9 @@ def test_nxos_ospf_interfaces_message_digest_key_merged(self): address_family=[ dict( afi="ipv4", - message_digest_key=dict(key_id=1, encryption=0, key="password"), + message_digest_key=dict( + key_id=1, encryption=0, key="password" + ), ), ], ), @@ -778,7 +816,9 @@ def test_nxos_ospf_interfaces_message_digest_key_replaced(self): address_family=[ dict( afi="ipv4", - message_digest_key=dict(key_id=1, encryption=0, key="password1"), + message_digest_key=dict( + key_id=1, encryption=0, key="password1" + ), ), ], ), @@ -891,11 +931,15 @@ def test_nxos_ospf_interfaces_linear_args_1_replaced(self): config=[ dict( name="Ethernet1/1", - address_family=[dict(afi="ipv4", cost=200, hello_interval=9000)], + address_family=[ + dict(afi="ipv4", cost=200, hello_interval=9000) + ], ), dict( name="Ethernet1/2", - address_family=[dict(afi="ipv6", cost=180, dead_interval=3000)], + address_family=[ + dict(afi="ipv6", cost=180, dead_interval=3000) + ], ), ], state="replaced", @@ -1180,7 +1224,9 @@ def test_nxos_ospf_interfaces_linear_args_4_merged(self): dict( name="Ethernet1/1", address_family=[ - dict(afi="ipv4", shutdown=False, transmit_delay=210), + dict( + afi="ipv4", shutdown=False, transmit_delay=210 + ), dict(afi="ipv6", shutdown=True), ], ), @@ -1194,8 +1240,12 @@ def test_nxos_ospf_interfaces_linear_args_4_merged(self): dict( name="Ethernet1/3", address_family=[ - dict(afi="ipv4", shutdown=True, transmit_delay=430), - dict(afi="ipv6", shutdown=True, transmit_delay=120), + dict( + afi="ipv4", shutdown=True, transmit_delay=430 + ), + dict( + afi="ipv6", shutdown=True, transmit_delay=120 + ), ], ), ], @@ -1320,7 +1370,9 @@ def test_nxos_ospf_interfaces_parsed(self): "address_family": [ { "afi": "ipv6", - "processes": [{"process_id": "210", "multi_areas": ["3.3.3.3"]}], + "processes": [ + {"process_id": "210", "multi_areas": ["3.3.3.3"]} + ], }, ], }, @@ -1380,7 +1432,9 @@ def test_nxos_ospf_interfaces_gathered(self): "address_family": [ { "afi": "ipv6", - "processes": [{"process_id": "210", "multi_areas": ["3.3.3.3"]}], + "processes": [ + {"process_id": "210", "multi_areas": ["3.3.3.3"]} + ], }, ], }, @@ -1426,7 +1480,9 @@ def test_nxos_ospf_interfaces_overridden(self): dict( name="Ethernet1/1", address_family=[ - dict(afi="ipv4", shutdown=False, transmit_delay=300), + dict( + afi="ipv4", shutdown=False, transmit_delay=300 + ), dict(afi="ipv6", shutdown=True), ], ), @@ -1542,15 +1598,21 @@ def test_nxos_ospf_interfaces_passive_intf(self): ), dict( name="Ethernet1/2", - address_family=[dict(afi="ipv4", default_passive_interface=True)], + address_family=[ + dict(afi="ipv4", default_passive_interface=True) + ], ), dict( name="Ethernet1/3", - address_family=[dict(afi="ipv6", default_passive_interface=True)], + address_family=[ + dict(afi="ipv6", default_passive_interface=True) + ], ), dict( name="Ethernet1/4", - address_family=[dict(afi="ipv4", default_passive_interface=True)], + address_family=[ + dict(afi="ipv4", default_passive_interface=True) + ], ), ], state="merged", diff --git a/tests/unit/modules/network/nxos/test_nxos_ospfv2.py b/tests/unit/modules/network/nxos/test_nxos_ospfv2.py index 175570499..db3ca64d7 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ospfv2.py +++ b/tests/unit/modules/network/nxos/test_nxos_ospfv2.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ospfv2.ospfv2.Ospfv2Facts.get_config", @@ -82,8 +84,12 @@ def test_nxos_ospfv2_merged(self): dict( area_id="0.0.0.100", filter_list=[ - dict(route_map="rmap_1", direction="in"), - dict(route_map="rmap_2", direction="out"), + dict( + route_map="rmap_1", direction="in" + ), + dict( + route_map="rmap_2", direction="out" + ), ], ranges=[ dict(prefix="198.51.100.64/27"), @@ -161,8 +167,12 @@ def test_nxos_ospfv2_merged_idempotent(self): dict( area_id="0.0.0.100", filter_list=[ - dict(route_map="rmap_1", direction="in"), - dict(route_map="rmap_2", direction="out"), + dict( + route_map="rmap_1", direction="in" + ), + dict( + route_map="rmap_2", direction="out" + ), ], ranges=[ dict(prefix="198.51.100.64/27"), @@ -324,8 +334,12 @@ def test_nxos_ospfv2_replaced_idempotent(self): dict( area_id="0.0.0.100", filter_list=[ - dict(route_map="rmap_1", direction="in"), - dict(route_map="rmap_2", direction="out"), + dict( + route_map="rmap_1", direction="in" + ), + dict( + route_map="rmap_2", direction="out" + ), ], ranges=[ dict(prefix="198.51.100.64/27"), @@ -365,7 +379,11 @@ def test_nxos_ospfv2_overridden(self): ) set_module_args( dict( - config=dict(processes=[dict(process_id="300", router_id="203.0.113.20")]), + config=dict( + processes=[ + dict(process_id="300", router_id="203.0.113.20") + ] + ), state="overridden", ), ignore_provider_arg, @@ -421,8 +439,12 @@ def test_nxos_ospfv2_overridden_idempotent(self): dict( area_id="0.0.0.100", filter_list=[ - dict(route_map="rmap_1", direction="in"), - dict(route_map="rmap_2", direction="out"), + dict( + route_map="rmap_1", direction="in" + ), + dict( + route_map="rmap_2", direction="out" + ), ], ranges=[ dict(prefix="198.51.100.64/27"), @@ -464,7 +486,9 @@ def test_nxos_ospfv2_deleted(self): ) set_module_args( dict( - config=dict(processes=[dict(process_id="100"), dict(process_id="300")]), + config=dict( + processes=[dict(process_id="100"), dict(process_id="300")] + ), state="deleted", ), ignore_provider_arg, @@ -494,7 +518,9 @@ def test_nxos_ospfv2_deleted_idempotent(self): ) set_module_args( dict( - config=dict(processes=[dict(process_id="400"), dict(process_id="500")]), + config=dict( + processes=[dict(process_id="400"), dict(process_id="500")] + ), state="deleted", ), ignore_provider_arg, diff --git a/tests/unit/modules/network/nxos/test_nxos_ospfv3.py b/tests/unit/modules/network/nxos/test_nxos_ospfv3.py index 70a2ae47e..8f90dd9a6 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ospfv3.py +++ b/tests/unit/modules/network/nxos/test_nxos_ospfv3.py @@ -53,7 +53,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ospfv3.ospfv3.Ospfv3Facts.get_config", @@ -231,7 +233,9 @@ def test_nxos_ospfv3_af_areas_ranges_merged(self): dict( area_id="1.1.1.2", ranges=[ - dict(prefix="2001:db4::/32", cost=11), + dict( + prefix="2001:db4::/32", cost=11 + ), dict( prefix="2001:db5::/32", not_advertise=True, @@ -286,7 +290,9 @@ def test_nxos_ospfv3_af_areas_ranges_replaced(self): dict( area_id="1.1.1.2", ranges=[ - dict(prefix="2001:db4::/32", cost=11), + dict( + prefix="2001:db4::/32", cost=11 + ), dict( prefix="2001:db5::/32", not_advertise=True, @@ -376,7 +382,9 @@ def test_nxos_ospfv3_af_areas_default_cost_replaced(self): address_family=dict( afi="ipv6", safi="unicast", - areas=[dict(area_id="1.1.1.2", default_cost=200)], + areas=[ + dict(area_id="1.1.1.2", default_cost=200) + ], ), ), ], @@ -413,7 +421,9 @@ def test_nxos_ospfv3_af_default_information_merged(self): afi="ipv6", safi="unicast", default_information=dict( - originate=dict(always=True, route_map="test-2"), + originate=dict( + always=True, route_map="test-2" + ), ), ), ), @@ -449,7 +459,9 @@ def test_nxos_ospfv3_af_default_information_merged_2(self): address_family=dict( afi="ipv6", safi="unicast", - default_information=dict(originate=dict(set=False)), + default_information=dict( + originate=dict(set=False) + ), ), ), ], @@ -484,7 +496,9 @@ def test_nxos_ospfv3_af_default_information_replaced(self): address_family=dict( afi="ipv6", safi="unicast", - default_information=dict(originate=dict(set=True)), + default_information=dict( + originate=dict(set=True) + ), ), ), ], @@ -516,7 +530,9 @@ def test_nxos_ospfv3_af_distance_merged(self): processes=[ dict( process_id="100", - address_family=dict(afi="ipv6", safi="unicast", distance=35), + address_family=dict( + afi="ipv6", safi="unicast", distance=35 + ), ), ], ), @@ -580,7 +596,9 @@ def test_nxos_ospfv3_af_maximum_paths_merged(self): processes=[ dict( process_id="100", - address_family=dict(afi="ipv6", safi="unicast", maximum_paths=27), + address_family=dict( + afi="ipv6", safi="unicast", maximum_paths=27 + ), ), ], ), @@ -663,7 +681,9 @@ def test_nxos_ospfv3_af_redistribute_merged(self): id="65563", route_map="test-3", ), - dict(protocol="static", route_map="test-4"), + dict( + protocol="static", route_map="test-4" + ), ], ), ), @@ -713,7 +733,9 @@ def test_nxos_ospfv3_af_redistribute_replaced(self): id="65563", route_map="test-3", ), - dict(protocol="static", route_map="test-4"), + dict( + protocol="static", route_map="test-4" + ), ], ), ), @@ -989,7 +1011,11 @@ def test_nxos_ospfv3_areas_nssa_merged(self): no_summary=True, no_redistribution=True, route_map="test-1", - translate=dict(type7=dict(always=True, supress_fa=True)), + translate=dict( + type7=dict( + always=True, supress_fa=True + ) + ), ), ), ], @@ -1024,7 +1050,9 @@ def test_nxos_ospfv3_areas_nssa_merged_2(self): processes=[ dict( process_id="100", - areas=[dict(area_id="1.1.1.1", nssa=dict(set=False))], + areas=[ + dict(area_id="1.1.1.1", nssa=dict(set=False)) + ], ), ], ), @@ -1155,7 +1183,11 @@ def test_nxos_ospfv3_areas_stub_replaced(self): ) set_module_args( dict( - config=dict(processes=[dict(process_id="100", areas=[dict(area_id="1.1.1.3")])]), + config=dict( + processes=[ + dict(process_id="100", areas=[dict(area_id="1.1.1.3")]) + ] + ), state="replaced", ), ignore_provider_arg, @@ -1178,7 +1210,9 @@ def test_nxos_ospfv3_autocost_flush_route_isolate_merged(self): processes=[ dict( process_id="100", - auto_cost=dict(reference_bandwidth=100, unit="Gbps"), + auto_cost=dict( + reference_bandwidth=100, unit="Gbps" + ), flush_routes=True, isolate=True, ), @@ -1411,7 +1445,9 @@ def test_nxos_ospfv3_graceful_restart_merged(self): processes=[ dict( process_id="100", - graceful_restart=dict(grace_period=50, helper_disable=True), + graceful_restart=dict( + grace_period=50, helper_disable=True + ), ), dict( process_id="102", @@ -1496,7 +1532,11 @@ def test_nxos_ospfv3_max_metric_merged(self): dict( process_id="102", max_metric=dict( - router_lsa=dict(inter_area_prefix_lsa=dict(max_metric_value=1800)), + router_lsa=dict( + inter_area_prefix_lsa=dict( + max_metric_value=1800 + ) + ), ), ), dict( @@ -1741,7 +1781,9 @@ def test_nxos_ospfv3_vrf_merged(self): wait_period=1200, wait_for_bgp_asn=65563, ), - inter_area_prefix_lsa=dict(set=True), + inter_area_prefix_lsa=dict( + set=True + ), ), ), ), @@ -2120,7 +2162,9 @@ def test_nxos_ospfv3_parsed(self): {"vrf": "blue", "router_id": "10.0.0.2"}, { "vrf": "red", - "areas": [{"area_id": "1.1.1.1", "nssa": {"set": True}}], + "areas": [ + {"area_id": "1.1.1.1", "nssa": {"set": True}} + ], }, ], }, @@ -2171,7 +2215,9 @@ def test_nxos_ospfv3_gathered(self): {"vrf": "blue", "router_id": "10.0.0.2"}, { "vrf": "red", - "areas": [{"area_id": "1.1.1.1", "nssa": {"set": True}}], + "areas": [ + {"area_id": "1.1.1.1", "nssa": {"set": True}} + ], }, ], }, diff --git a/tests/unit/modules/network/nxos/test_nxos_overlay_global.py b/tests/unit/modules/network/nxos/test_nxos_overlay_global.py index 976aa0964..f464094bc 100644 --- a/tests/unit/modules/network/nxos/test_nxos_overlay_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_overlay_global.py @@ -49,7 +49,9 @@ def tearDown(self): self.mock_get_config.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("", "nxos_overlay_global_config.cfg") + self.get_config.return_value = load_fixture( + "", "nxos_overlay_global_config.cfg" + ) self.load_config.return_value = None def test_nxos_overlay_global_up(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_pim.py b/tests/unit/modules/network/nxos/test_nxos_pim.py index eea384836..8ef0a7360 100644 --- a/tests/unit/modules/network/nxos/test_nxos_pim.py +++ b/tests/unit/modules/network/nxos/test_nxos_pim.py @@ -56,13 +56,17 @@ def test_nxos_pim_1(self): # Add/ Modify self.get_config.return_value = load_fixture("nxos_pim", "config.cfg") set_module_args(dict(ssm_range="233.0.0.0/8")) - self.execute_module(changed=True, commands=["ip pim ssm range 233.0.0.0/8"]) + self.execute_module( + changed=True, commands=["ip pim ssm range 233.0.0.0/8"] + ) def test_nxos_pim_2(self): # Remove existing values self.get_config.return_value = load_fixture("nxos_pim", "config.cfg") set_module_args(dict(bfd="disable", ssm_range="none")) - self.execute_module(changed=True, commands=["no ip pim bfd", "ip pim ssm range none"]) + self.execute_module( + changed=True, commands=["no ip pim bfd", "ip pim ssm range none"] + ) def test_nxos_pim_3(self): # bfd None (disable)-> enable @@ -88,7 +92,9 @@ def test_nxos_pim_5(self): # SSM 'default' self.get_config.return_value = load_fixture("nxos_pim", "config.cfg") set_module_args(dict(ssm_range="default")) - self.execute_module(changed=True, commands=["no ip pim ssm range none"]) + self.execute_module( + changed=True, commands=["no ip pim ssm range none"] + ) # SSM 'default' idempotence self.get_config.return_value = None diff --git a/tests/unit/modules/network/nxos/test_nxos_pim_interface.py b/tests/unit/modules/network/nxos/test_nxos_pim_interface.py index b746b8b46..54dcac3ce 100644 --- a/tests/unit/modules/network/nxos/test_nxos_pim_interface.py +++ b/tests/unit/modules/network/nxos/test_nxos_pim_interface.py @@ -65,7 +65,12 @@ def load_from_file(*args, **kwargs): for command in commands: if isinstance(command, dict): command = command["command"] - filename = str(command).split(" | ", 1)[0].replace(" ", "_").replace("/", "_") + filename = ( + str(command) + .split(" | ", 1)[0] + .replace(" ", "_") + .replace("/", "_") + ) output.append(load_fixture(module_name, filename)) return output @@ -161,7 +166,9 @@ def test_bfd_1(self): # default (None) -> enable self.get_config.return_value = None set_module_args(dict(interface="eth2/1", bfd="enable")) - self.execute_module(changed=True, commands=["interface eth2/1", "ip pim bfd-instance"]) + self.execute_module( + changed=True, commands=["interface eth2/1", "ip pim bfd-instance"] + ) # default (None) -> disable set_module_args(dict(interface="eth2/1", bfd="disable")) diff --git a/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py b/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py index f4dbd13ac..2e30bf402 100644 --- a/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py +++ b/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py @@ -50,12 +50,16 @@ def tearDown(self): self.mock_get_config.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("nxos_pim_rp_address", "config.cfg") + self.get_config.return_value = load_fixture( + "nxos_pim_rp_address", "config.cfg" + ) self.load_config.return_value = None def test_nxos_pim_rp_address(self): set_module_args(dict(rp_address="5.6.7.8")) - self.execute_module(changed=True, commands=["ip pim rp-address 5.6.7.8"]) + self.execute_module( + changed=True, commands=["ip pim rp-address 5.6.7.8"] + ) def test_nxos_pim_rp_address_no_change(self): set_module_args(dict(rp_address="1.2.3.4")) @@ -63,7 +67,9 @@ def test_nxos_pim_rp_address_no_change(self): def test_nxos_pim_rp_address_absent(self): set_module_args(dict(rp_address="1.2.3.4", state="absent")) - self.execute_module(changed=True, commands=["no ip pim rp-address 1.2.3.4"]) + self.execute_module( + changed=True, commands=["no ip pim rp-address 1.2.3.4"] + ) def test_nxos_pim_rp_address_absent_no_change(self): set_module_args(dict(rp_address="5.6.7.8", state="absent")) diff --git a/tests/unit/modules/network/nxos/test_nxos_ping.py b/tests/unit/modules/network/nxos/test_nxos_ping.py index bdaabe881..49eaf7051 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ping.py +++ b/tests/unit/modules/network/nxos/test_nxos_ping.py @@ -64,7 +64,9 @@ def test_nxos_ping_expected_success(self): ] set_module_args(dict(dest="172.28.128.7", vrf="management")) result = self.execute_module() - self.assertEqual(result["commands"], ["ping 172.28.128.7 count 5 vrf management"]) + self.assertEqual( + result["commands"], ["ping 172.28.128.7 count 5 vrf management"] + ) self.assertEqual(result["packet_loss"], "0.00%") self.assertEqual(result["packets_rx"], 5) self.assertEqual(result["packets_tx"], 5) @@ -86,7 +88,9 @@ def test_nxos_ping_expected_failure(self): 5 packets transmitted, 0 packets received, 100.00% packet loss """, ] - set_module_args(dict(dest="172.28.128.8", vrf="management", state="absent")) + set_module_args( + dict(dest="172.28.128.8", vrf="management", state="absent") + ) self.execute_module(failed=False) def test_nxos_ping_expected_success_but_failed(self): @@ -122,7 +126,9 @@ def test_nxos_ping_expected_failure_but_succeeded(self): round-trip min/avg/max = 1.597/2.32/4.197 ms """, ] - set_module_args(dict(dest="172.28.128.7", vrf="management", state="absent")) + set_module_args( + dict(dest="172.28.128.7", vrf="management", state="absent") + ) result = self.execute_module(failed=True) self.assertEqual(result["msg"], "Ping succeeded unexpectedly") @@ -171,7 +177,9 @@ def test_nxos_ping_expected_success_df_bit(self): ] set_module_args(dict(dest="172.28.128.7", df_bit=True)) result = self.execute_module() - self.assertEqual(result["commands"], ["ping 172.28.128.7 count 5 df-bit"]) + self.assertEqual( + result["commands"], ["ping 172.28.128.7 count 5 df-bit"] + ) def test_nxos_ping_expected_success_size(self): self.run_commands.return_value = [ @@ -190,7 +198,9 @@ def test_nxos_ping_expected_success_size(self): ] set_module_args(dict(dest="172.28.128.7", size=65468)) result = self.execute_module() - self.assertEqual(result["commands"], ["ping 172.28.128.7 count 5 packet-size 65468"]) + self.assertEqual( + result["commands"], ["ping 172.28.128.7 count 5 packet-size 65468"] + ) def test_nxos_ping_expected_success_all(self): self.run_commands.return_value = [ @@ -259,4 +269,6 @@ def test_nxos_ping_failed_error(self): self.run_commands.return_value = [""""""] set_module_args(dict(dest="172.28.128.7", count=10, vrf="site-1")) result = self.execute_module(failed=True) - self.assertEqual(result["msg"], "An unexpected error occurred. Check all params.") + self.assertEqual( + result["msg"], "An unexpected error occurred. Check all params." + ) diff --git a/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py b/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py index d94f0b3e0..6414e048f 100644 --- a/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py +++ b/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py @@ -53,7 +53,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.prefix_lists.prefix_lists.Prefix_listsFacts.get_config", @@ -557,15 +559,21 @@ def test_nxos_prefix_lists_parsed(self): ipv6 prefix-list plist3 description Test plist3 """, ) - set_module_args(dict(running_config=cfg, state="parsed"), ignore_provider_arg) + set_module_args( + dict(running_config=cfg, state="parsed"), ignore_provider_arg + ) parsed = [ { "afi": "ipv4", - "prefix_lists": [{"name": "plist1", "description": "Test plist1"}], + "prefix_lists": [ + {"name": "plist1", "description": "Test plist1"} + ], }, { "afi": "ipv6", - "prefix_lists": [{"name": "plist3", "description": "Test plist3"}], + "prefix_lists": [ + {"name": "plist3", "description": "Test plist3"} + ], }, ] result = self.execute_module(changed=False) diff --git a/tests/unit/modules/network/nxos/test_nxos_route_maps.py b/tests/unit/modules/network/nxos/test_nxos_route_maps.py index 06d76fe38..8441d06bc 100644 --- a/tests/unit/modules/network/nxos/test_nxos_route_maps.py +++ b/tests/unit/modules/network/nxos/test_nxos_route_maps.py @@ -53,7 +53,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.route_maps.route_maps.Route_mapsFacts.get_config", @@ -88,7 +90,9 @@ def test_nxos_route_maps_linear_merged(self): sequence=40, description="rmap1-deny-40", set=dict( - as_path=dict(prepend=dict(last_as=10), tag=True), + as_path=dict( + prepend=dict(last_as=10), tag=True + ), comm_list="comm1", dampening=dict( half_life=10, @@ -111,11 +115,15 @@ def test_nxos_route_maps_linear_merged(self): set=dict( null_interface="null0", ip=dict( - address=dict(prefix_list="prefixlist1"), + address=dict( + prefix_list="prefixlist1" + ), precedence="critical", ), ipv6=dict( - address=dict(prefix_list="prefixlist2"), + address=dict( + prefix_list="prefixlist2" + ), precedence="immediate", ), label_index=20, @@ -226,7 +234,9 @@ def test_nxos_route_maps_linear_merged_idempotent(self): sequence=40, description="rmap1-deny-40", set=dict( - as_path=dict(prepend=dict(last_as=10), tag=True), + as_path=dict( + prepend=dict(last_as=10), tag=True + ), comm_list="comm1", dampening=dict( half_life=10, @@ -249,11 +259,15 @@ def test_nxos_route_maps_linear_merged_idempotent(self): set=dict( null_interface="null0", ip=dict( - address=dict(prefix_list="prefixlist1"), + address=dict( + prefix_list="prefixlist1" + ), precedence="critical", ), ipv6=dict( - address=dict(prefix_list="prefixlist2"), + address=dict( + prefix_list="prefixlist2" + ), precedence="immediate", ), label_index=20, @@ -351,7 +365,9 @@ def test_nxos_route_maps_linear_replaced(self): action="deny", set=dict( ip=dict( - address=dict(prefix_list="prefixlist1"), + address=dict( + prefix_list="prefixlist1" + ), precedence="critical", ), ), @@ -422,7 +438,9 @@ def test_nxos_route_maps_parsed(self): action="deny", sequence=40, description="rmap1-deny-40", - set=dict(as_path=dict(prepend=dict(last_as=10), tag=True)), + set=dict( + as_path=dict(prepend=dict(last_as=10), tag=True) + ), ), ], ), @@ -488,7 +506,9 @@ def test_nxos_route_maps_gathered(self): action="deny", sequence=40, description="rmap1-deny-40", - set=dict(as_path=dict(prepend=dict(last_as=10), tag=True)), + set=dict( + as_path=dict(prepend=dict(last_as=10), tag=True) + ), ), ], ), @@ -551,7 +571,9 @@ def test_nxos_route_maps_rendered(self): action="deny", set=dict( ip=dict( - address=dict(prefix_list="prefixlist1"), + address=dict( + prefix_list="prefixlist1" + ), precedence="critical", ), ), @@ -618,7 +640,9 @@ def test_nxos_route_maps_overridden(self): description="rmap1-deny-40", set=dict( ipv6=dict( - address=dict(prefix_list="prefixlist2"), + address=dict( + prefix_list="prefixlist2" + ), precedence="immediate", ), ), @@ -742,7 +766,9 @@ def test_nxos_route_maps_complex_merged(self): as_path_list=["acl1", "acl2"], ), as_path=["65565", "65578", "65590"], - community=dict(community_list=["comm1", "comm2"]), + community=dict( + community_list=["comm1", "comm2"] + ), evpn=dict(route_types=["1", "2-mac-ip"]), extcommunity=dict( extcommunity_list=[ @@ -764,8 +790,12 @@ def test_nxos_route_maps_complex_merged(self): ), source="192.168.1.0/24", ), - next_hop=dict(prefix_lists=["pl1", "pl2"]), - route_source=dict(prefix_lists=["pl3", "pl4"]), + next_hop=dict( + prefix_lists=["pl1", "pl2"] + ), + route_source=dict( + prefix_lists=["pl3", "pl4"] + ), ), mac_list=["mac1", "mac2"], metric=[100, 200], @@ -792,8 +822,12 @@ def test_nxos_route_maps_complex_merged(self): ), source="192.168.1.0/24", ), - next_hop=dict(prefix_lists=["pl1", "pl2"]), - route_source=dict(prefix_lists=["pl3", "pl4"]), + next_hop=dict( + prefix_lists=["pl1", "pl2"] + ), + route_source=dict( + prefix_lists=["pl3", "pl4"] + ), ), ), ), @@ -801,20 +835,28 @@ def test_nxos_route_maps_complex_merged(self): sequence=40, action="permit", set=dict( - as_path=dict(prepend=dict(as_number=["65546", "78878"])), + as_path=dict( + prepend=dict( + as_number=["65546", "78878"] + ) + ), distance=dict( igp_ebgp_routes=10, internal_routes=20, local_routes=90, ), - evpn=dict(gateway_ip=dict(ip="192.168.1.1")), + evpn=dict( + gateway_ip=dict(ip="192.168.1.1") + ), ), ), dict( sequence=52, action="permit", set=dict( - evpn=dict(gateway_ip=dict(use_nexthop=True)), + evpn=dict( + gateway_ip=dict(use_nexthop=True) + ), community=dict( internet=True, number=["655:10", "655:20"], diff --git a/tests/unit/modules/network/nxos/test_nxos_snmp_server.py b/tests/unit/modules/network/nxos/test_nxos_snmp_server.py index 1b7672775..0d49757f2 100644 --- a/tests/unit/modules/network/nxos/test_nxos_snmp_server.py +++ b/tests/unit/modules/network/nxos/test_nxos_snmp_server.py @@ -42,7 +42,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.snmp_server.snmp_server.Snmp_serverFacts.get_config", @@ -68,17 +70,25 @@ def test_nxos_snmp_server_linear_merged(self): context=dict(name="public", vrf="siteA", instance="test"), counter=dict(cache=dict(timeout=1800)), drop=dict(unknown_engine_id=True, unknown_user=True), - engine_id=dict(local="'00:00:00:63:00:01:00:10:20:15:10:03'"), + engine_id=dict( + local="'00:00:00:63:00:01:00:10:20:15:10:03'" + ), communities=[ dict(name="private", group="network-admin"), dict(community="public", use_ipv4acl="myacl"), ], global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict( + community="public", context="public1" + ) + ), packetsize=484, protocol=dict(enable=True), - source_interface=dict(informs="Ethernet1/1", traps="Ethernet1/2"), + source_interface=dict( + informs="Ethernet1/1", traps="Ethernet1/2" + ), system_shutdown=True, tcp_session=dict(auth=True), ), @@ -139,13 +149,21 @@ def test_nxos_snmp_server_linear_merged_idempotent(self): context=dict(name="public", vrf="siteA"), counter=dict(cache=dict(timeout=1800)), drop=dict(unknown_engine_id=True, unknown_user=True), - engine_id=dict(local="00:00:00:63:00:01:00:10:20:15:10:03"), + engine_id=dict( + local="00:00:00:63:00:01:00:10:20:15:10:03" + ), global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict( + community="public", context="public1" + ) + ), packetsize=484, protocol=dict(enable=True), - source_interface=dict(informs="Ethernet1/1", traps="Ethernet1/2"), + source_interface=dict( + informs="Ethernet1/1", traps="Ethernet1/2" + ), system_shutdown=True, tcp_session=dict(auth=True), ), @@ -185,13 +203,21 @@ def test_nxos_snmp_server_linear_replaced(self): contact="testswitch@localhost", context=dict(name="public", vrf="siteA"), counter=dict(cache=dict(timeout=1860)), - engine_id=dict(local="00:00:00:63:00:01:00:10:20:15:10:03"), + engine_id=dict( + local="00:00:00:63:00:01:00:10:20:15:10:03" + ), global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict( + community="public", context="public1" + ) + ), packetsize=484, protocol=dict(enable=True), - source_interface=dict(informs="Ethernet1/3", traps="Ethernet1/2"), + source_interface=dict( + informs="Ethernet1/3", traps="Ethernet1/2" + ), tcp_session=dict(auth=True), ), state="replaced", @@ -238,13 +264,21 @@ def test_nxos_snmp_server_linear_overridden(self): contact="testswitch@localhost", context=dict(name="public", vrf="siteA"), counter=dict(cache=dict(timeout=1860)), - engine_id=dict(local="00:00:00:63:00:01:00:10:20:15:10:03"), + engine_id=dict( + local="00:00:00:63:00:01:00:10:20:15:10:03" + ), global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict( + community="public", context="public1" + ) + ), packetsize=484, protocol=dict(enable=True), - source_interface=dict(informs="Ethernet1/3", traps="Ethernet1/2"), + source_interface=dict( + informs="Ethernet1/3", traps="Ethernet1/2" + ), tcp_session=dict(auth=True), ), state="overridden", @@ -439,7 +473,9 @@ def test_nxos_snmp_server_hosts_merged(self): community="public", traps=True, ), - dict(host="192.168.1.1", source_interface="Ethernet1/1"), + dict( + host="192.168.1.1", source_interface="Ethernet1/1" + ), dict( host="192.168.2.1", version="1", @@ -504,7 +540,9 @@ def test_nxos_snmp_server_hosts_merged(self): community="public", traps=True, ), - dict(host="192.168.1.1", source_interface="Ethernet1/1"), + dict( + host="192.168.1.1", source_interface="Ethernet1/1" + ), dict( host="192.168.2.1", version="1", @@ -561,7 +599,9 @@ def test_nxos_snmp_server_hosts_replaced(self): community="public", traps=True, ), - dict(host="192.168.1.1", source_interface="Ethernet1/1"), + dict( + host="192.168.1.1", source_interface="Ethernet1/1" + ), dict( host="192.168.2.1", version="1", @@ -705,7 +745,9 @@ def test_nxos_snmp_server_users_merged(self): algorithm="md5", password="0x5632724fb8ac3699296af262", engine_id="2:2:2:2:2", - priv=dict(privacy_password="0x5632724fb8ac3699296af262"), + priv=dict( + privacy_password="0x5632724fb8ac3699296af262" + ), localizedv2_key=True, ), ), @@ -883,7 +925,9 @@ def test_nxos_snmp_server_parsed(self): contact="testswitch@localhost", communities=[ dict(name="private", group="network-admin"), - dict(name="public", use_ipv4acl="myacl", use_ipv6acl="myaclv6"), + dict( + name="public", use_ipv4acl="myacl", use_ipv6acl="myaclv6" + ), ], context=dict(name="public", vrf="siteA"), counter=dict(cache=dict(timeout=1800)), @@ -891,7 +935,9 @@ def test_nxos_snmp_server_parsed(self): engine_id=dict(local="00:00:00:63:00:01:00:10:20:15:10:03"), global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict(community="public", context="public1") + ), packetsize=484, protocol=dict(enable=True), source_interface=dict(informs="Ethernet1/1", traps="Ethernet1/2"), @@ -906,7 +952,9 @@ def test_nxos_snmp_server_parsed(self): algorithm="md5", password="0x7d425fbf09417c44bca69e1d9e9ce889", localized_key=True, - priv=dict(privacy_password="0x7d425fbf09417c44bca69e1d9e9ce889"), + priv=dict( + privacy_password="0x7d425fbf09417c44bca69e1d9e9ce889" + ), ), ), dict( @@ -935,16 +983,28 @@ def test_nxos_snmp_server_rendered(self): counter=dict(cache=dict(timeout=1800)), communities=[ dict(name="private", group="network-admin"), - dict(name="public", use_ipv4acl="myacl", use_ipv6acl="myaclv6"), + dict( + name="public", + use_ipv4acl="myacl", + use_ipv6acl="myaclv6", + ), ], drop=dict(unknown_engine_id=True, unknown_user=True), - engine_id=dict(local="'00:00:00:63:00:01:00:10:20:15:10:03'"), + engine_id=dict( + local="'00:00:00:63:00:01:00:10:20:15:10:03'" + ), global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict( + community="public", context="public1" + ) + ), packetsize=484, protocol=dict(enable=True), - source_interface=dict(informs="Ethernet1/1", traps="Ethernet1/2"), + source_interface=dict( + informs="Ethernet1/1", traps="Ethernet1/2" + ), system_shutdown=True, tcp_session=dict(auth=True), ), @@ -1008,7 +1068,9 @@ def test_nxos_snmp_server_gathered(self): engine_id=dict(local="00:00:00:63:00:01:00:10:20:15:10:03"), global_enforce_priv=True, location="lab", - mib=dict(community_map=dict(community="public", context="public1")), + mib=dict( + community_map=dict(community="public", context="public1") + ), packetsize=484, protocol=dict(enable=True), source_interface=dict(informs="Ethernet1/1", traps="Ethernet1/2"), diff --git a/tests/unit/modules/network/nxos/test_nxos_static_routes.py b/tests/unit/modules/network/nxos/test_nxos_static_routes.py index 76ed4a3a9..0c9505b6b 100644 --- a/tests/unit/modules/network/nxos/test_nxos_static_routes.py +++ b/tests/unit/modules/network/nxos/test_nxos_static_routes.py @@ -28,7 +28,9 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = self.mock_get_resource_connection.start() + self.get_resource_connection = ( + self.mock_get_resource_connection.start() + ) self.mock_execute_show_command = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.static_routes.static_routes.Static_routesFacts.get_static_routes_data", @@ -90,7 +92,12 @@ def test_nxos_static_routes_all_idempotent(self): "dest": "192.0.2.16/28", }, { - "next_hops": [{"forward_router_address": "192.0.2.26", "tag": 12}], + "next_hops": [ + { + "forward_router_address": "192.0.2.26", + "tag": 12, + } + ], "dest": "192.0.2.80/28", }, ], @@ -124,7 +131,9 @@ def test_nxos_static_routes_all_idempotent(self): "afi": "ipv4", "routes": [ { - "next_hops": [{"forward_router_address": "192.168.255.1"}], + "next_hops": [ + {"forward_router_address": "192.168.255.1"} + ], "dest": "0.0.0.0/0", }, ], @@ -216,7 +225,10 @@ def test_nxos_static_routes_all_idempotent(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.0.2.22", "tag": 4}, + { + "forward_router_address": "192.0.2.22", + "tag": 4, + }, { "forward_router_address": "192.0.2.23", "admin_distance": 1, @@ -268,7 +280,10 @@ def test_nxos_static_routes_merged(self): }, { "next_hops": [ - {"forward_router_address": "192.0.2.26", "tag": 12}, + { + "forward_router_address": "192.0.2.26", + "tag": 12, + }, ], "dest": "192.0.2.80/28", }, @@ -284,7 +299,9 @@ def test_nxos_static_routes_merged(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.0.2.13"}, + { + "forward_router_address": "192.0.2.13" + }, { "forward_router_address": "192.0.2.14", "admin_distance": 5, @@ -303,7 +320,11 @@ def test_nxos_static_routes_merged(self): "afi": "ipv4", "routes": [ { - "next_hops": [{"forward_router_address": "192.168.255.1"}], + "next_hops": [ + { + "forward_router_address": "192.168.255.1" + } + ], "dest": "0.0.0.0/0", }, ], @@ -395,7 +416,10 @@ def test_nxos_static_routes_merged(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.0.2.22", "tag": 4}, + { + "forward_router_address": "192.0.2.22", + "tag": 4, + }, { "forward_router_address": "192.0.2.23", "admin_distance": 1, @@ -487,7 +511,10 @@ def test_nxos_static_routes_replaced(self): }, { "next_hops": [ - {"forward_router_address": "192.0.2.27", "tag": 13}, + { + "forward_router_address": "192.0.2.27", + "tag": 13, + }, ], "dest": "192.0.2.80/28", }, @@ -582,7 +609,10 @@ def test_nxos_static_routes_overridden(self): }, { "next_hops": [ - {"forward_router_address": "192.0.2.27", "tag": 13}, + { + "forward_router_address": "192.0.2.27", + "tag": 13, + }, ], "dest": "192.0.2.80/28", }, @@ -749,7 +779,11 @@ def test_nxos_static_routes_deleteddest(self): config=[ dict( vrf="Test", - address_families=[dict(afi="ipv4", routes=[dict(dest="192.0.2.48/28")])], + address_families=[ + dict( + afi="ipv4", routes=[dict(dest="192.0.2.48/28")] + ) + ], ), ], state="deleted", @@ -815,7 +849,10 @@ def test_nxos_static_routes_deletedroute(self): }, { "next_hops": [ - {"forward_router_address": "192.0.2.26", "tag": 12}, + { + "forward_router_address": "192.0.2.26", + "tag": 12, + }, ], "dest": "192.0.2.80/28", }, @@ -831,7 +868,9 @@ def test_nxos_static_routes_deletedroute(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.0.2.13"}, + { + "forward_router_address": "192.0.2.13" + }, { "forward_router_address": "192.0.2.14", "admin_distance": 5, @@ -948,7 +987,12 @@ def test_nxos_static_routes_parsed(self): "dest": "192.0.2.16/28", }, { - "next_hops": [{"forward_router_address": "192.0.2.26", "tag": 12}], + "next_hops": [ + { + "forward_router_address": "192.0.2.26", + "tag": 12, + } + ], "dest": "192.0.2.80/28", }, ], @@ -964,7 +1008,10 @@ def test_nxos_static_routes_parsed(self): { "next_hops": [ {"forward_router_address": "192.0.2.13"}, - {"forward_router_address": "192.0.2.14", "admin_distance": 5}, + { + "forward_router_address": "192.0.2.14", + "admin_distance": 5, + }, ], "dest": "192.0.2.48/28", }, @@ -979,7 +1026,9 @@ def test_nxos_static_routes_parsed(self): "afi": "ipv4", "routes": [ { - "next_hops": [{"forward_router_address": "192.168.255.1"}], + "next_hops": [ + {"forward_router_address": "192.168.255.1"} + ], "dest": "0.0.0.0/0", }, ], @@ -1071,7 +1120,10 @@ def test_nxos_static_routes_parsed(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.0.2.22", "tag": 4}, + { + "forward_router_address": "192.0.2.22", + "tag": 4, + }, { "forward_router_address": "192.0.2.23", "admin_distance": 1, @@ -1138,7 +1190,12 @@ def test_nxos_static_routes_gathered(self): "dest": "192.0.2.17/28", }, { - "next_hops": [{"forward_router_address": "192.0.2.26", "tag": 12}], + "next_hops": [ + { + "forward_router_address": "192.0.2.26", + "tag": 12, + } + ], "dest": "192.0.2.79/28", }, ], @@ -1154,7 +1211,10 @@ def test_nxos_static_routes_gathered(self): { "next_hops": [ {"forward_router_address": "192.0.2.13"}, - {"forward_router_address": "192.0.2.14", "admin_distance": 5}, + { + "forward_router_address": "192.0.2.14", + "admin_distance": 5, + }, ], "dest": "192.0.2.48/28", }, @@ -1169,7 +1229,9 @@ def test_nxos_static_routes_gathered(self): "afi": "ipv4", "routes": [ { - "next_hops": [{"forward_router_address": "192.168.255.1"}], + "next_hops": [ + {"forward_router_address": "192.168.255.1"} + ], "dest": "0.0.0.0/0", }, ], @@ -1261,7 +1323,10 @@ def test_nxos_static_routes_gathered(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.0.2.22", "tag": 4}, + { + "forward_router_address": "192.0.2.22", + "tag": 4, + }, { "forward_router_address": "192.0.2.23", "admin_distance": 1, diff --git a/tests/unit/modules/network/nxos/test_nxos_system.py b/tests/unit/modules/network/nxos/test_nxos_system.py index ea7eec95c..a6fb286bd 100644 --- a/tests/unit/modules/network/nxos/test_nxos_system.py +++ b/tests/unit/modules/network/nxos/test_nxos_system.py @@ -51,7 +51,9 @@ def tearDown(self): self.mock_load_config.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("nxos_system", "config.cfg", device=device) + self.get_config.return_value = load_fixture( + "nxos_system", "config.cfg", device=device + ) self.load_config.return_value = None def test_nxos_system_hostname_changed(self): @@ -90,7 +92,9 @@ def test_nxos_system_domain_name_vrf_only(self): ), ) commands = [] - self.execute_module(changed=False, commands=commands, device="vrf_only") + self.execute_module( + changed=False, commands=commands, device="vrf_only" + ) def test_nxos_system_domain_name_complex(self): domain_name = dict(name="example.net", vrf="management") diff --git a/tests/unit/modules/network/nxos/test_nxos_telemetry.py b/tests/unit/modules/network/nxos/test_nxos_telemetry.py index 160804c11..63300899e 100644 --- a/tests/unit/modules/network/nxos/test_nxos_telemetry.py +++ b/tests/unit/modules/network/nxos/test_nxos_telemetry.py @@ -33,7 +33,9 @@ ) from ansible_collections.cisco.nxos.plugins.modules import nxos_telemetry from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import AnsibleFailJson +from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( + AnsibleFailJson, +) from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -57,12 +59,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.telemetry.telemetry.Telemetry.edit_config", @@ -183,7 +189,9 @@ def test_tms_global_merged2_n9k(self): def test_tms_global_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS global config is present. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -205,7 +213,9 @@ def test_tms_global_change_cert_n9k(self): # Assumes feature telemetry is enabled # TMS global config is present # Change certificate - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -233,7 +243,9 @@ def test_tms_global_change_interface_n9k(self): # Assumes feature telemetry is enabled # TMS global config is present # Change interface - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -262,7 +274,9 @@ def test_tms_global_change_several_n9k(self): # Assumes feature telemetry is enabled # TMS global config is present # Change source_interface, vrf and cert - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -314,20 +328,27 @@ def test_tms_destgroup_input_validation_1(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert "Parameter under is required" in str(testdata["msg"]) + assert "Parameter under is required" in str( + testdata["msg"] + ) assert testdata["failed"] def test_tms_destgroup_input_validation_2(self): # Parameter 'destination' is not a dict. self.execute_show_command.return_value = None self.get_platform_shortname.return_value = "N9K" - args = build_args([{"id": "88", "destination": "192.168.1.1"}], "destination_groups") + args = build_args( + [{"id": "88", "destination": "192.168.1.1"}], "destination_groups" + ) set_module_args(args, ignore_provider_arg) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert "Parameter under must be a dict" in str( - testdata["msg"], + assert ( + "Parameter under must be a dict" + in str( + testdata["msg"], + ) ) assert testdata["failed"] @@ -343,7 +364,9 @@ def test_tms_destgroup_input_validation_3(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert "Playbook entry contains unrecongnized parameters" in str(testdata["msg"]) + assert "Playbook entry contains unrecongnized parameters" in str( + testdata["msg"] + ) assert testdata["failed"] def test_tms_destgroup_merged_n9k(self): @@ -460,7 +483,9 @@ def test_tms_destgroup_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS destgroup config is not present. # Configure only identifier - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -483,7 +508,9 @@ def test_tms_destgroup_idempotent2_n9k(self): # Assumes feature telemetry is enabled # TMS destgroup config is not present. # Configure only identifier - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args([{"id": "2"}], "destination_groups") set_module_args(args, ignore_provider_arg) @@ -492,7 +519,9 @@ def test_tms_destgroup_idempotent2_n9k(self): def test_tms_destgroup_merged_aggregate_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS destgroup config is present. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -523,7 +552,9 @@ def test_tms_destgroup_merged_aggregate_idempotent_n9k(self): def test_tms_destgroup_change_n9k(self): # TMS destgroup config is not present. # Change protocol and encoding for dest group 2 - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -562,7 +593,9 @@ def test_tms_destgroup_add_n9k(self): # TMS destgroup config is not present. # Add destinations to destgroup 10 # Add new destgroup 55 and 56 - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -619,8 +652,12 @@ def test_tms_sensorgroup_merged_n9k(self): # TMS sensorgroup config is not present. self.execute_show_command.return_value = None self.get_platform_shortname.return_value = "N9K" - td55_name = "sys/bgp/inst/dom-default/peer-[10.10.10.11]/ent-[10.10.10.11]" - td55_fc = 'or(eq(ethpmPhysIf.operSt,"down"),eq(ethpmPhysIf.operSt,"up"))' + td55_name = ( + "sys/bgp/inst/dom-default/peer-[10.10.10.11]/ent-[10.10.10.11]" + ) + td55_fc = ( + 'or(eq(ethpmPhysIf.operSt,"down"),eq(ethpmPhysIf.operSt,"up"))' + ) args = build_args( [ { @@ -705,7 +742,9 @@ def test_tms_sensorgroup_input_validation_1(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert "Parameter under is required" in str(testdata["msg"]) + assert "Parameter under is required" in str( + testdata["msg"] + ) assert testdata["failed"] def test_tms_sensorgroup_input_validation_2(self): @@ -730,7 +769,10 @@ def test_tms_sensorgroup_input_validation_2(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert "Parameter under requires key" in str(testdata["msg"]) + assert ( + "Parameter under requires key" + in str(testdata["msg"]) + ) assert testdata["failed"] def test_tms_sensorgroup_resource_key_n9k(self): @@ -857,7 +899,9 @@ def test_tms_sensorgroup_merged_variable_args4_n9k(self): def test_tms_sensorgroup_merged_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS sensorgroup config is not present. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -880,7 +924,9 @@ def test_tms_sensorgroup_merged_idempotent_n9k(self): def test_tms_sensorgroup_quotes_merged_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS sensorgroup config is present with quotes in NX-API path. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K_SGs.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K_SGs.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -906,7 +952,9 @@ def test_tms_sensorgroup_quotes_merged_idempotent_n9k(self): def test_tms_sensorgroup_vxlan_idempotent_n9k(self): # TMS sensorgroup config present. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [{"id": "56", "data_source": "DME", "path": {"name": "vxlan"}}], @@ -917,7 +965,9 @@ def test_tms_sensorgroup_vxlan_idempotent_n9k(self): def test_tms_sensorgroup_idempotent_variable1_n9k(self): # TMS sensorgroup config is present with path key name. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -936,7 +986,9 @@ def test_tms_sensorgroup_idempotent_variable1_n9k(self): def test_tms_sensorgroup_idempotent_variable2_n9k(self): # TMS sensorgroup config is present with path key name and depth. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -953,7 +1005,9 @@ def test_tms_sensorgroup_idempotent_variable2_n9k(self): def test_tms_sensorgroup_idempotent_resource_key_n9k(self): # TMS sensorgroup config is present resource key only. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args([{"id": "55"}], "sensor_groups") set_module_args(args, ignore_provider_arg) @@ -1080,7 +1134,9 @@ def test_tms_subscription_merged_n9k(self): def test_tms_subscription_merged_idempotent_n9k(self): # TMS subscription config is not present. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -1104,7 +1160,9 @@ def test_tms_subscription_merged_idempotent_n9k(self): def test_tms_subscription_merged_change1_n9k(self): # TMS subscription config present. # Change sample interval for sensor group 2 - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -1135,7 +1193,9 @@ def test_tms_subscription_merged_change1_n9k(self): def test_tms_subscription_add_n9k(self): # TMS subscription config present. # Add new destination_group and sensor_group to subscription 5 - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" args = build_args( [ @@ -1322,7 +1382,9 @@ def test_telemetry_full_n9k(self): def test_telemetry_deleted_input_validation_n9k(self): # State is 'deleted' and 'config' key present. - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -1342,14 +1404,19 @@ def test_telemetry_deleted_input_validation_n9k(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert "Remove config key from playbook when state is " in str(testdata["msg"]) + assert ( + "Remove config key from playbook when state is " + in str(testdata["msg"]) + ) assert testdata["failed"] def test_telemetry_deleted_n9k(self): # Assumes feature telemetry is enabled # TMS global config is present. # Make absent with all playbook keys provided - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args(dict(state="deleted"), ignore_provider_arg) self.execute_module(changed=True, commands=["no telemetry"]) @@ -1366,7 +1433,9 @@ def test_telemetry_deleted_idempotent_n9k(self): def test_tms_replaced1_n9k(self): # Assumes feature telemetry is enabled # Modify global config and remove everything else - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( dict( @@ -1409,7 +1478,9 @@ def test_tms_replaced2_n9k(self): # Modify destination-group 10, add 11 and 99, remove 2 # Modify sensor-group 55, 56 # remove all subscriptions - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( { @@ -1525,7 +1596,9 @@ def test_tms_replaced3_n9k(self): # remove all other destination-groups # Modify sensor-group 55 and delete all others # Modify subscription 7, add 10 and delete all others - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( { @@ -1616,7 +1689,9 @@ def test_tms_replaced_idempotent_n9k(self): # remove all other destination-groups # Modify sensor-group 55 and delete all others # Modify subscription 7, add 10 and delete all others - self.execute_show_command.return_value = load_fixture("nxos_telemetry", "N9K.cfg") + self.execute_show_command.return_value = load_fixture( + "nxos_telemetry", "N9K.cfg" + ) self.get_platform_shortname.return_value = "N9K" set_module_args( { diff --git a/tests/unit/modules/network/nxos/test_nxos_user.py b/tests/unit/modules/network/nxos/test_nxos_user.py index c397c82cb..98070c114 100644 --- a/tests/unit/modules/network/nxos/test_nxos_user.py +++ b/tests/unit/modules/network/nxos/test_nxos_user.py @@ -73,7 +73,9 @@ def test_mds(self): { "usr_name": "admin", "expire_date": "this user account has no expiry date", - "TABLE_role": {"ROW_role": {"role": "network-admin"}}, + "TABLE_role": { + "ROW_role": {"role": "network-admin"} + }, }, { "usr_name": "ansible-test-1", @@ -92,7 +94,9 @@ def test_mds(self): "network_os_image": "bootflash:///m9100-s5ek9-mz.8.4.2b.bin", "network_os_platform": "DS-C9710", } - set_module_args(dict(name="ansible-test-2", configured_password="ansible")) + set_module_args( + dict(name="ansible-test-2", configured_password="ansible") + ) self.execute_module( changed=True, commands=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_vlans.py b/tests/unit/modules/network/nxos/test_nxos_vlans.py index 97870e76d..945cbc738 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vlans.py +++ b/tests/unit/modules/network/nxos/test_nxos_vlans.py @@ -45,12 +45,16 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = self.mock_get_resource_connection_config.start() + self.get_resource_connection_config = ( + self.mock_get_resource_connection_config.start() + ) self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() + self.get_resource_connection_facts = ( + self.mock_get_resource_connection_facts.start() + ) self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.vlans.vlans.Vlans.edit_config", @@ -119,7 +123,9 @@ def test_1(self): config=[ dict(vlan_id=4), dict(vlan_id=5, mapped_vni=555, mode="ce"), - dict(vlan_id=7, mapped_vni=777, name="test-vlan7", enabled=False), + dict( + vlan_id=7, mapped_vni=777, name="test-vlan7", enabled=False + ), dict(vlan_id="8", state="active", name="test-changeme-not"), # vlan 3 is not present in playbook. ], diff --git a/tests/unit/modules/network/nxos/test_nxos_vpc.py b/tests/unit/modules/network/nxos/test_nxos_vpc.py index a74525e86..72d6e9968 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vpc.py +++ b/tests/unit/modules/network/nxos/test_nxos_vpc.py @@ -70,7 +70,9 @@ def vrf_load_from_file(*args, **kwargs): module, commands = args output = list() for command in commands: - filename = "vrf_test_" + str(command).split(" | ", 1)[0].replace(" ", "_") + filename = "vrf_test_" + str(command).split(" | ", 1)[ + 0 + ].replace(" ", "_") output.append(load_fixture("nxos_vpc", filename)) return output @@ -126,7 +128,9 @@ def test_nxos_vpc_vrf_1(self): def test_nxos_vpc_vrf_2(self): # vrf 'my_vrf'-> vrf 'test-vrf' # All pkl commands should be present - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) set_module_args( dict( domain=100, @@ -147,7 +151,9 @@ def test_nxos_vpc_vrf_2(self): def test_nxos_vpc_vrf_3(self): # vrf 'my_vrf' -> vrf 'obviously-different-vrf' # Existing pkl_src should be retained even though playbook does not specify it - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) set_module_args( dict( domain=100, @@ -167,8 +173,12 @@ def test_nxos_vpc_vrf_3(self): def test_nxos_vpc_vrf_4(self): # vrf 'my_vrf'-> vrf 'management' # 'management' is the default value for vrf, it will not nvgen - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") - set_module_args(dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="management")) + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) + set_module_args( + dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="management") + ) self.execute_module( changed=True, device="_vrf_test", @@ -180,7 +190,9 @@ def test_nxos_vpc_vrf_4(self): def test_nxos_vpc_vrf_5(self): # vrf 'my_vrf' -> vrf 'my_vrf' (idempotence) - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) set_module_args( dict( domain=100, @@ -193,7 +205,9 @@ def test_nxos_vpc_vrf_5(self): def test_nxos_vpc_vrf_6(self): # vrf 'my_vrf' -> absent tests - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) set_module_args(dict(domain=100, state="absent")) self.execute_module( changed=True, @@ -204,13 +218,19 @@ def test_nxos_vpc_vrf_6(self): def test_nxos_vpc_vrf_7(self): # dest 192.168.1.1 source 10.1.1.1 vrf my_vrf -> (dest only) (idempotence) # pkl_src/pkl_vrf not in playbook but exists on device. - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) set_module_args(dict(domain=100, pkl_dest="192.168.1.1")) self.execute_module(changed=False, device="_vrf_test") def test_nxos_vpc_vrf_8(self): # dest 192.168.1.1 source 10.1.1.1 vrf my_vrf -> (optional vrf) (idempotence) # pkl_src not in playbook but exists on device. - self.get_config.return_value = load_fixture("nxos_vpc", "vrf_test_vpc_config") - set_module_args(dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="my_vrf")) + self.get_config.return_value = load_fixture( + "nxos_vpc", "vrf_test_vpc_config" + ) + set_module_args( + dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="my_vrf") + ) self.execute_module(changed=False, device="_vrf_test") diff --git a/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py b/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py index de7ad79bd..2eeaaccc9 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py +++ b/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py @@ -70,9 +70,13 @@ def load_from_file(*args, **kwargs): def test_nxos_vpc_interface_absent(self): set_module_args(dict(portchannel=10, vpc=100, state="absent")) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface port-channel10", "no vpc"]) + self.assertEqual( + result["commands"], ["interface port-channel10", "no vpc"] + ) def test_nxos_vpc_interface_present(self): set_module_args(dict(portchannel=20, vpc=200, state="present")) result = self.execute_module(changed=True) - self.assertEqual(result["commands"], ["interface port-channel20", "vpc 200"]) + self.assertEqual( + result["commands"], ["interface port-channel20", "vpc 200"] + ) diff --git a/tests/unit/modules/network/nxos/test_nxos_vrf.py b/tests/unit/modules/network/nxos/test_nxos_vrf.py index 8f2a2ae1d..1502e4629 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vrf.py +++ b/tests/unit/modules/network/nxos/test_nxos_vrf.py @@ -66,15 +66,21 @@ def load_from_file(*args, **kwargs): def test_nxos_vrf_present(self): set_module_args(dict(vrf="ntc", state="present", admin_state="up")) - self.execute_module(changed=True, commands=["vrf context ntc", "no shutdown", "exit"]) + self.execute_module( + changed=True, commands=["vrf context ntc", "no shutdown", "exit"] + ) def test_nxos_vrf_present_no_change(self): - set_module_args(dict(vrf="management", state="present", admin_state="up")) + set_module_args( + dict(vrf="management", state="present", admin_state="up") + ) self.execute_module(changed=False, commands=[]) def test_nxos_vrf_absent(self): set_module_args(dict(vrf="management", state="absent")) - self.execute_module(changed=True, commands=["no vrf context management"]) + self.execute_module( + changed=True, commands=["no vrf context management"] + ) def test_nxos_vrf_absent_no_change(self): set_module_args(dict(vrf="ntc", state="absent")) diff --git a/tests/unit/modules/network/nxos/test_nxos_vrf_af.py b/tests/unit/modules/network/nxos/test_nxos_vrf_af.py index bfc2adef8..0e14eec9c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vrf_af.py +++ b/tests/unit/modules/network/nxos/test_nxos_vrf_af.py @@ -48,7 +48,9 @@ def setUp(self): "ansible_collections.cisco.nxos.plugins.modules.nxos_vrf_af.get_capabilities", ) self.get_capabilities = self.mock_get_capabilities.start() - self.get_capabilities.return_value = {"device_info": {"network_os_platform": "N7K-C7018"}} + self.get_capabilities.return_value = { + "device_info": {"network_os_platform": "N7K-C7018"} + } def tearDown(self): super(TestNxosVrfafModule, self).tearDown() @@ -57,7 +59,9 @@ def tearDown(self): self.mock_get_capabilities.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("nxos_vrf_af", "config.cfg") + self.get_config.return_value = load_fixture( + "nxos_vrf_af", "config.cfg" + ) self.load_config.return_value = None def test_nxos_vrf_af_present_current_non_existing(self): @@ -87,14 +91,18 @@ def test_nxos_vrf_af_absent_current_existing(self): ) def test_nxos_vrf_af_auto_evpn_route_target_present_current_existing(self): - set_module_args(dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=True)) + set_module_args( + dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=True) + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) def test_nxos_vrf_af_auto_evpn_route_target_present_current_non_existing( self, ): - set_module_args(dict(vrf="vrf10", afi="ipv4", route_target_both_auto_evpn=True)) + set_module_args( + dict(vrf="vrf10", afi="ipv4", route_target_both_auto_evpn=True) + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -106,7 +114,9 @@ def test_nxos_vrf_af_auto_evpn_route_target_present_current_non_existing( ) def test_nxos_vrf_af_auto_evpn_route_target_absent_current_existing(self): - set_module_args(dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=False)) + set_module_args( + dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=False) + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -120,7 +130,9 @@ def test_nxos_vrf_af_auto_evpn_route_target_absent_current_existing(self): def test_nxos_vrf_af_auto_evpn_route_target_absent_current_non_existing( self, ): - set_module_args(dict(vrf="vrf1", afi="ipv4", route_target_both_auto_evpn=False)) + set_module_args( + dict(vrf="vrf1", afi="ipv4", route_target_both_auto_evpn=False) + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -1088,12 +1100,16 @@ def test_nxos_vrf_af_auto_evpn_route_target_and_manual_route_targets_with_absent ) def test_nxos_vrf_af_both_auto_N9K(self): - self.get_capabilities.return_value = {"device_info": {"network_os_platform": "N9K-C9300v"}} + self.get_capabilities.return_value = { + "device_info": {"network_os_platform": "N9K-C9300v"} + } set_module_args( dict( vrf="v2000", afi="ipv4", - route_targets=[{"rt": "auto", "direction": "both", "state": "present"}], + route_targets=[ + {"rt": "auto", "direction": "both", "state": "present"} + ], ), ) result = self.execute_module(changed=True) diff --git a/tests/unit/modules/network/nxos/test_nxos_vsan.py b/tests/unit/modules/network/nxos/test_nxos_vsan.py index af9ee7ad3..4a0d91e65 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vsan.py +++ b/tests/unit/modules/network/nxos/test_nxos_vsan.py @@ -11,7 +11,9 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_vsan from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import AnsibleFailJson +from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( + AnsibleFailJson, +) from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -21,7 +23,9 @@ class TestNxosVsanModule(TestNxosModule): def setUp(self): super(TestNxosVsanModule, self).setUp() - module_path = "ansible_collections.cisco.nxos.plugins.modules.nxos_vsan." + module_path = ( + "ansible_collections.cisco.nxos.plugins.modules.nxos_vsan." + ) self.mock_run_commands = patch(module_path + "run_commands") self.run_commands = self.mock_run_commands.start() @@ -34,7 +38,9 @@ def setUp(self): self.mock_execute_show_vsanmemcmd = patch( module_path + "GetVsanInfoFromSwitch.execute_show_vsan_mem_cmd", ) - self.execute_show_vsanmem_cmd = self.mock_execute_show_vsanmemcmd.start() + self.execute_show_vsanmem_cmd = ( + self.mock_execute_show_vsanmemcmd.start() + ) self.mock_load_config = patch(module_path + "load_config") self.load_config = self.mock_load_config.start() @@ -70,16 +76,26 @@ def test_vsan_add_remove_but_present_in_switch(self): ], } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) def test_vsan_remove(self): - margs = {"vsan": [{"id": 922, "remove": True}, {"id": 923, "remove": True}]} + margs = { + "vsan": [{"id": 922, "remove": True}, {"id": 923, "remove": True}] + } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -105,8 +121,12 @@ def test_vsan_add(self): ], } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -142,8 +162,12 @@ def test_vsan_suspend(self): ], } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -161,10 +185,16 @@ def test_vsan_suspend(self): ) def test_vsan_invalid_vsan(self): - margs = {"vsan": [{"id": 4096, "name": "vsan-SAN-925", "suspend": True}]} + margs = { + "vsan": [{"id": 4096, "name": "vsan-SAN-925", "suspend": True}] + } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] @@ -172,10 +202,16 @@ def test_vsan_invalid_vsan(self): assert testdata["failed"] def test_vsan_change_reserved_vsan(self): - margs = {"vsan": [{"id": 4094, "name": "vsan-SAN-925", "suspend": True}]} + margs = { + "vsan": [{"id": 4094, "name": "vsan-SAN-925", "suspend": True}] + } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=False) assert "reserved vsan" in str(result["messages"]) self.assertEqual(result["commands"], []) @@ -190,8 +226,12 @@ def test_vsan_add_int_existing_vsan(self): ], } set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=True) self.assertEqual( result["commands"], @@ -207,8 +247,12 @@ def test_vsan_add_int_existing_vsan(self): def test_vsan_remove_non_existing_vsan(self): margs = {"vsan": [{"id": 1111, "remove": True}]} set_module_args(margs, True) - self.execute_show_vsan_cmd.return_value = load_fixture("nxos_vsan", "shvsan.cfg") - self.execute_show_vsanmem_cmd.return_value = load_fixture("nxos_vsan", "shvsanmem.cfg") + self.execute_show_vsan_cmd.return_value = load_fixture( + "nxos_vsan", "shvsan.cfg" + ) + self.execute_show_vsanmem_cmd.return_value = load_fixture( + "nxos_vsan", "shvsanmem.cfg" + ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) assert "no vsan" in str(result["messages"]) diff --git a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py index f6862a77e..beae9a09b 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py +++ b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py @@ -50,11 +50,15 @@ def tearDown(self): self.mock_load_config.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("nxos_vxlan_vtep", "config.cfg") + self.get_config.return_value = load_fixture( + "nxos_vxlan_vtep", "config.cfg" + ) self.load_config.return_value = None def test_nxos_vxlan_vtep(self): - set_module_args(dict(interface="nve1", description="simple description")) + set_module_args( + dict(interface="nve1", description="simple description") + ) self.execute_module( changed=True, commands=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py index c6dc6e8d8..597857989 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py +++ b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py @@ -50,7 +50,9 @@ def tearDown(self): self.mock_load_config.stop() def load_fixtures(self, commands=None, device=""): - self.get_config.return_value = load_fixture("nxos_vxlan_vtep_vni", "config.cfg") + self.get_config.return_value = load_fixture( + "nxos_vxlan_vtep_vni", "config.cfg" + ) self.load_config.return_value = None def test_nxos_vxlan_vtep_vni_present_no_change(self): @@ -59,11 +61,15 @@ def test_nxos_vxlan_vtep_vni_present_no_change(self): def test_nxos_vxlan_vtep_vni(self): set_module_args(dict(interface="nve1", vni=5000)) - self.execute_module(changed=True, commands=["interface nve1", "member vni 5000"]) + self.execute_module( + changed=True, commands=["interface nve1", "member vni 5000"] + ) def test_nxos_vxlan_vtep_vni_absent(self): set_module_args(dict(interface="nve1", vni=6000, state="absent")) - self.execute_module(changed=True, commands=["interface nve1", "no member vni 6000"]) + self.execute_module( + changed=True, commands=["interface nve1", "no member vni 6000"] + ) def test_nxos_vxlan_vtep_vni_absent_no_change(self): set_module_args(dict(interface="nve2", vni=6000, state="absent")) diff --git a/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py b/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py index 6afe78a5b..9af738342 100644 --- a/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py +++ b/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py @@ -19,7 +19,9 @@ class TestNxosZoneZonesetModule(TestNxosModule): def setUp(self): super(TestNxosZoneZonesetModule, self).setUp() - module_path = "ansible_collections.cisco.nxos.plugins.modules.nxos_zone_zoneset." + module_path = ( + "ansible_collections.cisco.nxos.plugins.modules.nxos_zone_zoneset." + ) self.mock_run_commands = patch(module_path + "run_commands") self.run_commands = self.mock_run_commands.start() @@ -27,12 +29,16 @@ def setUp(self): self.mock_execute_show_cmd_zoneset_active = patch( module_path + "ShowZonesetActive.execute_show_zoneset_active_cmd", ) - self.execute_show_cmd_zoneset_active = self.mock_execute_show_cmd_zoneset_active.start() + self.execute_show_cmd_zoneset_active = ( + self.mock_execute_show_cmd_zoneset_active.start() + ) self.mock_execute_show_cmd_zoneset = patch( module_path + "ShowZoneset.execute_show_zoneset_cmd", ) - self.execute_show_cmd_zoneset = self.mock_execute_show_cmd_zoneset.start() + self.execute_show_cmd_zoneset = ( + self.mock_execute_show_cmd_zoneset.start() + ) self.mock_execute_show_cmd_zone = patch( module_path + "ShowZone.execute_show_zone_vsan_cmd", @@ -42,7 +48,9 @@ def setUp(self): self.mock_execute_show_cmd_zone_status = patch( module_path + "ShowZoneStatus.execute_show_zone_status_cmd", ) - self.execute_show_cmd_zone_status = self.mock_execute_show_cmd_zone_status.start() + self.execute_show_cmd_zone_status = ( + self.mock_execute_show_cmd_zone_status.start() + ) self.mock_load_config = patch(module_path + "load_config") self.load_config = self.mock_load_config.start() @@ -261,7 +269,9 @@ def test_zone_add_rem_1(self): self.assertEqual(result["commands"], []) def test_zone_add_rem_2(self): - a = dict(zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneBNew")])]) + a = dict( + zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneBNew")])] + ) set_module_args(a, True) self.execute_show_cmd_zone_status.return_value = load_fixture( "nxos_zone_zoneset", @@ -283,7 +293,9 @@ def test_zone_add_rem_2(self): ) def test_zone_add_rem_3(self): - a = dict(zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneB")])]) + a = dict( + zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneB")])] + ) set_module_args(a, True) self.execute_show_cmd_zone_status.return_value = load_fixture( "nxos_zone_zoneset", @@ -338,7 +350,9 @@ def test_zonemem_add_rem_1(self): mem2 = {"device_alias": "test123", "remove": True} a = dict( zone_zoneset_details=[ - dict(vsan=923, zone=[dict(name="zoneA", members=[mem1, mem2])]), + dict( + vsan=923, zone=[dict(name="zoneA", members=[mem1, mem2])] + ), ], ) set_module_args(a, True) @@ -369,7 +383,9 @@ def test_zonemem_add_rem_2(self): mem2 = {"device_alias": "test123", "remove": True} a = dict( zone_zoneset_details=[ - dict(vsan=923, zone=[dict(name="zoneA1", members=[mem1, mem2])]), + dict( + vsan=923, zone=[dict(name="zoneA1", members=[mem1, mem2])] + ), ], ) set_module_args(a, True) @@ -478,7 +494,9 @@ def test_zoneset_add_rem(self): def test_zoneset_add_rem_1(self): a = dict( - zone_zoneset_details=[dict(vsan=922, zoneset=[dict(name="zsetname21New")])], + zone_zoneset_details=[ + dict(vsan=922, zoneset=[dict(name="zsetname21New")]) + ], ) set_module_args(a, True) self.execute_show_cmd_zone_status.return_value = load_fixture( @@ -501,7 +519,9 @@ def test_zoneset_add_rem_1(self): def test_zoneset_add_rem_2(self): a = dict( - zone_zoneset_details=[dict(vsan=922, zoneset=[dict(name="zsetname21")])], + zone_zoneset_details=[ + dict(vsan=922, zoneset=[dict(name="zsetname21")]) + ], ) set_module_args(a, True) self.execute_show_cmd_zone_status.return_value = load_fixture( @@ -520,7 +540,9 @@ def test_zoneset_add_rem_2(self): def test_zoneset_add_rem_3(self): a = dict( zone_zoneset_details=[ - dict(vsan=922, zoneset=[dict(name="zsetname21New", remove=True)]), + dict( + vsan=922, zoneset=[dict(name="zsetname21New", remove=True)] + ), ], ) set_module_args(a, True) @@ -543,7 +565,9 @@ def test_zoneset_mem_add_rem(self): a = dict( zone_zoneset_details=[ - dict(vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])]), + dict( + vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])] + ), ], ) set_module_args(a, True) @@ -572,7 +596,9 @@ def test_zoneset_mem_add_rem_1(self): a = dict( zone_zoneset_details=[ - dict(vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])]), + dict( + vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])] + ), ], ) set_module_args(a, True) @@ -601,7 +627,9 @@ def test_zoneset_mem_add_rem_2(self): a = dict( zone_zoneset_details=[ - dict(vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])]), + dict( + vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])] + ), ], ) set_module_args(a, True) @@ -622,7 +650,9 @@ def test_zoneset_mem_add_rem_2(self): def test_zoneset_activate_deactivate(self): a = dict( zone_zoneset_details=[ - dict(vsan=221, zoneset=[dict(name="zsv221", action="activate")]), + dict( + vsan=221, zoneset=[dict(name="zsv221", action="activate")] + ), ], ) set_module_args(a, True) @@ -713,7 +743,9 @@ def test_bug_zone_remove(self): mem2 = {"pwwn": "50:06:01:6a:47:e4:6e:59", "remove": True} a = dict( zone_zoneset_details=[ - dict(vsan=221, zone=[dict(name="zv221", members=[mem1, mem2])]), + dict( + vsan=221, zone=[dict(name="zv221", members=[mem1, mem2])] + ), ], ) set_module_args(a, True) From 79d3c1abfd547628ceb92ec9cda1f66bdb4f42e6 Mon Sep 17 00:00:00 2001 From: Ashwini Mhatre Date: Thu, 7 Mar 2024 17:33:27 +0530 Subject: [PATCH 17/19] Update pyproject.toml --- pyproject.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c547b3fd7..967d963d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,8 @@ [tool.black] -line-length = 79 +line-length = 100 [tool.pytest.ini_options] +addopts = ["-vvv", "-n", "2", "--log-level", "WARNING", "--color", "yes"] testpaths = ["tests"] filterwarnings = [ 'ignore:AnsibleCollectionFinder has already been configured', From efe03ce07b1e4756a602701c078aab5bafcb441f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 7 Mar 2024 12:04:23 +0000 Subject: [PATCH 18/19] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- clean.py | 16 +- plugins/action/nxos.py | 18 +-- plugins/cliconf/nxos.py | 99 +++++++----- plugins/httpapi/nxos.py | 16 +- .../network/nxos/argspec/acls/acls.py | 120 +++++++------- .../bgp_address_family/bgp_address_family.py | 8 +- .../nxos/argspec/bgp_global/bgp_global.py | 16 +- .../bgp_neighbor_address_family.py | 24 +-- .../argspec/bgp_templates/bgp_templates.py | 4 +- .../argspec/logging_global/logging_global.py | 2 +- .../ospf_interfaces/ospf_interfaces.py | 2 +- .../network/nxos/argspec/ospfv2/ospfv2.py | 72 ++++----- .../network/nxos/argspec/ospfv3/ospfv3.py | 60 +++---- .../nxos/argspec/route_maps/route_maps.py | 38 ++--- .../nxos/argspec/snmp_server/snmp_server.py | 14 +- .../argspec/static_routes/static_routes.py | 2 +- .../config/acl_interfaces/acl_interfaces.py | 45 +++--- .../network/nxos/config/acls/acls.py | 150 +++++++----------- .../config/bfd_interfaces/bfd_interfaces.py | 24 ++- .../bgp_address_family/bgp_address_family.py | 38 ++--- .../nxos/config/bgp_global/bgp_global.py | 30 ++-- .../bgp_neighbor_address_family.py | 20 ++- .../config/bgp_templates/bgp_templates.py | 22 ++- .../config/fc_interfaces/fc_interfaces.py | 18 +-- .../network/nxos/config/hostname/hostname.py | 4 +- .../config/hsrp_interfaces/hsrp_interfaces.py | 24 +-- .../nxos/config/interfaces/interfaces.py | 26 +-- .../config/l2_interfaces/l2_interfaces.py | 27 ++-- .../config/l3_interfaces/l3_interfaces.py | 65 ++++---- .../network/nxos/config/lacp/lacp.py | 6 +- .../config/lacp_interfaces/lacp_interfaces.py | 21 +-- .../config/lag_interfaces/lag_interfaces.py | 30 ++-- .../nxos/config/lldp_global/lldp_global.py | 15 +- .../config/lldp_interfaces/lldp_interfaces.py | 19 +-- .../config/logging_global/logging_global.py | 4 +- .../nxos/config/ntp_global/ntp_global.py | 8 +- .../config/ospf_interfaces/ospf_interfaces.py | 44 ++--- .../network/nxos/config/ospfv2/ospfv2.py | 44 ++--- .../network/nxos/config/ospfv3/ospfv3.py | 45 ++---- .../nxos/config/prefix_lists/prefix_lists.py | 26 ++- .../nxos/config/route_maps/route_maps.py | 61 +++---- .../nxos/config/snmp_server/snmp_server.py | 12 +- .../config/static_routes/static_routes.py | 25 +-- .../nxos/config/telemetry/telemetry.py | 112 ++++++------- .../network/nxos/config/vlans/vlans.py | 11 +- .../facts/acl_interfaces/acl_interfaces.py | 10 +- .../network/nxos/facts/acls/acls.py | 25 ++- .../facts/bfd_interfaces/bfd_interfaces.py | 19 +-- .../bgp_address_family/bgp_address_family.py | 14 +- .../nxos/facts/bgp_global/bgp_global.py | 14 +- .../bgp_neighbor_address_family.py | 16 +- .../nxos/facts/bgp_templates/bgp_templates.py | 17 +- .../module_utils/network/nxos/facts/facts.py | 12 +- .../nxos/facts/fc_interfaces/fc_interfaces.py | 17 +- .../network/nxos/facts/hostname/hostname.py | 11 +- .../facts/hsrp_interfaces/hsrp_interfaces.py | 12 +- .../nxos/facts/interfaces/interfaces.py | 21 ++- .../nxos/facts/l2_interfaces/l2_interfaces.py | 13 +- .../nxos/facts/l3_interfaces/l3_interfaces.py | 27 ++-- .../network/nxos/facts/lacp/lacp.py | 11 +- .../facts/lacp_interfaces/lacp_interfaces.py | 10 +- .../facts/lag_interfaces/lag_interfaces.py | 9 +- .../network/nxos/facts/legacy/base.py | 63 ++++---- .../nxos/facts/lldp_global/lldp_global.py | 14 +- .../facts/lldp_interfaces/lldp_interfaces.py | 7 +- .../facts/logging_global/logging_global.py | 7 +- .../nxos/facts/ntp_global/ntp_global.py | 11 +- .../facts/ospf_interfaces/ospf_interfaces.py | 10 +- .../network/nxos/facts/ospfv2/ospfv2.py | 6 +- .../network/nxos/facts/ospfv3/ospfv3.py | 4 +- .../nxos/facts/prefix_lists/prefix_lists.py | 16 +- .../nxos/facts/route_maps/route_maps.py | 11 +- .../nxos/facts/snmp_server/snmp_server.py | 14 +- .../nxos/facts/static_routes/static_routes.py | 23 +-- .../network/nxos/facts/telemetry/telemetry.py | 48 +++--- .../network/nxos/facts/vlans/vlans.py | 20 +-- plugins/module_utils/network/nxos/nxos.py | 99 ++++++------ .../nxos/rm_templates/bgp_address_family.py | 3 +- .../network/nxos/rm_templates/bgp_global.py | 4 +- .../bgp_neighbor_address_family.py | 3 +- .../nxos/rm_templates/bgp_templates.py | 4 +- .../nxos/rm_templates/fc_interfaces.py | 8 +- .../network/nxos/rm_templates/hostname.py | 4 +- .../nxos/rm_templates/logging_global.py | 8 +- .../network/nxos/rm_templates/ntp_global.py | 4 +- .../nxos/rm_templates/ospf_interfaces.py | 4 +- .../network/nxos/rm_templates/ospfv2.py | 7 +- .../network/nxos/rm_templates/ospfv3.py | 10 +- .../network/nxos/rm_templates/prefix_lists.py | 4 +- .../network/nxos/rm_templates/route_maps.py | 4 +- .../network/nxos/rm_templates/snmp_server.py | 4 +- .../nxos/rm_templates/static_routes.py | 4 +- .../network/nxos/utils/telemetry/telemetry.py | 29 ++-- .../module_utils/network/nxos/utils/utils.py | 4 +- plugins/modules/nxos_aaa_server.py | 38 ++--- plugins/modules/nxos_aaa_server_host.py | 18 ++- plugins/modules/nxos_acls.py | 7 +- plugins/modules/nxos_banner.py | 5 +- plugins/modules/nxos_bfd_global.py | 3 +- plugins/modules/nxos_command.py | 9 +- plugins/modules/nxos_config.py | 17 +- plugins/modules/nxos_devicealias.py | 47 ++---- plugins/modules/nxos_evpn_global.py | 5 +- plugins/modules/nxos_evpn_vni.py | 13 +- plugins/modules/nxos_facts.py | 9 +- plugins/modules/nxos_feature.py | 8 +- plugins/modules/nxos_file_copy.py | 40 ++--- plugins/modules/nxos_gir.py | 50 ++---- .../modules/nxos_gir_profile_management.py | 3 +- plugins/modules/nxos_hsrp.py | 51 +++--- plugins/modules/nxos_igmp.py | 6 +- plugins/modules/nxos_igmp_interface.py | 48 +++--- plugins/modules/nxos_igmp_snooping.py | 15 +- plugins/modules/nxos_install_os.py | 19 ++- plugins/modules/nxos_lacp.py | 4 +- plugins/modules/nxos_logging.py | 75 +++++---- plugins/modules/nxos_ntp.py | 26 +-- plugins/modules/nxos_ntp_auth.py | 33 +++- plugins/modules/nxos_ntp_options.py | 3 +- plugins/modules/nxos_nxapi.py | 27 ++-- plugins/modules/nxos_overlay_global.py | 16 +- plugins/modules/nxos_pim.py | 8 +- plugins/modules/nxos_pim_interface.py | 55 +++---- plugins/modules/nxos_pim_rp_address.py | 11 +- plugins/modules/nxos_ping.py | 15 +- plugins/modules/nxos_reboot.py | 7 +- plugins/modules/nxos_rollback.py | 7 +- plugins/modules/nxos_rpm.py | 34 ++-- plugins/modules/nxos_snapshot.py | 15 +- plugins/modules/nxos_snmp_community.py | 2 +- plugins/modules/nxos_snmp_contact.py | 3 +- plugins/modules/nxos_snmp_host.py | 26 +-- plugins/modules/nxos_snmp_location.py | 3 +- plugins/modules/nxos_snmp_traps.py | 13 +- plugins/modules/nxos_snmp_user.py | 7 +- plugins/modules/nxos_system.py | 3 +- plugins/modules/nxos_telemetry.py | 3 +- plugins/modules/nxos_udld.py | 15 +- plugins/modules/nxos_udld_interface.py | 25 ++- plugins/modules/nxos_user.py | 15 +- plugins/modules/nxos_vlans.py | 3 +- plugins/modules/nxos_vpc.py | 21 ++- plugins/modules/nxos_vpc_interface.py | 20 ++- plugins/modules/nxos_vrf.py | 30 ++-- plugins/modules/nxos_vrf_af.py | 18 ++- plugins/modules/nxos_vrf_interface.py | 9 +- plugins/modules/nxos_vrrp.py | 13 +- plugins/modules/nxos_vsan.py | 39 ++--- plugins/modules/nxos_vtp_domain.py | 3 +- plugins/modules/nxos_vtp_password.py | 8 +- plugins/modules/nxos_vtp_version.py | 5 +- plugins/modules/nxos_vxlan_vtep.py | 43 +++-- plugins/modules/nxos_vxlan_vtep_vni.py | 49 +++--- plugins/modules/nxos_zone_zoneset.py | 121 ++++---------- plugins/netconf/nxos.py | 4 +- plugins/terminal/nxos.py | 15 +- tests/unit/compat/mock.py | 2 +- tests/unit/mock/path.py | 3 +- tests/unit/mock/vault_helper.py | 4 +- tests/unit/mock/yaml_helper.py | 26 +-- tests/unit/modules/conftest.py | 15 +- .../unit/modules/network/nxos/nxos_module.py | 17 +- tests/unit/modules/network/nxos/test_nxos.py | 6 +- .../network/nxos/test_nxos_acl_interfaces.py | 24 ++- .../modules/network/nxos/test_nxos_acls.py | 26 ++- .../network/nxos/test_nxos_bfd_global.py | 12 +- .../network/nxos/test_nxos_bfd_interfaces.py | 20 +-- .../nxos/test_nxos_bgp_address_family.py | 84 ++++++---- .../network/nxos/test_nxos_bgp_global.py | 16 +- .../test_nxos_bgp_neighbor_address_family.py | 68 ++++---- .../network/nxos/test_nxos_bgp_templates.py | 7 +- .../modules/network/nxos/test_nxos_command.py | 8 +- .../modules/network/nxos/test_nxos_config.py | 47 ++++-- .../network/nxos/test_nxos_devicealias.py | 103 +++++++----- .../network/nxos/test_nxos_evpn_global.py | 6 +- .../network/nxos/test_nxos_evpn_vni.py | 5 +- .../network/nxos/test_nxos_fc_interfaces.py | 19 ++- .../modules/network/nxos/test_nxos_feature.py | 12 +- .../network/nxos/test_nxos_hostname.py | 7 +- .../network/nxos/test_nxos_hsrp_interfaces.py | 20 +-- .../network/nxos/test_nxos_interfaces.py | 30 ++-- .../network/nxos/test_nxos_l3_interfaces.py | 49 +++--- .../network/nxos/test_nxos_lacp_interfaces.py | 10 +- .../network/nxos/test_nxos_lldp_interfaces.py | 20 +-- .../network/nxos/test_nxos_logging_global.py | 30 ++-- .../network/nxos/test_nxos_ntp_global.py | 18 ++- .../modules/network/nxos/test_nxos_nxapi.py | 3 +- .../network/nxos/test_nxos_ospf_interfaces.py | 87 ++++++---- .../modules/network/nxos/test_nxos_ospfv2.py | 36 +++-- .../modules/network/nxos/test_nxos_ospfv3.py | 60 ++++--- .../network/nxos/test_nxos_overlay_global.py | 3 +- .../modules/network/nxos/test_nxos_pim.py | 9 +- .../network/nxos/test_nxos_pim_interface.py | 10 +- .../network/nxos/test_nxos_pim_rp_address.py | 9 +- .../modules/network/nxos/test_nxos_ping.py | 16 +- .../network/nxos/test_nxos_prefix_lists.py | 11 +- .../network/nxos/test_nxos_route_maps.py | 46 +++--- .../network/nxos/test_nxos_snmp_server.py | 75 +++++---- .../network/nxos/test_nxos_static_routes.py | 29 ++-- .../modules/network/nxos/test_nxos_system.py | 8 +- .../network/nxos/test_nxos_telemetry.py | 118 +++++++------- .../modules/network/nxos/test_nxos_user.py | 4 +- .../modules/network/nxos/test_nxos_vlans.py | 13 +- .../modules/network/nxos/test_nxos_vpc.py | 29 ++-- .../network/nxos/test_nxos_vpc_interface.py | 6 +- .../modules/network/nxos/test_nxos_vrf.py | 8 +- .../modules/network/nxos/test_nxos_vrf_af.py | 17 +- .../modules/network/nxos/test_nxos_vsan.py | 66 ++++---- .../network/nxos/test_nxos_vxlan_vtep.py | 5 +- .../network/nxos/test_nxos_vxlan_vtep_vni.py | 9 +- .../network/nxos/test_nxos_zone_zoneset.py | 48 +++--- 211 files changed, 2386 insertions(+), 2522 deletions(-) diff --git a/clean.py b/clean.py index 184f51efe..2c4bd82a3 100644 --- a/clean.py +++ b/clean.py @@ -113,11 +113,7 @@ def update_include_cli(data: CommentedSeq) -> bool: :param data: The task list :return: Whether the include_cli task was updated """ - match = [ - idx - for idx, item in enumerate(data) - if item.get("include") == "cli.yaml" - ] + match = [idx for idx, item in enumerate(data) if item.get("include") == "cli.yaml"] if not match: return False @@ -135,11 +131,7 @@ def update_include_nxapi(data: CommentedSeq) -> bool: :param data: The task list :return: Whether the include_nxapi task was updated """ - match = [ - idx - for idx, item in enumerate(data) - if item.get("include") == "nxapi.yaml" - ] + match = [idx for idx, item in enumerate(data) if item.get("include") == "nxapi.yaml"] if not match: return False @@ -306,9 +298,7 @@ def undo_set_fact_equal(list_of_tasks) -> bool: ) if commented: - list_of_tasks[entry]["ansible.builtin.set_fact"].ca.items[ - last_key - ] = [ + list_of_tasks[entry]["ansible.builtin.set_fact"].ca.items[last_key] = [ None, None, ct, diff --git a/plugins/action/nxos.py b/plugins/action/nxos.py index 79a3fce5f..4d7b75c90 100644 --- a/plugins/action/nxos.py +++ b/plugins/action/nxos.py @@ -36,9 +36,7 @@ def run(self, tmp=None, task_vars=None): del tmp # tmp no longer has any effect module_name = self._task.action.split(".")[-1] - self._config_module = ( - True if module_name in ["nxos_config", "config"] else False - ) + self._config_module = True if module_name in ["nxos_config", "config"] else False persistent_connection = self._play_context.connection.split(".")[-1] warnings = [] @@ -68,7 +66,7 @@ def run(self, tmp=None, task_vars=None): conn = Connection(self._connection.socket_path) persistent_command_timeout = conn.get_option( - "persistent_command_timeout" + "persistent_command_timeout", ) file_pull = self._task.args.get("file_pull", False) file_pull_timeout = self._task.args.get("file_pull_timeout") @@ -78,7 +76,8 @@ def run(self, tmp=None, task_vars=None): # if file_pull_timeout is explicitly set, use that if file_pull_timeout: conn.set_option( - "persistent_command_timeout", file_pull_timeout + "persistent_command_timeout", + file_pull_timeout, ) # if file_pull_timeout is not set and command_timeout < 300s, bump to 300s. elif persistent_command_timeout < 300: @@ -102,13 +101,8 @@ def run(self, tmp=None, task_vars=None): f"PERSISTENT_CONNECT_TIMEOUT is %s {persistent_connect_timeout}", self._play_context.remote_addr, ) - if ( - persistent_command_timeout < 600 - or persistent_connect_timeout < 600 - ): - msg = ( - "PERSISTENT_COMMAND_TIMEOUT and PERSISTENT_CONNECT_TIMEOUT" - ) + if persistent_command_timeout < 600 or persistent_connect_timeout < 600: + msg = "PERSISTENT_COMMAND_TIMEOUT and PERSISTENT_CONNECT_TIMEOUT" msg += " must be set to 600 seconds or higher when using nxos_install_os module." msg += " Current persistent_command_timeout setting:" + str( persistent_command_timeout, diff --git a/plugins/cliconf/nxos.py b/plugins/cliconf/nxos.py index 860537f8e..e0fe8e6b1 100644 --- a/plugins/cliconf/nxos.py +++ b/plugins/cliconf/nxos.py @@ -55,12 +55,8 @@ NetworkConfig, dumps, ) -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( - to_list, -) -from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import ( - CliconfBase, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list +from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import CliconfBase class Cliconf(CliconfBase): @@ -89,40 +85,52 @@ def get_device_info(self): platform_reply = self.get("show inventory") match_sys_ver = re.search( - r"\s+system:\s+version\s*(\S+)", reply, re.M + r"\s+system:\s+version\s*(\S+)", + reply, + re.M, ) if match_sys_ver: device_info["network_os_version"] = match_sys_ver.group(1) else: match_kick_ver = re.search( - r"\s+kickstart:\s+version\s*(\S+)", reply, re.M + r"\s+kickstart:\s+version\s*(\S+)", + reply, + re.M, ) if match_kick_ver: device_info["network_os_version"] = match_kick_ver.group(1) if "network_os_version" not in device_info: match_sys_ver = re.search( - r"\s+NXOS:\s+version\s*(\S+)", reply, re.M + r"\s+NXOS:\s+version\s*(\S+)", + reply, + re.M, ) if match_sys_ver: device_info["network_os_version"] = match_sys_ver.group(1) match_chassis_id = re.search( - r"Hardware\n\s+cisco(.+)$", reply, re.M + r"Hardware\n\s+cisco(.+)$", + reply, + re.M, ) if match_chassis_id: device_info["network_os_model"] = match_chassis_id.group( - 1 + 1, ).strip() match_host_name = re.search( - r"\s+Device name:\s*(\S+)", reply, re.M + r"\s+Device name:\s*(\S+)", + reply, + re.M, ) if match_host_name: device_info["network_os_hostname"] = match_host_name.group(1) match_isan_file_name = re.search( - r"\s+system image file is:\s*(\S+)", reply, re.M + r"\s+system image file is:\s*(\S+)", + reply, + re.M, ) if match_isan_file_name: device_info["network_os_image"] = match_isan_file_name.group(1) @@ -133,18 +141,16 @@ def get_device_info(self): re.M, ) if match_kick_file_name: - device_info[ - "network_os_image" - ] = match_kick_file_name.group(1) + device_info["network_os_image"] = match_kick_file_name.group(1) if "network_os_image" not in device_info: match_isan_file_name = re.search( - r"\s+NXOS image file is:\s*(\S+)", reply, re.M + r"\s+NXOS image file is:\s*(\S+)", + reply, + re.M, ) if match_isan_file_name: - device_info[ - "network_os_image" - ] = match_isan_file_name.group(1) + device_info["network_os_image"] = match_isan_file_name.group(1) match_os_platform = re.search( r'NAME: "Chassis",\s*DESCR:.*\nPID:\s*(\S+)', @@ -173,7 +179,7 @@ def get_diff( if candidate is None and device_operations["supports_generate_diff"]: raise ValueError( - "candidate configuration is required to generate diff" + "candidate configuration is required to generate diff", ) if diff_match not in option_values["diff_match"]: @@ -195,7 +201,9 @@ def get_diff( if running and diff_match != "none" and diff_replace != "config": # running configuration running_obj = NetworkConfig( - indent=2, contents=running, ignore_lines=diff_ignore_lines + indent=2, + contents=running, + ignore_lines=diff_ignore_lines, ) configdiffobjs = candidate_obj.difference( running_obj, @@ -207,9 +215,7 @@ def get_diff( else: configdiffobjs = candidate_obj.items - diff["config_diff"] = ( - dumps(configdiffobjs, "commands") if configdiffobjs else "" - ) + diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else "" return diff def get_config(self, source="running", flags=None, format="text"): @@ -223,7 +229,7 @@ def get_config(self, source="running", flags=None, format="text"): lookup = {"running": "running-config", "startup": "startup-config"} if source not in lookup: raise ValueError( - "fetching configuration from %s is not supported" % source + "fetching configuration from %s is not supported" % source, ) cmd = "show {0} ".format(lookup[source]) @@ -237,12 +243,20 @@ def get_config(self, source="running", flags=None, format="text"): return self.send_command(cmd) def edit_config( - self, candidate=None, commit=True, replace=None, comment=None + self, + candidate=None, + commit=True, + replace=None, + comment=None, ): resp = {} operations = self.get_device_operations() self.check_edit_config_capability( - operations, candidate, commit, replace, comment + operations, + candidate, + commit, + replace, + comment, ) results = [] requests = [] @@ -306,7 +320,8 @@ def run_commands(self, commands=None, check_rc=True): output = cmd.pop("output", None) if output: cmd["command"] = self._get_command_with_output( - cmd["command"], output + cmd["command"], + output, ) try: @@ -321,8 +336,7 @@ def run_commands(self, commands=None, check_rc=True): out = to_text(out, errors="surrogate_or_strict").strip() except UnicodeError: raise ConnectionError( - message="Failed to decode output from %s: %s" - % (cmd, to_text(out)), + message="Failed to decode output from %s: %s" % (cmd, to_text(out)), ) try: @@ -376,13 +390,13 @@ def pull_file(self, command, remotepassword=None): re.compile(rb"(?i)Too many authentication failures"), re.compile(rb"Access Denied"), re.compile( - rb"(?i)Copying to\/from this server name is not permitted" + rb"(?i)Copying to\/from this server name is not permitted", ), ] # set error regex for copy command current_stderr_re = self._connection._get_terminal_std_re( - "terminal_stderr_re" + "terminal_stderr_re", ) current_stderr_re.extend(possible_errors_re) @@ -396,7 +410,7 @@ def pull_file(self, command, remotepassword=None): # set stdout regex for copy command to handle optional user prompts # based on different match conditions current_stdout_re = self._connection._get_terminal_std_re( - "terminal_stdout_re" + "terminal_stdout_re", ) current_stdout_re.extend(possible_prompts_re) @@ -413,12 +427,14 @@ def pull_file(self, command, remotepassword=None): if possible_prompts_re[1].search(to_bytes(output)): output = self.send_command( - command="yes", strip_prompt=False + command="yes", + strip_prompt=False, ) if possible_prompts_re[2].search(to_bytes(output)): output = self.send_command( - command=remotepassword, strip_prompt=False + command=remotepassword, + strip_prompt=False, ) if "Copy complete" in output: file_pulled = True @@ -440,17 +456,17 @@ def set_cli_prompt_context(self): if out is None: raise AnsibleConnectionFailure( message="cli prompt is not identified from the last received" - " response window: %s" - % self._connection._last_recv_window, + " response window: %s" % self._connection._last_recv_window, ) # Match prompts ending in )# except those with (maint-mode)# config_prompt = re.compile(r"^.*\((?!maint-mode).*\)#$") while config_prompt.match( - to_text(out, errors="surrogate_then_replace").strip() + to_text(out, errors="surrogate_then_replace").strip(), ): self._connection.queue_message( - "vvvv", "wrong context, sending exit to device" + "vvvv", + "wrong context, sending exit to device", ) self._connection.send_command("exit") out = self._connection.get_prompt() @@ -465,7 +481,8 @@ def _get_command_with_output(self, command, output): ) if output in ["json", "json-pretty"] and not re.search( - output_re, command + output_re, + command, ): device_info = self.get_device_info() model = device_info.get("network_os_model", "") diff --git a/plugins/httpapi/nxos.py b/plugins/httpapi/nxos.py index aaf82f6bf..0c7543db6 100644 --- a/plugins/httpapi/nxos.py +++ b/plugins/httpapi/nxos.py @@ -22,12 +22,8 @@ from ansible.module_utils._text import to_text from ansible.module_utils.connection import ConnectionError -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( - to_list, -) -from ansible_collections.ansible.netcommon.plugins.plugin_utils.httpapi_base import ( - HttpApiBase, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list +from ansible_collections.ansible.netcommon.plugins.plugin_utils.httpapi_base import HttpApiBase OPTIONS = { @@ -110,7 +106,7 @@ def _run_queue(self, queue, output): except ValueError: raise ConnectionError( "Response was not valid JSON, got {0}".format( - to_text(response_data.getvalue()) + to_text(response_data.getvalue()), ), ) @@ -125,7 +121,7 @@ def get_device_info(self): device_info["network_os"] = "nxos" reply, platform_reply = self.send_request( - ["show version", "show inventory"] + ["show version", "show inventory"], ) find_os_version = [ @@ -140,7 +136,9 @@ def get_device_info(self): break match_chassis_id = re.search( - r"Hardware\n\s+cisco\s*(\S+\s+\S+)", reply, re.M + r"Hardware\n\s+cisco\s*(\S+\s+\S+)", + reply, + re.M, ) if match_chassis_id: device_info["network_os_model"] = match_chassis_id.group(1) diff --git a/plugins/module_utils/network/nxos/argspec/acls/acls.py b/plugins/module_utils/network/nxos/argspec/acls/acls.py index 297072f23..85c509e6b 100644 --- a/plugins/module_utils/network/nxos/argspec/acls/acls.py +++ b/plugins/module_utils/network/nxos/argspec/acls/acls.py @@ -77,11 +77,11 @@ class AclsArgs(object): # pylint: disable=R0903 "options": { "end": {"type": "str"}, "start": { - "type": "str" + "type": "str", }, }, "required_together": [ - ["start", "end"] + ["start", "end"], ], "type": "dict", }, @@ -92,7 +92,7 @@ class AclsArgs(object): # pylint: disable=R0903 "wildcard_bits": {"type": "str"}, }, "required_together": [ - ["address", "wildcard_bits"] + ["address", "wildcard_bits"], ], "type": "dict", }, @@ -107,141 +107,141 @@ class AclsArgs(object): # pylint: disable=R0903 "protocol": {"type": "str"}, "protocol_options": { "mutually_exclusive": [ - ["icmp", "igmp", "tcp"] + ["icmp", "igmp", "tcp"], ], "options": { "icmp": { "options": { "administratively_prohibited": { - "type": "bool" + "type": "bool", }, "alternate_address": { - "type": "bool" + "type": "bool", }, "conversion_error": { - "type": "bool" + "type": "bool", }, "dod_host_prohibited": { - "type": "bool" + "type": "bool", }, "dod_net_prohibited": { - "type": "bool" + "type": "bool", }, "echo": {"type": "bool"}, "echo_reply": {"type": "bool"}, "echo_request": { - "type": "bool" + "type": "bool", }, "general_parameter_problem": { - "type": "bool" + "type": "bool", }, "host_isolated": { - "type": "bool" + "type": "bool", }, "host_precedence_unreachable": { - "type": "bool" + "type": "bool", }, "host_redirect": { - "type": "bool" + "type": "bool", }, "host_tos_redirect": { - "type": "bool" + "type": "bool", }, "host_tos_unreachable": { - "type": "bool" + "type": "bool", }, "host_unknown": { - "type": "bool" + "type": "bool", }, "host_unreachable": { - "type": "bool" + "type": "bool", }, "information_reply": { - "type": "bool" + "type": "bool", }, "information_request": { - "type": "bool" + "type": "bool", }, "mask_reply": {"type": "bool"}, "mask_request": { - "type": "bool" + "type": "bool", }, "message_code": { - "type": "int" + "type": "int", }, "message_type": { - "type": "int" + "type": "int", }, "mobile_redirect": { - "type": "bool" + "type": "bool", }, "net_redirect": { - "type": "bool" + "type": "bool", }, "net_tos_redirect": { - "type": "bool" + "type": "bool", }, "net_tos_unreachable": { - "type": "bool" + "type": "bool", }, "net_unreachable": { - "type": "bool" + "type": "bool", }, "network_unknown": { - "type": "bool" + "type": "bool", }, "no_room_for_option": { - "type": "bool" + "type": "bool", }, "option_missing": { - "type": "bool" + "type": "bool", }, "packet_too_big": { - "type": "bool" + "type": "bool", }, "parameter_problem": { - "type": "bool" + "type": "bool", }, "port_unreachable": { - "type": "bool" + "type": "bool", }, "precedence_unreachable": { - "type": "bool" + "type": "bool", }, "protocol_unreachable": { - "type": "bool" + "type": "bool", }, "reassembly_timeout": { - "type": "bool" + "type": "bool", }, "redirect": {"type": "bool"}, "router_advertisement": { - "type": "bool" + "type": "bool", }, "router_solicitation": { - "type": "bool" + "type": "bool", }, "source_quench": { - "type": "bool" + "type": "bool", }, "source_route_failed": { - "type": "bool" + "type": "bool", }, "time_exceeded": { - "type": "bool" + "type": "bool", }, "timestamp_reply": { - "type": "bool" + "type": "bool", }, "timestamp_request": { - "type": "bool" + "type": "bool", }, "traceroute": {"type": "bool"}, "ttl_exceeded": { - "type": "bool" + "type": "bool", }, "unreachable": { - "type": "bool" + "type": "bool", }, }, "type": "dict", @@ -250,33 +250,33 @@ class AclsArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "beyond_scope": { - "type": "bool" + "type": "bool", }, "destination_unreachable": { "type": "bool", }, "echo_reply": {"type": "bool"}, "echo_request": { - "type": "bool" + "type": "bool", }, "fragments": {"type": "bool"}, "header": {"type": "bool"}, "hop_limit": {"type": "bool"}, "mld_query": {"type": "bool"}, "mld_reduction": { - "type": "bool" + "type": "bool", }, "mld_report": {"type": "bool"}, "mldv2": {"type": "bool"}, "nd_na": {"type": "bool"}, "nd_ns": {"type": "bool"}, "next_header": { - "type": "bool" + "type": "bool", }, "no_admin": {"type": "bool"}, "no_route": {"type": "bool"}, "packet_too_big": { - "type": "bool" + "type": "bool", }, "parameter_option": { "type": "bool", @@ -291,10 +291,10 @@ class AclsArgs(object): # pylint: disable=R0903 "type": "bool", }, "renum_command": { - "type": "bool" + "type": "bool", }, "renum_result": { - "type": "bool" + "type": "bool", }, "renum_seq_number": { "type": "bool", @@ -309,13 +309,13 @@ class AclsArgs(object): # pylint: disable=R0903 "type": "bool", }, "time_exceeded": { - "type": "bool" + "type": "bool", }, "unreachable": { - "type": "bool" + "type": "bool", }, "telemetry_path": { - "type": "bool" + "type": "bool", }, "telemetry_queue": { "type": "bool", @@ -334,7 +334,7 @@ class AclsArgs(object): # pylint: disable=R0903 "dvmrp": {"type": "bool"}, "host_query": {"type": "bool"}, "host_report": { - "type": "bool" + "type": "bool", }, }, "type": "dict", @@ -343,7 +343,7 @@ class AclsArgs(object): # pylint: disable=R0903 "options": { "ack": {"type": "bool"}, "established": { - "type": "bool" + "type": "bool", }, "fin": {"type": "bool"}, "psh": {"type": "bool"}, @@ -386,7 +386,7 @@ class AclsArgs(object): # pylint: disable=R0903 "options": { "end": {"type": "str"}, "start": { - "type": "str" + "type": "str", }, }, "type": "dict", @@ -398,7 +398,7 @@ class AclsArgs(object): # pylint: disable=R0903 "wildcard_bits": {"type": "str"}, }, "required_together": [ - ["address", "wildcard_bits"] + ["address", "wildcard_bits"], ], "type": "dict", }, diff --git a/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py b/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py index f8e5b7188..3a33c0521 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_address_family/bgp_address_family.py @@ -136,25 +136,25 @@ class Bgp_address_familyArgs(object): # pylint: disable=R0903 "ibgp": { "type": "dict", "options": { - "parallel_paths": {"type": "int"} + "parallel_paths": {"type": "int"}, }, }, "eibgp": { "type": "dict", "options": { - "parallel_paths": {"type": "int"} + "parallel_paths": {"type": "int"}, }, }, "local": { "type": "dict", "options": { - "parallel_paths": {"type": "int"} + "parallel_paths": {"type": "int"}, }, }, "mixed": { "type": "dict", "options": { - "parallel_paths": {"type": "int"} + "parallel_paths": {"type": "int"}, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py b/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py index 041965148..9c38c15d6 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_global/bgp_global.py @@ -145,7 +145,7 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "options": { "tx_interval": {"type": "int"}, "min_rx_interval": { - "type": "int" + "type": "int", }, "multiplier": {"type": "int"}, }, @@ -162,7 +162,7 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "capability": { "type": "dict", "options": { - "suppress_4_byte_as": {"type": "bool"} + "suppress_4_byte_as": {"type": "bool"}, }, }, "description": {"type": "str"}, @@ -279,7 +279,7 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "nexthop": { "type": "dict", "options": { - "suppress_default_resolution": {"type": "bool"} + "suppress_default_resolution": {"type": "bool"}, }, }, "rd": { @@ -386,13 +386,13 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "tx_interval": { - "type": "int" + "type": "int", }, "min_rx_interval": { - "type": "int" + "type": "int", }, "multiplier": { - "type": "int" + "type": "int", }, }, }, @@ -408,7 +408,7 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "capability": { "type": "dict", "options": { - "suppress_4_byte_as": {"type": "bool"} + "suppress_4_byte_as": {"type": "bool"}, }, }, "description": {"type": "str"}, @@ -508,7 +508,7 @@ class Bgp_globalArgs(object): # pylint: disable=R0903 "connection_mode": { "type": "dict", "options": { - "passive": {"type": "bool"} + "passive": {"type": "bool"}, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py index f1a91cc5a..1fafd2fae 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_neighbor_address_family/bgp_neighbor_address_family.py @@ -138,7 +138,7 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "options": { "max_prefix_limit": {"type": "int"}, "generate_warning_threshold": { - "type": "int" + "type": "int", }, "restart_interval": {"type": "int"}, "warning_only": {"type": "bool"}, @@ -246,19 +246,19 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 }, "exist_map": {"type": "str"}, "non_exist_map": { - "type": "str" + "type": "str", }, }, }, "advertisement_interval": { - "type": "int" + "type": "int", }, "allowas_in": { "type": "dict", "options": { "set": {"type": "bool"}, "max_occurences": { - "type": "int" + "type": "int", }, }, }, @@ -295,7 +295,7 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 }, }, "disable_peer_as_check": { - "type": "bool" + "type": "bool", }, "filter_list": { "type": "dict", @@ -315,16 +315,16 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "max_prefix_limit": { - "type": "int" + "type": "int", }, "generate_warning_threshold": { - "type": "int" + "type": "int", }, "restart_interval": { - "type": "int" + "type": "int", }, "warning_only": { - "type": "bool" + "type": "bool", }, }, }, @@ -336,7 +336,7 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 }, }, "next_hop_third_party": { - "type": "bool" + "type": "bool", }, "prefix_list": { "type": "dict", @@ -346,7 +346,7 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 }, }, "rewrite_evpn_rt_asn": { - "type": "bool" + "type": "bool", }, "rewrite_rt_asn": {"type": "bool"}, "route_map": { @@ -357,7 +357,7 @@ class Bgp_neighbor_address_familyArgs(object): # pylint: disable=R0903 }, }, "route_reflector_client": { - "type": "bool" + "type": "bool", }, "send_community": { "type": "dict", diff --git a/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py b/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py index a7eec977a..d063471e0 100644 --- a/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/argspec/bgp_templates/bgp_templates.py @@ -127,7 +127,7 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 "inherit": { "type": "dict", "options": { - "peer_policy": {"type": "str"} + "peer_policy": {"type": "str"}, }, }, "maximum_prefix": { @@ -219,7 +219,7 @@ class Bgp_templatesArgs(object): # pylint: disable=R0903 "capability": { "type": "dict", "options": { - "suppress_4_byte_as": {"type": "bool"} + "suppress_4_byte_as": {"type": "bool"}, }, }, "description": {"type": "str"}, diff --git a/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py b/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py index 45cf32a6e..98c9bea7a 100644 --- a/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py +++ b/plugins/module_utils/network/nxos/argspec/logging_global/logging_global.py @@ -247,7 +247,7 @@ class Logging_globalArgs(object): # pylint: disable=R0903 "trustpoint": { "type": "dict", "options": { - "client_identity": {"type": "str"} + "client_identity": {"type": "str"}, }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py b/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py index c3b400a2a..b7bec9ca9 100644 --- a/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/argspec/ospf_interfaces/ospf_interfaces.py @@ -42,7 +42,7 @@ class Ospf_interfacesArgs(object): # pylint: disable=R0903 "type": "list", "elements": "dict", "mutually_exclusive": [ - ["passive_interface", "default_passive_interface"] + ["passive_interface", "default_passive_interface"], ], "options": { "afi": { diff --git a/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py b/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py index 193c6244a..7b17868bd 100644 --- a/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py +++ b/plugins/module_utils/network/nxos/argspec/ospfv2/ospfv2.py @@ -82,7 +82,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "nssa": { "options": { "default_information_originate": { - "type": "bool" + "type": "bool", }, "no_redistribution": {"type": "bool"}, "no_summary": {"type": "bool"}, @@ -91,17 +91,17 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "type7": { "mutually_exclusive": [ - ["always", "never"] + ["always", "never"], ], "options": { "always": { - "type": "bool" + "type": "bool", }, "never": { - "type": "bool" + "type": "bool", }, "supress_fa": { - "type": "bool" + "type": "bool", }, }, "type": "dict", @@ -202,7 +202,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "external_lsa": { "options": { "max_metric_value": { - "type": "int" + "type": "int", }, "set": {"type": "bool"}, }, @@ -213,7 +213,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "wait_for_bgp_asn": { - "type": "int" + "type": "int", }, "wait_period": {"type": "int"}, }, @@ -223,7 +223,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "summary_lsa": { "options": { "max_metric_value": { - "type": "int" + "type": "int", }, "set": {"type": "bool"}, }, @@ -244,7 +244,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "type": "list", "elements": "dict", "options": { - "area_id": {"type": "str"} + "area_id": {"type": "str"}, }, }, "multicast_intact": {"type": "bool"}, @@ -312,13 +312,13 @@ class Ospfv2Args(object): # pylint: disable=R0903 "lsa": { "options": { "hold_interval": { - "type": "int" + "type": "int", }, "max_interval": { - "type": "int" + "type": "int", }, "start_interval": { - "type": "int" + "type": "int", }, }, "type": "dict", @@ -326,13 +326,13 @@ class Ospfv2Args(object): # pylint: disable=R0903 "spf": { "options": { "initial_spf_delay": { - "type": "int" + "type": "int", }, "max_wait_time": { - "type": "int" + "type": "int", }, "min_hold_time": { - "type": "int" + "type": "int", }, }, "type": "dict", @@ -367,7 +367,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "message_digest": { - "type": "bool" + "type": "bool", }, }, "type": "dict", @@ -391,10 +391,10 @@ class Ospfv2Args(object): # pylint: disable=R0903 "nssa": { "options": { "default_information_originate": { - "type": "bool" + "type": "bool", }, "no_redistribution": { - "type": "bool" + "type": "bool", }, "no_summary": {"type": "bool"}, "set": {"type": "bool"}, @@ -409,13 +409,13 @@ class Ospfv2Args(object): # pylint: disable=R0903 ], "options": { "always": { - "type": "bool" + "type": "bool", }, "never": { - "type": "bool" + "type": "bool", }, "supress_fa": { - "type": "bool" + "type": "bool", }, }, "type": "dict", @@ -431,7 +431,7 @@ class Ospfv2Args(object): # pylint: disable=R0903 "options": { "cost": {"type": "int"}, "not_advertise": { - "type": "bool" + "type": "bool", }, "prefix": { "type": "str", @@ -529,27 +529,27 @@ class Ospfv2Args(object): # pylint: disable=R0903 "external_lsa": { "options": { "max_metric_value": { - "type": "int" + "type": "int", }, "set": { - "type": "bool" + "type": "bool", }, }, "type": "dict", }, "include_stub": { - "type": "bool" + "type": "bool", }, "on_startup": { "options": { "set": { - "type": "bool" + "type": "bool", }, "wait_for_bgp_asn": { - "type": "int" + "type": "int", }, "wait_period": { - "type": "int" + "type": "int", }, }, "type": "dict", @@ -558,10 +558,10 @@ class Ospfv2Args(object): # pylint: disable=R0903 "summary_lsa": { "options": { "max_metric_value": { - "type": "int" + "type": "int", }, "set": { - "type": "bool" + "type": "bool", }, }, "type": "dict", @@ -637,13 +637,13 @@ class Ospfv2Args(object): # pylint: disable=R0903 "lsa": { "options": { "hold_interval": { - "type": "int" + "type": "int", }, "max_interval": { - "type": "int" + "type": "int", }, "start_interval": { - "type": "int" + "type": "int", }, }, "type": "dict", @@ -651,13 +651,13 @@ class Ospfv2Args(object): # pylint: disable=R0903 "spf": { "options": { "initial_spf_delay": { - "type": "int" + "type": "int", }, "max_wait_time": { - "type": "int" + "type": "int", }, "min_hold_time": { - "type": "int" + "type": "int", }, }, "type": "dict", diff --git a/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py b/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py index 0854a62dc..a9294a406 100644 --- a/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py +++ b/plugins/module_utils/network/nxos/argspec/ospfv3/ospfv3.py @@ -85,7 +85,7 @@ class Ospfv3Args(object): # pylint: disable=R0903 }, "cost": {"type": "int"}, "not_advertise": { - "type": "bool" + "type": "bool", }, }, }, @@ -163,13 +163,13 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "initial_spf_delay": { - "type": "int" + "type": "int", }, "min_hold_time": { - "type": "int" + "type": "int", }, "max_wait_time": { - "type": "int" + "type": "int", }, }, }, @@ -189,7 +189,7 @@ class Ospfv3Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "default_information_originate": { - "type": "bool" + "type": "bool", }, "no_redistribution": {"type": "bool"}, "no_summary": {"type": "bool"}, @@ -201,13 +201,13 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "always": { - "type": "bool" + "type": "bool", }, "never": { - "type": "bool" + "type": "bool", }, "supress_fa": { - "type": "bool" + "type": "bool", }, }, }, @@ -282,7 +282,7 @@ class Ospfv3Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "max_metric_value": { - "type": "int" + "type": "int", }, }, }, @@ -293,7 +293,7 @@ class Ospfv3Args(object): # pylint: disable=R0903 "set": {"type": "bool"}, "wait_period": {"type": "int"}, "wait_for_bgp_asn": { - "type": "int" + "type": "int", }, }, }, @@ -302,7 +302,7 @@ class Ospfv3Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "max_metric_value": { - "type": "int" + "type": "int", }, }, }, @@ -330,13 +330,13 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "start_interval": { - "type": "int" + "type": "int", }, "hold_interval": { - "type": "int" + "type": "int", }, "max_interval": { - "type": "int" + "type": "int", }, }, }, @@ -361,10 +361,10 @@ class Ospfv3Args(object): # pylint: disable=R0903 "options": { "set": {"type": "bool"}, "default_information_originate": { - "type": "bool" + "type": "bool", }, "no_redistribution": { - "type": "bool" + "type": "bool", }, "no_summary": {"type": "bool"}, "route_map": {"type": "str"}, @@ -375,13 +375,13 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "always": { - "type": "bool" + "type": "bool", }, "never": { - "type": "bool" + "type": "bool", }, "supress_fa": { - "type": "bool" + "type": "bool", }, }, }, @@ -453,27 +453,27 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "set": { - "type": "bool" + "type": "bool", }, "max_metric_value": { - "type": "int" + "type": "int", }, }, }, "stub_prefix_lsa": { - "type": "bool" + "type": "bool", }, "on_startup": { "type": "dict", "options": { "set": { - "type": "bool" + "type": "bool", }, "wait_period": { - "type": "int" + "type": "int", }, "wait_for_bgp_asn": { - "type": "int" + "type": "int", }, }, }, @@ -481,10 +481,10 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "set": { - "type": "bool" + "type": "bool", }, "max_metric_value": { - "type": "int" + "type": "int", }, }, }, @@ -511,13 +511,13 @@ class Ospfv3Args(object): # pylint: disable=R0903 "type": "dict", "options": { "start_interval": { - "type": "int" + "type": "int", }, "hold_interval": { - "type": "int" + "type": "int", }, "max_interval": { - "type": "int" + "type": "int", }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py b/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py index 91de47ec9..2b4c1f52a 100644 --- a/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py +++ b/plugins/module_utils/network/nxos/argspec/route_maps/route_maps.py @@ -120,18 +120,18 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "prefix": { - "type": "str" - } + "type": "str", + }, }, }, "group_range": { "type": "dict", "options": { "first": { - "type": "str" + "type": "str", }, "last": { - "type": "str" + "type": "str", }, }, }, @@ -139,7 +139,7 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "prefix": { - "type": "str" + "type": "str", }, "rp_type": { "type": "str", @@ -193,18 +193,18 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "prefix": { - "type": "str" - } + "type": "str", + }, }, }, "group_range": { "type": "dict", "options": { "first": { - "type": "str" + "type": "str", }, "last": { - "type": "str" + "type": "str", }, }, }, @@ -212,7 +212,7 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "type": "dict", "options": { "prefix": { - "type": "str" + "type": "str", }, "rp_type": { "type": "str", @@ -318,7 +318,7 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "half_life": {"type": "int"}, "start_reuse_route": {"type": "int"}, "start_suppress_route": { - "type": "int" + "type": "int", }, "max_suppress_time": {"type": "int"}, }, @@ -337,12 +337,12 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "gateway_ip": { "type": "dict", "mutually_exclusive": [ - ["ip", "use_nexthop"] + ["ip", "use_nexthop"], ], "options": { "ip": {"type": "str"}, "use_nexthop": { - "type": "bool" + "type": "bool", }, }, }, @@ -372,7 +372,7 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "address": { "type": "dict", "options": { - "prefix_list": {"type": "str"} + "prefix_list": {"type": "str"}, }, }, "precedence": {"type": "str"}, @@ -407,10 +407,10 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "default": False, }, "peer_address": { - "type": "bool" + "type": "bool", }, "redist_unchanged": { - "type": "bool" + "type": "bool", }, "unchanged": {"type": "bool"}, "verify_availability": { @@ -449,7 +449,7 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "address": { "type": "dict", "options": { - "prefix_list": {"type": "str"} + "prefix_list": {"type": "str"}, }, }, "precedence": {"type": "str"}, @@ -471,10 +471,10 @@ class Route_mapsArgs(object): # pylint: disable=R0903 "bandwidth": {"type": "int"}, "igrp_delay_metric": {"type": "int"}, "igrp_reliability_metric": { - "type": "int" + "type": "int", }, "igrp_effective_bandwidth_metric": { - "type": "int" + "type": "int", }, "igrp_mtu": {"type": "int"}, }, diff --git a/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py b/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py index 9cba81b8f..ada6a8784 100644 --- a/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py +++ b/plugins/module_utils/network/nxos/argspec/snmp_server/snmp_server.py @@ -133,14 +133,14 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "options": { "enable": {"type": "bool"}, "cefcMIBEnableStatusNotification": { - "type": "bool" + "type": "bool", }, "entity_fan_status_change": {"type": "bool"}, "entity_mib_change": {"type": "bool"}, "entity_module_inserted": {"type": "bool"}, "entity_module_removed": {"type": "bool"}, "entity_module_status_change": { - "type": "bool" + "type": "bool", }, "entity_power_out_change": {"type": "bool"}, "entity_power_status_change": {"type": "bool"}, @@ -170,11 +170,11 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "enable": {"type": "bool"}, "notify_license_expiry": {"type": "bool"}, "notify_license_expiry_warning": { - "type": "bool" + "type": "bool", }, "notify_licensefile_missing": {"type": "bool"}, "notify_no_license_for_feature": { - "type": "bool" + "type": "bool", }, }, }, @@ -183,7 +183,7 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "options": { "enable": {"type": "bool"}, "cErrDisableInterfaceEventRev1": { - "type": "bool" + "type": "bool", }, "cieLinkDown": {"type": "bool"}, "cieLinkUp": {"type": "bool"}, @@ -265,7 +265,7 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "options": { "enable": {"type": "bool"}, "cseFailSwCoreNotifyExtended": { - "type": "bool" + "type": "bool", }, }, }, @@ -282,7 +282,7 @@ class Snmp_serverArgs(object): # pylint: disable=R0903 "enable": {"type": "bool"}, "upgradeJobStatusNotify": {"type": "bool"}, "upgradeOpNotifyOnCompletion": { - "type": "bool" + "type": "bool", }, }, }, diff --git a/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py b/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py index e6945f3ce..4e529f442 100644 --- a/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py +++ b/plugins/module_utils/network/nxos/argspec/static_routes/static_routes.py @@ -58,7 +58,7 @@ class Static_routesArgs(object): # pylint: disable=R0903 "elements": "dict", "options": { "forward_router_address": { - "type": "str" + "type": "str", }, "interface": {"type": "str"}, "admin_distance": {"type": "int"}, diff --git a/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py b/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py index 68f47d777..184b8d033 100644 --- a/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py +++ b/plugins/module_utils/network/nxos/config/acl_interfaces/acl_interfaces.py @@ -23,9 +23,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( get_interface_type, normalize_interface, @@ -57,7 +55,7 @@ def get_acl_interfaces_facts(self, data=None): data=data, ) acl_interfaces_facts = facts["ansible_network_resources"].get( - "acl_interfaces" + "acl_interfaces", ) if not acl_interfaces_facts: return [] @@ -141,13 +139,10 @@ def set_state(self, want, have): :returns: the commands necessary to migrate the current configuration to the desired configuration """ - if ( - self.state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if self.state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - self.state + self.state, ), ) @@ -195,7 +190,9 @@ def _state_replaced(self, want, have): want_afi = [] if want.get("access_groups"): want_afi = search_obj_in_list( - ag["afi"], want["access_groups"], "afi" + ag["afi"], + want["access_groups"], + "afi", ) if not want_afi: # whatever in have is not in want @@ -210,17 +207,13 @@ def _state_replaced(self, want, have): del_acl.append(acl) afi = want_afi["afi"] del_dict["access_groups"].append( - {"afi": afi, "acls": del_acl} + {"afi": afi, "acls": del_acl}, ) commands.extend(self._state_deleted([del_dict], have)) commands.extend(self._state_merged(want, have)) new_commands.append(commands[0]) - commands = [ - commands[i] - for i in range(1, len(commands)) - if commands[i] != commands[0] - ] + commands = [commands[i] for i in range(1, len(commands)) if commands[i] != commands[0]] new_commands.extend(commands) return new_commands @@ -259,34 +252,32 @@ def set_commands(self, want, have, deleted=False): if w_afi["afi"] == "ipv4": ip = "ip" have_afi = search_obj_in_list( - w_afi["afi"], have_name["access_groups"], "afi" + w_afi["afi"], + have_name["access_groups"], + "afi", ) if have_afi: new_acls = [] if deleted: if w_afi.get("acls") and have_afi.get("acls"): new_acls = [ - acl - for acl in w_afi.get("acls") - if acl in have_afi.get("acls") + acl for acl in w_afi.get("acls") if acl in have_afi.get("acls") ] elif "acls" not in w_afi.keys(): new_acls = have_afi.get("acls") else: if w_afi.get("acls"): new_acls = [ - acl - for acl in w_afi["acls"] - if acl not in have_afi["acls"] + acl for acl in w_afi["acls"] if acl not in have_afi["acls"] ] commands.extend( - self.process_acl(new_acls, ip, deleted) + self.process_acl(new_acls, ip, deleted), ) else: if not deleted: if w_afi.get("acls"): commands.extend( - self.process_acl(w_afi["acls"], ip) + self.process_acl(w_afi["acls"], ip), ) else: # only name is given to delete @@ -323,7 +314,7 @@ def process_acl(self, acls, ip, deleted=False): if ip == "ipv6": ag = " traffic-filter " commands.append( - no + ip + port + ag + acl["name"] + " " + acl["direction"] + no + ip + port + ag + acl["name"] + " " + acl["direction"], ) return commands @@ -343,7 +334,7 @@ def _state_deleted(self, main_want, have): else: for want in main_want: commands.extend( - self.set_commands(want, have, deleted=True) + self.set_commands(want, have, deleted=True), ) else: for h in have: diff --git a/plugins/module_utils/network/nxos/config/acls/acls.py b/plugins/module_utils/network/nxos/config/acls/acls.py index dcc4fc7a8..ef9c85514 100644 --- a/plugins/module_utils/network/nxos/config/acls/acls.py +++ b/plugins/module_utils/network/nxos/config/acls/acls.py @@ -17,9 +17,7 @@ import re -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import ( ConfigBase, ) @@ -31,9 +29,7 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acls.acls import ( AclsArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( search_obj_in_list, ) @@ -226,57 +222,43 @@ def convert_values(self, want): ace["dscp"] = ace["dscp"].lower() if "precedence" in ace.keys(): if ace["precedence"].isdigit(): - ace["precedence"] = precedence[ - int(ace["precedence"]) - ] + ace["precedence"] = precedence[int(ace["precedence"])] if ( "protocol" in ace.keys() and ace["protocol"].isdigit() and int(ace["protocol"]) in protocol.keys() ): - ace["protocol"] = protocol[ - int(ace["protocol"]) - ] + ace["protocol"] = protocol[int(ace["protocol"])] # convert number to name - if "protocol" in ace.keys() and ace[ - "protocol" - ] in ["tcp", "udp"]: + if "protocol" in ace.keys() and ace["protocol"] in ["tcp", "udp"]: for x in ["source", "destination"]: if "port_protocol" in ace[x].keys(): key = list( - ace[x]["port_protocol"].keys() + ace[x]["port_protocol"].keys(), )[0] # key could be eq,gt,lt,neq or range if key != "range": val = ace[x]["port_protocol"][key] - if ( - val.isdigit() - and int(val) - in port_protocol.keys() - ): - ace[x]["port_protocol"][ - key - ] = port_protocol[int(val)] + if val.isdigit() and int(val) in port_protocol.keys(): + ace[x]["port_protocol"][key] = port_protocol[ + int(val) + ] else: st = int( - ace[x]["port_protocol"][ - "range" - ]["start"] + ace[x]["port_protocol"]["range"]["start"], ) end = int( - ace[x]["port_protocol"][ - "range" - ]["end"] + ace[x]["port_protocol"]["range"]["end"], ) if st in port_protocol.keys(): - ace[x]["port_protocol"][ - "range" - ]["start"] = port_protocol[st] + ace[x]["port_protocol"]["range"][ + "start" + ] = port_protocol[st] if end in port_protocol.keys(): - ace[x]["port_protocol"][ - "range" - ]["end"] = port_protocol[end] + ace[x]["port_protocol"]["range"][ + "end" + ] = port_protocol[end] return want def set_state(self, want, have): @@ -342,18 +324,16 @@ def _state_replaced(self, want, have): # creates new ACL in replaced state merge_dict = {"afi": want["afi"], "acls": [w]} commands.extend( - self._state_merged(merge_dict, have) + self._state_merged(merge_dict, have), ) else: # acl in want exists in have have_name = search_obj_in_list( - w["name"], have_afi["acls"], "name" - ) - have_aces = ( - have_name.get("aces") - if have_name.get("aces") - else [] + w["name"], + have_afi["acls"], + "name", ) + have_aces = have_name.get("aces") if have_name.get("aces") else [] merge_aces = [] del_aces = [] w_aces = w.get("aces") if w.get("aces") else [] @@ -367,21 +347,21 @@ def _state_replaced(self, want, have): merge_dict = { "afi": want["afi"], "acls": [ - {"name": w["name"], "aces": merge_aces} + {"name": w["name"], "aces": merge_aces}, ], } del_dict = { "afi": want["afi"], "acls": [ - {"name": w["name"], "aces": del_aces} + {"name": w["name"], "aces": del_aces}, ], } if del_dict["acls"]: acl_commands.extend( - self._state_deleted([del_dict], have) + self._state_deleted([del_dict], have), ) acl_commands.extend( - self._state_merged(merge_dict, have) + self._state_merged(merge_dict, have), ) for i in range(1, len(acl_commands)): @@ -418,7 +398,9 @@ def _state_overridden(self, want, have): w = search_obj_in_list(h["afi"], want, "afi") for h_acl in h["acls"]: w_acl = search_obj_in_list( - h_acl["name"], w["acls"], "name" + h_acl["name"], + w["acls"], + "name", ) if not w_acl: del_dict = { @@ -459,10 +441,7 @@ def _state_deleted(self, want, have): if have_afi: if w.get("acls"): for acl in w["acls"]: - if ( - "aces" in acl.keys() - and self.state != "deleted" - ): + if "aces" in acl.keys() and self.state != "deleted": have_name = search_obj_in_list( acl["name"], have_afi["acls"], @@ -476,14 +455,11 @@ def _state_deleted(self, want, have): # only sequence number is specified to be deleted if "aces" in have_name.keys(): for h_ace in have_name["aces"]: - if ( - h_ace["sequence"] - == ace["sequence"] - ): + if h_ace["sequence"] == ace["sequence"]: ace_commands.append( "no " + str( - ace["sequence"] + ace["sequence"], ), ) flag = 1 @@ -491,16 +467,13 @@ def _state_deleted(self, want, have): if "aces" in have_name.keys(): for h_ace in have_name["aces"]: # when want['ace'] does not have seq number - if ( - "sequence" - not in ace.keys() - ): + if "sequence" not in ace.keys(): del h_ace["sequence"] if ace == h_ace: ace_commands.append( "no " + self.process_ace( - ace + ace, ), ) flag = 1 @@ -517,7 +490,7 @@ def _state_deleted(self, want, have): acl_names.append(acl["name"]) for name in acl_names: commands.append( - "no " + ip + " access-list " + name + "no " + ip + " access-list " + name, ) else: @@ -527,7 +500,7 @@ def _state_deleted(self, want, have): acl_names.append(h["name"]) for name in acl_names: commands.append( - "no " + ip + " access-list " + name + "no " + ip + " access-list " + name, ) else: v6 = [] @@ -572,7 +545,9 @@ def set_commands(self, want, have): if want.get("acls"): for w_acl in want["acls"]: have_acl = search_obj_in_list( - w_acl["name"], have_afi["acls"], "name" + w_acl["name"], + have_afi["acls"], + "name", ) name = w_acl["name"] flag = 0 @@ -587,9 +562,7 @@ def set_commands(self, want, have): # For replaced and overridden, rule is deleted in the state's config) ace_list = [ - item - for item in w_acl["aces"] - if "sequence" not in item.keys() + item for item in w_acl["aces"] if "sequence" not in item.keys() ] # case 1 want_seq = [ @@ -598,21 +571,17 @@ def set_commands(self, want, have): if "sequence" in item.keys() ] - have_seq = [ - item["sequence"] - for item in have_acl["aces"] - ] + have_seq = [item["sequence"] for item in have_acl["aces"]] new_seq = list(set(want_seq) - set(have_seq)) common_seq = list( - set(want_seq).intersection(set(have_seq)) + set(want_seq).intersection(set(have_seq)), ) temp_list = [ item for item in w_acl["aces"] - if "sequence" in item.keys() - and item["sequence"] in new_seq + if "sequence" in item.keys() and item["sequence"] in new_seq ] # case 2 ace_list.extend(temp_list) for w in w_acl["aces"]: @@ -633,10 +602,7 @@ def set_commands(self, want, have): ], }, ) - if ( - "sequence" in w.keys() - and w["sequence"] in common_seq - ): + if "sequence" in w.keys() and w["sequence"] in common_seq: temp_obj = search_obj_in_list( w["sequence"], have_acl["aces"], @@ -658,13 +624,14 @@ def set_commands(self, want, have): ace_list = list(w_acl["aces"]) for w_ace in ace_list: ace_commands.append( - self.process_ace(w_ace).strip() + self.process_ace(w_ace).strip(), ) flag = 1 if flag: ace_commands.insert( - 0, ip + "access-list " + name + 0, + ip + "access-list " + name, ) else: @@ -672,7 +639,7 @@ def set_commands(self, want, have): if "aces" in w_acl.keys(): for w_ace in w_acl["aces"]: commands.append( - self.process_ace(w_ace).strip() + self.process_ace(w_ace).strip(), ) commands.extend(ace_commands) else: @@ -700,14 +667,15 @@ def process_ace(self, w_ace): command += w_ace["protocol"] + " " src = self.get_address(w_ace["source"], w_ace["protocol"]) dest = self.get_address( - w_ace["destination"], w_ace["protocol"] + w_ace["destination"], + w_ace["protocol"], ) command += src + dest if "protocol_options" in ace_keys: pro = list(w_ace["protocol_options"].keys())[0] if pro != w_ace["protocol"]: self._module.fail_json( - msg="protocol and protocol_options mismatch" + msg="protocol and protocol_options mismatch", ) flags = "" for k in w_ace["protocol_options"][pro].keys(): @@ -733,12 +701,10 @@ def get_address(self, endpoint, pro=""): if "address" in keys: if "wildcard_bits" not in keys: self._module.fail_json( - msg="wildcard bits not specified for address" + msg="wildcard bits not specified for address", ) else: - ret_addr = ( - endpoint["address"] + " " + endpoint["wildcard_bits"] + " " - ) + ret_addr = endpoint["address"] + " " + endpoint["wildcard_bits"] + " " elif "any" in keys: ret_addr = "any " elif "host" in keys: @@ -756,13 +722,7 @@ def get_options(self, item): com = "" subkey = list(item.keys()) if "range" in subkey: - com = ( - "range " - + item["range"]["start"] - + " " - + item["range"]["end"] - + " " - ) + com = "range " + item["range"]["start"] + " " + item["range"]["end"] + " " else: com = subkey[0] + " " + item[subkey[0]] + " " return com diff --git a/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py b/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py index 2b81658a9..b01e0653f 100644 --- a/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py +++ b/plugins/module_utils/network/nxos/config/bfd_interfaces/bfd_interfaces.py @@ -24,9 +24,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, search_obj_in_list, @@ -58,7 +56,8 @@ def get_bfd_interfaces_facts(self, data=None): data=data, ) bfd_interfaces_facts = facts["ansible_network_resources"].get( - "bfd_interfaces", [] + "bfd_interfaces", + [], ) platform = facts.get("ansible_net_platform", "") @@ -87,7 +86,7 @@ def execute_module(self): if self.state in self.ACTION_STATES or self.state == "rendered": commands.extend( - self.set_config(existing_bfd_interfaces_facts, platform) + self.set_config(existing_bfd_interfaces_facts, platform), ) if commands and self.state in self.ACTION_STATES: @@ -114,7 +113,7 @@ def execute_module(self): msg="value of running_config parameter must not be empty for state parsed", ) result["parsed"], platform = self.get_bfd_interfaces_facts( - data=running_config + data=running_config, ) if self.state in self.ACTION_STATES: @@ -166,13 +165,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) @@ -228,7 +224,7 @@ def _state_overridden(self, want, have): # Clean up bfd attrs for any interfaces not listed in the play h = flatten_dict(h) obj_in_want = flatten_dict( - search_obj_in_list(h["name"], want, "name") + search_obj_in_list(h["name"], want, "name"), ) if obj_in_want: # Let the 'want' loop handle all vals for this interface @@ -264,7 +260,7 @@ def _state_deleted(self, want, have): if want: for w in want: obj_in_have = flatten_dict( - search_obj_in_list(w["name"], have, "name") + search_obj_in_list(w["name"], have, "name"), ) cmds.extend(self.del_attribs(obj_in_have)) else: @@ -320,7 +316,7 @@ def add_commands(self, want): def set_commands(self, want, have): cmds = [] obj_in_have = flatten_dict( - search_obj_in_list(want["name"], have, "name") + search_obj_in_list(want["name"], have, "name"), ) if not obj_in_have: cmds = self.add_commands(want) diff --git a/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py b/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py index 2aae0a64a..9a91e67ce 100644 --- a/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/config/bgp_address_family/bgp_address_family.py @@ -29,9 +29,7 @@ remove_empties, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_address_family import ( Bgp_address_familyTemplate, ) @@ -116,9 +114,7 @@ def generate_commands(self): # if state is overridden or deleted, remove superfluos config if self.state in ["deleted", "overridden"]: - if ( - haved and haved["as_number"] == wantd.get("as_number") - ) or not wantd: + if (haved and haved["as_number"] == wantd.get("as_number")) or not wantd: remove = True if self.state == "deleted" else False purge = True if not wantd else False self._remove_af(want_af, have_af, remove=remove, purge=purge) @@ -126,7 +122,11 @@ def generate_commands(self): for k, hvrf in iteritems(hvrfs): wvrf = wvrfs.get(k, {}) self._remove_af( - wvrf, hvrf, vrf=k, remove=remove, purge=purge + wvrf, + hvrf, + vrf=k, + remove=remove, + purge=purge, ) if self.state in ["merged", "replaced", "overridden", "rendered"]: @@ -147,7 +147,8 @@ def generate_commands(self): if self.commands: self.commands.insert( - 0, "router bgp {as_number}".format(**haved or wantd) + 0, + "router bgp {as_number}".format(**haved or wantd), ) def _compare(self, want, have): @@ -204,19 +205,13 @@ def _build_key(data): # transform parameters which are # list of dicts to dict of dicts for item in entry.get("address_family", []): - item["aggregate_address"] = { - x["prefix"]: x for x in item.get("aggregate_address", []) - } + item["aggregate_address"] = {x["prefix"]: x for x in item.get("aggregate_address", [])} item["inject_map"] = { - (x["route_map"], x["exist_map"]): x - for x in item.get("inject_map", []) - } - item["networks"] = { - x["prefix"]: x for x in item.get("networks", []) + (x["route_map"], x["exist_map"]): x for x in item.get("inject_map", []) } + item["networks"] = {x["prefix"]: x for x in item.get("networks", [])} item["redistribute"] = { - (x.get("id"), x["protocol"]): x - for x in item.get("redistribute", []) + (x.get("id"), x["protocol"]): x for x in item.get("redistribute", []) } # transform all entries under @@ -249,7 +244,12 @@ def _build_key(data): # final structure: https://gist.github.com/NilashishC/628dae5fe39a4908e87c9e833bfbe57d def _remove_af( - self, want_af, have_af, vrf=None, remove=False, purge=False + self, + want_af, + have_af, + vrf=None, + remove=False, + purge=False, ): cur_ptr = len(self.commands) for k, v in iteritems(have_af): diff --git a/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py b/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py index 7aa6b51c6..bdcb55339 100644 --- a/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/nxos/config/bgp_global/bgp_global.py @@ -26,9 +26,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_global import ( Bgp_globalTemplate, ) @@ -134,15 +132,11 @@ def generate_commands(self): # if state is deleted, clean up global params if self.state == "deleted": - if not self.want or ( - self.have.get("as_number") == self.want.get("as_number") - ): + if not self.want or (self.have.get("as_number") == self.want.get("as_number")): self._compare(want={}, have=self.have) elif self.state == "purged": - if not self.want or ( - self.have.get("as_number") == self.want.get("as_number") - ): + if not self.want or (self.have.get("as_number") == self.want.get("as_number")): self.addcmd(self.have or {}, "as_number", True) else: @@ -170,9 +164,7 @@ def _compare(self, want, have, vrf=None): begin, self._tmplt.render( want or have, - "vrf" - if "vrf" in (want.keys() or have.keys()) - else "as_number", + "vrf" if "vrf" in (want.keys() or have.keys()) else "as_number", False, ), ) @@ -244,7 +236,8 @@ def _compare_neighbors(self, want, have, vrf=None): if len(self.commands) != begin or (entry and not have_nbr): self.commands.insert( - begin, self._tmplt.render(entry, "neighbor_address", False) + begin, + self._tmplt.render(entry, "neighbor_address", False), ) # cleanup remaining neighbors @@ -299,7 +292,7 @@ def _vrfs_compare(self, want, have): self._module.fail_json( msg="VRF {0} has address-family configurations. " "Please use the nxos_bgp_af module to remove those first.".format( - name + name, ), ) else: @@ -329,13 +322,10 @@ def _build_key(x): for x in entry["neighbors"]: if "path_attribute" in x: x["path_attribute"] = { - _build_key(item): item - for item in x.get("path_attribute", []) + _build_key(item): item for item in x.get("path_attribute", []) } - entry["neighbors"] = { - x["neighbor_address"]: x for x in entry.get("neighbors", []) - } + entry["neighbors"] = {x["neighbor_address"]: x for x in entry.get("neighbors", [])} if "vrfs" in entry: entry["vrfs"] = {x["vrf"]: x for x in entry.get("vrfs", [])} @@ -344,7 +334,7 @@ def _build_key(x): def _get_config(self): return self._connection.get( - "show running-config | section '^router bgp'" + "show running-config | section '^router bgp'", ) def _build_af_data(self): diff --git a/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py index 17a1d706b..f2b5b6eba 100644 --- a/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/config/bgp_neighbor_address_family/bgp_neighbor_address_family.py @@ -27,9 +27,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_neighbor_address_family import ( Bgp_neighbor_address_familyTemplate, ) @@ -127,7 +125,8 @@ def generate_commands(self): if self.commands: self.commands.insert( - 0, "router bgp {as_number}".format(**haved or wantd) + 0, + "router bgp {as_number}".format(**haved or wantd), ) def _compare(self, want, have, vrf=""): @@ -176,7 +175,8 @@ def _compare(self, want, have, vrf=""): if len(self.commands) != begin: self.commands.insert( - begin, "neighbor {0}".format(w_nbr["neighbor_address"]) + begin, + "neighbor {0}".format(w_nbr["neighbor_address"]), ) if self.state in ["overridden", "deleted"]: @@ -188,7 +188,8 @@ def _compare(self, want, have, vrf=""): self.addcmd(have_af, "address_family", True) if len(self.commands) != begin: self.commands.insert( - begin, "neighbor {0}".format(h_nbr["neighbor_address"]) + begin, + "neighbor {0}".format(h_nbr["neighbor_address"]), ) if vrf: @@ -212,12 +213,9 @@ def _bgp_list_to_dict(self, data): for nbr in data["neighbors"]: if "address_family" in nbr: nbr["address_family"] = { - (x["afi"], x.get("safi")): x - for x in nbr["address_family"] + (x["afi"], x.get("safi")): x for x in nbr["address_family"] } - data["neighbors"] = { - x["neighbor_address"]: x for x in data["neighbors"] - } + data["neighbors"] = {x["neighbor_address"]: x for x in data["neighbors"]} if "vrfs" in data: for vrf in data["vrfs"]: diff --git a/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py b/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py index 441250c22..ac76720de 100644 --- a/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/config/bgp_templates/bgp_templates.py @@ -27,9 +27,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.bgp_templates import ( Bgp_templatesTemplate, ) @@ -132,9 +130,7 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} wantd = {} # remove superfluous config for overridden and deleted @@ -150,7 +146,8 @@ def generate_commands(self): self._compare(want=want, have=haved.pop(k, {})) if len(self.commands) != begin: self.commands.insert( - begin, "template peer {0}".format(want["name"]) + begin, + "template peer {0}".format(want["name"]), ) if self.commands: @@ -193,11 +190,12 @@ def _afs_compare(self, want, have): self._af_compare(want=wentry, have=have.pop(name, {})) if begin != len(self.commands): self.commands.insert( - begin, self._tmplt.render(wentry, "address_family", False) + begin, + self._tmplt.render(wentry, "address_family", False), ) for name, hentry in iteritems(have): self.commands.append( - self._tmplt.render(hentry, "address_family", True) + self._tmplt.render(hentry, "address_family", True), ) def _af_compare(self, want, have): @@ -234,13 +232,11 @@ def _build_key(x): for entry in v: if "address_family" in entry: entry["address_family"] = { - (x["afi"], x.get("safi")): x - for x in entry["address_family"] + (x["afi"], x.get("safi")): x for x in entry["address_family"] } if "path_attribute" in entry: entry["path_attribute"] = { - _build_key(x): x - for x in entry.get("path_attribute", []) + _build_key(x): x for x in entry.get("path_attribute", []) } # attach top-level keys with their values diff --git a/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py b/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py index 3f9f2c688..faeb47564 100644 --- a/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/config/fc_interfaces/fc_interfaces.py @@ -27,9 +27,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.fc_interfaces import ( Fc_interfacesTemplate, ) @@ -87,9 +85,7 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} wantd = {} # remove superfluous config for overridden and deleted @@ -102,9 +98,7 @@ def generate_commands(self): self._compare(want=want, have=haved.pop(k, {})) modified_list = [ - "switchport trunk mode on" - if item.startswith("no switchport trunk mode") - else item + "switchport trunk mode on" if item.startswith("no switchport trunk mode") else item for item in self.commands ] self.commands = modified_list @@ -204,14 +198,16 @@ def _compare(self, want, have): self.addcmd(have, "enabled", False) ana_cmds = self._calculate_ana_config( - want.get("analytics", ""), have.get("analytics", "") + want.get("analytics", ""), + have.get("analytics", ""), ) self.commands.extend(ana_cmds) if len(self.commands) != begin: self.commands.insert( - begin, self._tmplt.render(want or have, "interface", False) + begin, + self._tmplt.render(want or have, "interface", False), ) def normalize_interface_names(self, param): diff --git a/plugins/module_utils/network/nxos/config/hostname/hostname.py b/plugins/module_utils/network/nxos/config/hostname/hostname.py index 1c4082f33..42ed06946 100644 --- a/plugins/module_utils/network/nxos/config/hostname/hostname.py +++ b/plugins/module_utils/network/nxos/config/hostname/hostname.py @@ -22,9 +22,7 @@ ResourceModule, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.hostname import ( HostnameTemplate, ) diff --git a/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py b/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py index b82af93c8..4e33ed14d 100644 --- a/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py +++ b/plugins/module_utils/network/nxos/config/hsrp_interfaces/hsrp_interfaces.py @@ -22,9 +22,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, normalize_interface, @@ -56,7 +54,8 @@ def get_hsrp_interfaces_facts(self, data=None): data=data, ) hsrp_interfaces_facts = facts["ansible_network_resources"].get( - "hsrp_interfaces", [] + "hsrp_interfaces", + [], ) return hsrp_interfaces_facts @@ -102,7 +101,7 @@ def execute_module(self): msg="value of running_config parameter must not be empty for state parsed", ) result["parsed"] = self.get_hsrp_interfaces_facts( - data=running_config + data=running_config, ) if self.state in self.ACTION_STATES: @@ -145,13 +144,10 @@ def set_state(self, want, have): """ state = self._module.params["state"] # check for 'config' keyword in play - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) @@ -241,7 +237,7 @@ def _state_deleted(self, want, have): if want: for w in want: obj_in_have = flatten_dict( - search_obj_in_list(w["name"], have, "name") + search_obj_in_list(w["name"], have, "name"), ) cmds.extend(self.del_attribs(obj_in_have)) else: @@ -280,11 +276,7 @@ def add_commands(self, want, obj_in_have): if want["bfd"] == "enable": cmd = "hsrp bfd" cmds.append(cmd) - elif ( - want["bfd"] == "disable" - and obj_in_have - and obj_in_have.get("bfd") == "enable" - ): + elif want["bfd"] == "disable" and obj_in_have and obj_in_have.get("bfd") == "enable": cmd = "no hsrp bfd" cmds.append(cmd) diff --git a/plugins/module_utils/network/nxos/config/interfaces/interfaces.py b/plugins/module_utils/network/nxos/config/interfaces/interfaces.py index f67599b28..bd160271e 100644 --- a/plugins/module_utils/network/nxos/config/interfaces/interfaces.py +++ b/plugins/module_utils/network/nxos/config/interfaces/interfaces.py @@ -29,9 +29,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( default_intf_enabled, ) @@ -68,7 +66,7 @@ def get_interfaces_facts(self, data=None): data=data, ) interfaces_facts = self.facts["ansible_network_resources"].get( - "interfaces" + "interfaces", ) return interfaces_facts @@ -188,10 +186,7 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state, @@ -438,7 +433,8 @@ def add_commands(self, d, obj_in_have=None): if "enabled" in d: have_enabled = ( obj_in_have.get( - "enabled", self.default_enabled(d, obj_in_have) + "enabled", + self.default_enabled(d, obj_in_have), ) or False ) @@ -488,9 +484,7 @@ def render_interface_defaults(self, config, intfs): Run through the gathered interfaces and tag their default enabled state. """ intf_defs = {} - L3_enabled = ( - True if re.search("N[56]K", self.get_platform()) else False - ) + L3_enabled = True if re.search("N[56]K", self.get_platform()) else False intf_defs = { "sysdefs": { "mode": None, @@ -501,16 +495,12 @@ def render_interface_defaults(self, config, intfs): pat = "(no )*system default switchport$" m = re.search(pat, config, re.MULTILINE) if m: - intf_defs["sysdefs"]["mode"] = ( - "layer3" if "no " in m.groups() else "layer2" - ) + intf_defs["sysdefs"]["mode"] = "layer3" if "no " in m.groups() else "layer2" pat = "(no )*system default switchport shutdown$" m = re.search(pat, config, re.MULTILINE) if m: - intf_defs["sysdefs"]["L2_enabled"] = ( - True if "no " in m.groups() else False - ) + intf_defs["sysdefs"]["L2_enabled"] = True if "no " in m.groups() else False for item in intfs: intf_defs[item["name"]] = default_intf_enabled( diff --git a/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py b/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py index 2401cc619..c69eb3460 100644 --- a/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py +++ b/plugins/module_utils/network/nxos/config/l2_interfaces/l2_interfaces.py @@ -26,9 +26,7 @@ remove_empties, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, normalize_interface, @@ -64,7 +62,7 @@ def get_l2_interfaces_facts(self, data=None): data=data, ) l2_interfaces_facts = facts["ansible_network_resources"].get( - "l2_interfaces" + "l2_interfaces", ) if not l2_interfaces_facts: return [] @@ -109,7 +107,7 @@ def execute_module(self): msg="value of running_config parameter must not be empty for state parsed", ) result["parsed"] = self.get_l2_interfaces_facts( - data=running_config + data=running_config, ) if self.state in self.ACTION_STATES: @@ -165,13 +163,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) @@ -186,7 +181,7 @@ def set_state(self, want, have): commands.extend(self._state_merged(flatten_dict(w), have)) elif state == "replaced": commands.extend( - self._state_replaced(flatten_dict(w), have) + self._state_replaced(flatten_dict(w), have), ) return commands @@ -232,7 +227,7 @@ def _state_overridden(self, want, have): for h in have: h = flatten_dict(h) obj_in_want = flatten_dict( - search_obj_in_list(h["name"], want, "name") + search_obj_in_list(h["name"], want, "name"), ) if h == obj_in_want: continue @@ -269,7 +264,7 @@ def _state_deleted(self, want, have): if want: for w in want: obj_in_have = flatten_dict( - search_obj_in_list(w["name"], have, "name") + search_obj_in_list(w["name"], have, "name"), ) commands.extend(self.del_attribs(obj_in_have)) else: @@ -317,11 +312,11 @@ def add_commands(self, d, vlan_exists=False): if "allowed_vlans" in d: if vlan_exists: commands.append( - cmd + "trunk allowed vlan add " + str(d["allowed_vlans"]) + cmd + "trunk allowed vlan add " + str(d["allowed_vlans"]), ) else: commands.append( - cmd + "trunk allowed vlan " + str(d["allowed_vlans"]) + cmd + "trunk allowed vlan " + str(d["allowed_vlans"]), ) if "native_vlan" in d: commands.append(cmd + "trunk native vlan " + str(d["native_vlan"])) @@ -352,7 +347,7 @@ def set_commands(self, w, have, replace=False): vlan_tobe_added.pop(vlan_tobe_added.index(w_vlans)) if vlan_tobe_added: diff.update( - {"allowed_vlans": ",".join(vlan_tobe_added)} + {"allowed_vlans": ",".join(vlan_tobe_added)}, ) if have_vlans: commands = self.add_commands(diff, True) diff --git a/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py index 40a5c52e2..edfb607e1 100644 --- a/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/nxos/config/l3_interfaces/l3_interfaces.py @@ -28,9 +28,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( normalize_interface, search_obj_in_list, @@ -67,7 +65,7 @@ def get_l3_interfaces_facts(self, data=None): ) l3_interfaces_facts = facts["ansible_network_resources"].get( - "l3_interfaces" + "l3_interfaces", ) self.platform = facts.get("ansible_net_platform", "") @@ -115,7 +113,7 @@ def execute_module(self): msg="value of running_config parameter must not be empty for state parsed", ) result["parsed"] = self.get_l3_interfaces_facts( - data=running_config + data=running_config, ) if self.state in self.ACTION_STATES: @@ -158,13 +156,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) @@ -198,10 +193,14 @@ def _state_replaced(self, want, have): # Process lists of dicts separately v4_cmds = self._v4_cmds( - want.pop("ipv4", []), have_v4, state="replaced" + want.pop("ipv4", []), + have_v4, + state="replaced", ) v6_cmds = self._v6_cmds( - want.pop("ipv6", []), have_v6, state="replaced" + want.pop("ipv6", []), + have_v6, + state="replaced", ) # Process remaining attrs @@ -209,9 +208,7 @@ def _state_replaced(self, want, have): # Find 'want' changes first diff = self.diff_of_dicts(want, obj_in_have) rmv = {"name": name} - haves_not_in_want = ( - set(obj_in_have.keys()) - set(want.keys()) - set(diff.keys()) - ) + haves_not_in_want = set(obj_in_have.keys()) - set(want.keys()) - set(diff.keys()) for i in haves_not_in_want: rmv[i] = obj_in_have[i] cmds.extend(self.generate_delete_commands(rmv)) @@ -310,9 +307,7 @@ def _v4_cmds(self, want, have, state=None): sec_to_rmv = [] sec_diff = self.diff_list_of_dicts(sec_h, sec_w) for i in sec_diff: - if overridden or [ - w for w in sec_w if w["address"] == i["address"] - ]: + if overridden or [w for w in sec_w if w["address"] == i["address"]]: sec_to_rmv.append(i["address"]) # Check if new primary is currently a secondary @@ -440,7 +435,7 @@ def generate_delete_commands(self, obj): have = self.existing_facts.get(name, {}) if have.get("evpn_multisite_tracking", False) is not False: cmd = "no evpn multisite %s" % have.get( - "evpn_multisite_tracking" + "evpn_multisite_tracking", ) commands.append(cmd) return commands @@ -502,20 +497,22 @@ def add_commands(self, diff, name=""): if "ipv6_redirects" in diff: # Note: device will auto-disable redirects when secondaries are present if diff["ipv6_redirects"] != self.check_existing( - name, "ipv6_redirects" + name, + "ipv6_redirects", ): no_cmd = "no " if diff["ipv6_redirects"] is False else "" commands.append(no_cmd + "ipv6 redirects") self.cmd_order_fixup(commands, name) if "unreachables" in diff: if diff["unreachables"] != self.check_existing( - name, "unreachables" + name, + "unreachables", ): no_cmd = "no " if diff["unreachables"] is False else "" commands.append(no_cmd + "ip unreachables") if "evpn_multisite_tracking" in diff: commands.append( - "evpn multisite " + str(diff["evpn_multisite_tracking"]) + "evpn multisite " + str(diff["evpn_multisite_tracking"]), ) if "ipv4" in diff: commands.extend(self.generate_afi_commands(diff["ipv4"])) @@ -528,11 +525,7 @@ def add_commands(self, diff, name=""): def generate_afi_commands(self, diff): cmds = [] for i in diff: - cmd = ( - "ipv6 address " - if re.search("::", i["address"]) - else "ip address " - ) + cmd = "ipv6 address " if re.search("::", i["address"]) else "ip address " cmd += i["address"] if i.get("secondary"): cmd += " secondary" @@ -550,10 +543,14 @@ def set_commands(self, w, have): else: # lists of dicts must be processed separately from non-list attrs v4_cmds = self._v4_cmds( - w.pop("ipv4", []), obj_in_have.pop("ipv4", []), state="merged" + w.pop("ipv4", []), + obj_in_have.pop("ipv4", []), + state="merged", ) v6_cmds = self._v6_cmds( - w.pop("ipv6", []), obj_in_have.pop("ipv6", []), state="merged" + w.pop("ipv6", []), + obj_in_have.pop("ipv6", []), + state="merged", ) # diff remaining attrs @@ -568,16 +565,10 @@ def set_commands(self, w, have): def cmd_order_fixup(self, cmds, name): """Inserts 'interface ' config at the beginning of populated command list; reorders dependent commands that must process after others.""" if cmds: - if name and not [ - item for item in cmds if item.startswith("interface") - ]: + if name and not [item for item in cmds if item.startswith("interface")]: cmds.insert(0, "interface " + name) - redirects = [ - item - for item in cmds - if re.match("(no )*ip(v6)* redirects", item) - ] + redirects = [item for item in cmds if re.match("(no )*ip(v6)* redirects", item)] if redirects: # redirects should occur after ipv4 commands, just move to end of list redirects = redirects.pop() diff --git a/plugins/module_utils/network/nxos/config/lacp/lacp.py b/plugins/module_utils/network/nxos/config/lacp/lacp.py index 1d1fe7576..f6d8401e5 100644 --- a/plugins/module_utils/network/nxos/config/lacp/lacp.py +++ b/plugins/module_utils/network/nxos/config/lacp/lacp.py @@ -24,9 +24,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts class Lacp(ConfigBase): @@ -135,7 +133,7 @@ def set_state(self, want, have): if state in ("merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) diff --git a/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py b/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py index 6bcb1788a..ee98e7f21 100644 --- a/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py +++ b/plugins/module_utils/network/nxos/config/lacp_interfaces/lacp_interfaces.py @@ -24,9 +24,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, get_interface_type, @@ -61,7 +59,7 @@ def get_lacp_interfaces_facts(self, data=None): data=data, ) lacp_interfaces_facts = facts["ansible_network_resources"].get( - "lacp_interfaces" + "lacp_interfaces", ) if not lacp_interfaces_facts: return [] @@ -106,7 +104,7 @@ def execute_module(self): msg="value of running_config parameter must not be empty for state parsed", ) result["parsed"] = self.get_lacp_interfaces_facts( - data=running_config + data=running_config, ) if self.state in self.ACTION_STATES: @@ -155,13 +153,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) commands = list() @@ -176,7 +171,7 @@ def set_state(self, want, have): commands.extend(self._state_merged(flatten_dict(w), have)) elif state == "replaced": commands.extend( - self._state_replaced(flatten_dict(w), have) + self._state_replaced(flatten_dict(w), have), ) return commands @@ -219,7 +214,7 @@ def _state_overridden(self, want, have): for h in have: h = flatten_dict(h) obj_in_want = flatten_dict( - search_obj_in_list(h["name"], want, "name") + search_obj_in_list(h["name"], want, "name"), ) if h == obj_in_want: continue @@ -256,7 +251,7 @@ def _state_deleted(self, want, have): if want: for w in want: obj_in_have = flatten_dict( - search_obj_in_list(w["name"], have, "name") + search_obj_in_list(w["name"], have, "name"), ) commands.extend(self.del_attribs(obj_in_have)) else: diff --git a/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py b/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py index e5fbacc9a..e2d9de4de 100644 --- a/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py +++ b/plugins/module_utils/network/nxos/config/lag_interfaces/lag_interfaces.py @@ -25,9 +25,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( normalize_interface, ) @@ -57,7 +55,7 @@ def get_lag_interfaces_facts(self, data=None): data=data, ) lag_interfaces_facts = facts["ansible_network_resources"].get( - "lag_interfaces" + "lag_interfaces", ) if not lag_interfaces_facts: return [] @@ -108,7 +106,7 @@ def execute_module(self): msg="value of running_config parameter must not be empty for state parsed", ) result["parsed"] = self.get_lag_interfaces_facts( - data=running_config + data=running_config, ) if self.state in self.ACTION_STATES: @@ -137,7 +135,7 @@ def set_config(self, existing_lag_interfaces_facts): if "members" in w and w["members"]: for item in w["members"]: item.update( - {"member": normalize_interface(item["member"])} + {"member": normalize_interface(item["member"])}, ) have = existing_lag_interfaces_facts resp = self.set_state(want, have) @@ -153,13 +151,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) commands = list() @@ -203,7 +198,8 @@ def _state_overridden(self, want, have): obj_in_want = search_obj_in_list(h["name"], want, "name") if obj_in_want: diff = self.diff_list_of_dicts( - h.get("members", []), obj_in_want["members"] + h.get("members", []), + obj_in_want["members"], ) if not diff: continue @@ -249,9 +245,7 @@ def diff_list_of_dicts(self, want, have): diff = [] for w_item in want: - h_item = ( - search_obj_in_list(w_item["member"], have, key="member") or {} - ) + h_item = search_obj_in_list(w_item["member"], have, key="member") or {} delta = dict_diff(h_item, w_item) if delta: if h_item: @@ -320,7 +314,8 @@ def set_commands(self, w, have): if "members" not in obj_in_have: obj_in_have["members"] = None diff = self.diff_list_of_dicts( - w["members"], obj_in_have["members"] + w["members"], + obj_in_have["members"], ) commands = self.add_commands(diff, w["name"]) return commands @@ -339,7 +334,8 @@ def del_intf_commands(self, w, have): obj_in_have = search_obj_in_list(w["name"], have, "name") if obj_in_have: lst_to_del = self.intersect_list_of_dicts( - w["members"], obj_in_have["members"] + w["members"], + obj_in_have["members"], ) if lst_to_del: for item in lst_to_del: diff --git a/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py b/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py index 455939c62..b49ee3806 100644 --- a/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py +++ b/plugins/module_utils/network/nxos/config/lldp_global/lldp_global.py @@ -23,9 +23,7 @@ remove_empties, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts class Lldp_global(ConfigBase): @@ -52,7 +50,7 @@ def get_lldp_global_facts(self, data=None): data=data, ) lldp_global_facts = facts["ansible_network_resources"].get( - "lldp_global" + "lldp_global", ) if not lldp_global_facts: return {} @@ -135,7 +133,7 @@ def set_state(self, want, have): if state in ("merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) commands = list() @@ -180,7 +178,7 @@ def delete_nested_dict(self, have, want): else: if key in want.keys(): outer_dict.update( - {key: self.delete_nested_dict(val, want[key])} + {key: self.delete_nested_dict(val, want[key])}, ) else: outer_dict.update({key: val}) @@ -199,8 +197,9 @@ def find_delete_params(self, have, want): delete_dict.update( { key: self.delete_nested_dict( - have["tlv_select"], want["tlv_select"] - ) + have["tlv_select"], + want["tlv_select"], + ), }, ) return delete_dict diff --git a/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py b/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py index 2fbfc9fe9..08dfa3117 100644 --- a/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py +++ b/plugins/module_utils/network/nxos/config/lldp_interfaces/lldp_interfaces.py @@ -24,9 +24,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( flatten_dict, get_interface_type, @@ -59,7 +57,7 @@ def get_lldp_interfaces_facts(self, data=None): data=data, ) lldp_interfaces_facts = facts["ansible_network_resources"].get( - "lldp_interfaces" + "lldp_interfaces", ) if not lldp_interfaces_facts: return [] @@ -159,7 +157,7 @@ def set_state(self, want, have): commands.extend(self._state_merged(flatten_dict(w), have)) elif state == "replaced": commands.extend( - self._state_replaced(flatten_dict(w), have) + self._state_replaced(flatten_dict(w), have), ) return commands @@ -194,7 +192,7 @@ def _state_replaced(self, want, have): del_commands = [] delete_dict = {} obj_in_have = flatten_dict( - search_obj_in_list(want["name"], have, "name") + search_obj_in_list(want["name"], have, "name"), ) for k1 in obj_in_have.keys(): if k1 not in want.keys(): @@ -261,7 +259,7 @@ def _state_deleted(self, want, have): if want: for w in want: obj_in_have = flatten_dict( - search_obj_in_list(w["name"], have, "name") + search_obj_in_list(w["name"], have, "name"), ) commands.extend(self.del_commands(obj_in_have)) else: @@ -274,7 +272,7 @@ def _state_deleted(self, want, have): def set_commands(self, want, have): commands = [] obj_in_have = flatten_dict( - search_obj_in_list(want["name"], have, "name") + search_obj_in_list(want["name"], have, "name"), ) if not obj_in_have: commands = self.add_commands(flatten_dict(want)) @@ -302,7 +300,7 @@ def add_commands(self, d): commands.append("no lldp receive") if "management_address" in d: commands.append( - "lldp tlv-set management-address " + d["management_address"] + "lldp tlv-set management-address " + d["management_address"], ) if "vlan" in d: commands.append("lldp tlv-set vlan " + str(d["vlan"])) @@ -320,8 +318,7 @@ def del_commands(self, obj): commands.append("lldp receive") if "management_address" in obj: commands.append( - "no lldp tlv-set management-address " - + obj["management_address"] + "no lldp tlv-set management-address " + obj["management_address"], ) if "vlan" in obj: commands.append("no lldp tlv-set vlan " + str(obj["vlan"])) diff --git a/plugins/module_utils/network/nxos/config/logging_global/logging_global.py b/plugins/module_utils/network/nxos/config/logging_global/logging_global.py index b9a3cf00e..6e493ad36 100644 --- a/plugins/module_utils/network/nxos/config/logging_global/logging_global.py +++ b/plugins/module_utils/network/nxos/config/logging_global/logging_global.py @@ -29,9 +29,7 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.logging_global import ( Logging_globalTemplate, ) diff --git a/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py b/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py index 823f09008..57a1a58d9 100644 --- a/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py +++ b/plugins/module_utils/network/nxos/config/ntp_global/ntp_global.py @@ -28,9 +28,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ntp_global import ( Ntp_globalTemplate, ) @@ -150,9 +148,7 @@ def _ntp_list_to_dict(self, data): if "access_group" in tmp: for x in ["peer", "query_only", "serve", "serve_only"]: if x in tmp["access_group"]: - tmp["access_group"][x] = { - i["access_list"]: i for i in tmp["access_group"][x] - } + tmp["access_group"][x] = {i["access_list"]: i for i in tmp["access_group"][x]} pkey = { "authentication_keys": "id", "peers": "peer", diff --git a/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py b/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py index ca201d7e5..e640bc9de 100644 --- a/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/config/ospf_interfaces/ospf_interfaces.py @@ -26,9 +26,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ospf_interfaces import ( Ospf_interfacesTemplate, ) @@ -92,9 +90,7 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} wantd = {} # remove superfluous config for overridden and deleted @@ -116,7 +112,8 @@ def _compare(self, want, have): self._compare_ospf_interfaces(want, have) if len(self.commands) != begin: self.commands.insert( - begin, self._tmplt.render(want or have, "interface", False) + begin, + self._tmplt.render(want or have, "interface", False), ) def _compare_ospf_interfaces(self, want, have): @@ -136,14 +133,11 @@ def _compare_ospf_interfaces(self, want, have): # this ensures that the "no" form of "ip ospf passive-interface" # command is executed even when there is no existing config - if ( - witem.get("passive_interface") is False - and "passive_interface" not in hitem - ): + if witem.get("passive_interface") is False and "passive_interface" not in hitem: hitem["passive_interface"] = True if "passive_interface" in hitem and witem.get( - "default_passive_interface" + "default_passive_interface", ): self.commands.append(self._generate_passive_intf(witem)) @@ -153,18 +147,24 @@ def _compare_ospf_interfaces(self, want, have): for area in witem.get("multi_areas", []): if area not in hitem.get("multi_areas", []): self.addcmd( - {"afi": afi, "area": area}, "multi_areas", negate=False + {"afi": afi, "area": area}, + "multi_areas", + negate=False, ) # remove superfluous top-level `multi_areas` config for area in hitem.get("multi_areas", []): if area not in witem.get("multi_areas", []): self.addcmd( - {"afi": afi, "area": area}, "multi_areas", negate=True + {"afi": afi, "area": area}, + "multi_areas", + negate=True, ) # compare config->address_family->processes self._compare_processes( - afi, witem.get("processes", {}), hitem.get("processes", {}) + afi, + witem.get("processes", {}), + hitem.get("processes", {}), ) def _compare_processes(self, afi, want, have): @@ -183,14 +183,18 @@ def _compare_processes(self, afi, want, have): if area not in hproc.get("multi_areas", []): marea_dict["area"] = area self.addcmd( - marea_dict, "processes_multi_areas", negate=False + marea_dict, + "processes_multi_areas", + negate=False, ) # remove superfluous processes->multi_areas config for area in hproc.get("multi_areas", []): if area not in wproc.get("multi_areas", []): marea_dict["area"] = area self.addcmd( - marea_dict, "processes_multi_areas", negate=True + marea_dict, + "processes_multi_areas", + negate=True, ) # remove superflous config->address_family->processes @@ -210,12 +214,10 @@ def _list_to_dict(self, entry): for item in entry.values(): for ag in item.get("address_family", []): ag["processes"] = { - subentry["process_id"]: subentry - for subentry in ag.get("processes", []) + subentry["process_id"]: subentry for subentry in ag.get("processes", []) } item["address_family"] = { - subentry["afi"]: subentry - for subentry in item.get("address_family", []) + subentry["afi"]: subentry for subentry in item.get("address_family", []) } def _generate_passive_intf(self, data): diff --git a/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py b/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py index 03ea3e3f3..8a6f42e7a 100644 --- a/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py +++ b/plugins/module_utils/network/nxos/config/ospfv2/ospfv2.py @@ -25,9 +25,7 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ospfv2 import ( Ospfv2Template, ) @@ -93,14 +91,8 @@ def gen_config(self): :returns: the commands necessary to migrate the current configuration to the desired configuration """ - wantd = { - (entry["process_id"]): entry - for entry in self.want.get("processes", []) - } - haved = { - (entry["process_id"]): entry - for entry in self.have.get("processes", []) - } + wantd = {(entry["process_id"]): entry for entry in self.want.get("processes", [])} + haved = {(entry["process_id"]): entry for entry in self.have.get("processes", [])} # turn all lists of dicts into dicts prior to merge for entry in wantd, haved: @@ -112,9 +104,7 @@ def gen_config(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} wantd = {} # if state is overridden, first remove processes that are in have but not in want @@ -138,9 +128,7 @@ def _compare(self, want, have): begin, self._tmplt.render( want or have, - "vrf" - if "vrf" in (want.keys() or have.keys()) - else "process_id", + "vrf" if "vrf" in (want.keys() or have.keys()) else "process_id", False, ), ) @@ -205,34 +193,24 @@ def _vrfs_compare(self, want, have): def _ospf_list_to_dict(self, entry): for _pid, proc in iteritems(entry): for area in proc.get("areas", []): - area["ranges"] = { - entry["prefix"]: entry for entry in area.get("ranges", []) - } + area["ranges"] = {entry["prefix"]: entry for entry in area.get("ranges", [])} area["filter_list"] = { - entry["direction"]: entry - for entry in area.get("filter_list", []) + entry["direction"]: entry for entry in area.get("filter_list", []) } mpls_areas = { entry["area_id"]: entry - for entry in proc.get("mpls", {}) - .get("traffic_eng", {}) - .get("areas", []) + for entry in proc.get("mpls", {}).get("traffic_eng", {}).get("areas", []) } if mpls_areas: proc["mpls"]["traffic_eng"]["areas"] = mpls_areas - proc["areas"] = { - entry["area_id"]: entry for entry in proc.get("areas", []) - } + proc["areas"] = {entry["area_id"]: entry for entry in proc.get("areas", [])} proc["summary_address"] = { - entry["prefix"]: entry - for entry in proc.get("summary_address", []) + entry["prefix"]: entry for entry in proc.get("summary_address", []) } proc["redistribute"] = { (entry.get("id"), entry["protocol"]): entry for entry in proc.get("redistribute", []) } if "vrfs" in proc: - proc["vrfs"] = { - entry["vrf"]: entry for entry in proc.get("vrfs", []) - } + proc["vrfs"] = {entry["vrf"]: entry for entry in proc.get("vrfs", [])} self._ospf_list_to_dict(proc["vrfs"]) diff --git a/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py b/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py index 0d08d85d7..e60fc31a2 100644 --- a/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py +++ b/plugins/module_utils/network/nxos/config/ospfv3/ospfv3.py @@ -27,9 +27,7 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.ospfv3 import ( Ospfv3Template, ) @@ -83,14 +81,8 @@ def generate_commands(self): """Generate configuration commands to send based on want, have and desired state. """ - wantd = { - (entry["process_id"]): entry - for entry in self.want.get("processes", []) - } - haved = { - (entry["process_id"]): entry - for entry in self.have.get("processes", []) - } + wantd = {(entry["process_id"]): entry for entry in self.want.get("processes", [])} + haved = {(entry["process_id"]): entry for entry in self.have.get("processes", [])} # turn all lists of dicts into dicts prior to merge for entry in wantd, haved: @@ -102,9 +94,7 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} wantd = {} # if state is overridden, first remove processes that are in have but not in want @@ -133,9 +123,7 @@ def _compare(self, want, have): begin, self._tmplt.render( want or have, - "vrf" - if "vrf" in (want.keys() or have.keys()) - else "process_id", + "vrf" if "vrf" in (want.keys() or have.keys()) else "process_id", False, ), ) @@ -221,33 +209,22 @@ def _af_compare_lists(self, want, have): def _ospfv3_list_to_dict(self, entry): for _pid, proc in iteritems(entry): - proc["areas"] = { - entry["area_id"]: entry for entry in proc.get("areas", []) - } + proc["areas"] = {entry["area_id"]: entry for entry in proc.get("areas", [])} af = proc.get("address_family") if af: for area in af.get("areas", []): - area["ranges"] = { - entry["prefix"]: entry - for entry in area.get("ranges", []) - } + area["ranges"] = {entry["prefix"]: entry for entry in area.get("ranges", [])} area["filter_list"] = { - entry["direction"]: entry - for entry in area.get("filter_list", []) + entry["direction"]: entry for entry in area.get("filter_list", []) } - af["areas"] = { - entry["area_id"]: entry for entry in af.get("areas", []) - } + af["areas"] = {entry["area_id"]: entry for entry in af.get("areas", [])} af["summary_address"] = { - entry["prefix"]: entry - for entry in af.get("summary_address", []) + entry["prefix"]: entry for entry in af.get("summary_address", []) } af["redistribute"] = { (entry.get("id"), entry["protocol"]): entry for entry in af.get("redistribute", []) } if "vrfs" in proc: - proc["vrfs"] = { - entry["vrf"]: entry for entry in proc.get("vrfs", []) - } + proc["vrfs"] = {entry["vrf"]: entry for entry in proc.get("vrfs", [])} self._ospfv3_list_to_dict(proc["vrfs"]) diff --git a/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py b/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py index a7c7abf60..d29338488 100644 --- a/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py +++ b/plugins/module_utils/network/nxos/config/prefix_lists/prefix_lists.py @@ -26,9 +26,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.prefix_lists import ( Prefix_listsTemplate, ) @@ -76,18 +74,14 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} for key, hvalue in iteritems(haved): wvalue = wantd.pop(key, {}) if wvalue: wplists = wvalue.get("prefix_lists", {}) hplists = hvalue.get("prefix_lists", {}) hvalue["prefix_lists"] = { - k: v - for k, v in iteritems(hplists) - if k in wplists or not wplists + k: v for k, v in iteritems(hplists) if k in wplists or not wplists } # remove superfluous config for overridden and deleted @@ -112,7 +106,8 @@ def _compare(self, want, have): self.compare(["description"], want=wentry, have=hentry) # compare sequences self._compare_seqs( - wentry.pop("entries", {}), hentry.pop("entries", {}) + wentry.pop("entries", {}), + hentry.pop("entries", {}), ) if self.state in ["overridden", "deleted"]: @@ -120,7 +115,8 @@ def _compare(self, want, have): for h in hplists.values(): self.commands.append( "no {0} prefix-list {1}".format( - h["afi"].replace("ipv4", "ip"), h["name"] + h["afi"].replace("ipv4", "ip"), + h["name"], ), ) @@ -152,9 +148,5 @@ def _prefix_list_transform(self, entry): if "entries" in plist: for seq in plist["entries"]: seq.update({"afi": afi, "name": plist["name"]}) - plist["entries"] = { - x["sequence"]: x for x in plist["entries"] - } - value["prefix_lists"] = { - entry["name"]: entry for entry in value["prefix_lists"] - } + plist["entries"] = {x["sequence"]: x for x in plist["entries"]} + value["prefix_lists"] = {entry["name"]: entry for entry in value["prefix_lists"]} diff --git a/plugins/module_utils/network/nxos/config/route_maps/route_maps.py b/plugins/module_utils/network/nxos/config/route_maps/route_maps.py index 8de4ab2f1..2f618152b 100644 --- a/plugins/module_utils/network/nxos/config/route_maps/route_maps.py +++ b/plugins/module_utils/network/nxos/config/route_maps/route_maps.py @@ -27,9 +27,7 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.route_maps import ( Route_mapsTemplate, ) @@ -132,9 +130,7 @@ def generate_commands(self): # if state is deleted, empty out wantd and set haved to wantd if self.state == "deleted": - haved = { - k: v for k, v in iteritems(haved) if k in wantd or not wantd - } + haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd} wantd = {} # remove superfluous config for overridden and deleted @@ -143,7 +139,7 @@ def generate_commands(self): if k not in wantd: for _hk, hentry in iteritems(have.get("entries", {})): self.commands.append( - self._tmplt.render(hentry, "route_map", True) + self._tmplt.render(hentry, "route_map", True), ) for wk, want in iteritems(wantd): @@ -176,36 +172,35 @@ def _compare_entries(self, want, have): self.commands.insert(pos, self.commands.pop(i)) pos += 1 self.commands.insert( - begin, self._tmplt.render(wentry, "route_map", False) + begin, + self._tmplt.render(wentry, "route_map", False), ) # remove superfluos entries from have for _hk, hentry in iteritems(have): self.commands.append(self._tmplt.render(hentry, "route_map", True)) def _compare_extcomm(self, want, have): - hentry = ( - get_from_dict(data_dict=have, keypath="set.extcommunity.rt") or {} - ) - wentry = ( - get_from_dict(data_dict=want, keypath="set.extcommunity.rt") or {} - ) + hentry = get_from_dict(data_dict=have, keypath="set.extcommunity.rt") or {} + wentry = get_from_dict(data_dict=want, keypath="set.extcommunity.rt") or {} h_nums = set(hentry.get("extcommunity_numbers", [])) w_nums = set(wentry.get("extcommunity_numbers", [])) if h_nums != w_nums or wentry.get("additive") != hentry.get( - "additive" + "additive", ): if self.state not in ["merged", "rendered"]: # need to explicitly remove existing entry to correctly apply new one self.commands.append( self._tmplt.render( - hentry, "set.extcommunity.rt", negate=True - ) + hentry, + "set.extcommunity.rt", + negate=True, + ), ) # default CLI behaviour is to 'merge' with existing entry self.commands.append( - self._tmplt.render(wentry, "set.extcommunity.rt", negate=False) + self._tmplt.render(wentry, "set.extcommunity.rt", negate=False), ) def _compare_lists(self, want, have): @@ -222,46 +217,30 @@ def _compare_lists(self, want, have): h_set[hx[i]["address"]] = hx[i] sum_set = list(set(list(w_set) + list(h_set))) for each in sum_set: - if ( - each in w_set - and each in h_set - and w_set[each] == h_set[each] - ): + if each in w_set and each in h_set and w_set[each] == h_set[each]: for i in range( 0, len( - want["set"]["ip"]["next_hop"][ - "verify_availability" - ] + want["set"]["ip"]["next_hop"]["verify_availability"], ), ): if ( - want["set"]["ip"]["next_hop"][ - "verify_availability" - ][i]["address"] + want["set"]["ip"]["next_hop"]["verify_availability"][i]["address"] == each ): - want["set"]["ip"]["next_hop"][ - "verify_availability" - ].pop(i) + want["set"]["ip"]["next_hop"]["verify_availability"].pop(i) break for i in range( 0, len( - have["set"]["ip"]["next_hop"][ - "verify_availability" - ] + have["set"]["ip"]["next_hop"]["verify_availability"], ), ): if ( - have["set"]["ip"]["next_hop"][ - "verify_availability" - ][i]["address"] + have["set"]["ip"]["next_hop"]["verify_availability"][i]["address"] == each ): - have["set"]["ip"]["next_hop"][ - "verify_availability" - ].pop(i) + have["set"]["ip"]["next_hop"]["verify_availability"].pop(i) break w_set.pop(each) h_set.pop(each) diff --git a/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py b/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py index 27e767973..472e7285f 100644 --- a/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py +++ b/plugins/module_utils/network/nxos/config/snmp_server/snmp_server.py @@ -29,9 +29,7 @@ get_from_dict, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.snmp_server import ( Snmp_serverTemplate, ) @@ -232,14 +230,10 @@ def _build_key(x): tmp = deepcopy(data) if "communities" in tmp: - tmp["communities"] = { - _build_key(entry): entry for entry in tmp["communities"] - } + tmp["communities"] = {_build_key(entry): entry for entry in tmp["communities"]} if "users" in tmp: if "auth" in tmp["users"]: - tmp["users"]["auth"] = { - _build_key(entry): entry for entry in tmp["users"]["auth"] - } + tmp["users"]["auth"] = {_build_key(entry): entry for entry in tmp["users"]["auth"]} if "use_acls" in tmp["users"]: tmp["users"]["use_acls"] = { entry["user"]: entry for entry in tmp["users"]["use_acls"] diff --git a/plugins/module_utils/network/nxos/config/static_routes/static_routes.py b/plugins/module_utils/network/nxos/config/static_routes/static_routes.py index 539401115..73d1e84b7 100644 --- a/plugins/module_utils/network/nxos/config/static_routes/static_routes.py +++ b/plugins/module_utils/network/nxos/config/static_routes/static_routes.py @@ -26,9 +26,7 @@ dict_merge, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.rm_templates.static_routes import ( Static_routesTemplate, ) @@ -95,15 +93,19 @@ def generate_commands(self): for k, want in wantd.items(): self._compare_top_level_keys( - want=want, have=haved.pop(k, {}), vrf_name=k + want=want, + have=haved.pop(k, {}), + vrf_name=k, ) if (self.state == "deleted" and not wantd) or self.state in [ - "overridden" + "overridden", ]: for k, have in haved.items(): self._compare_top_level_keys( - want={}, have=have, vrf_name=k + want={}, + have=have, + vrf_name=k, ) def _compare_top_level_keys(self, want, have, vrf_name): @@ -126,7 +128,9 @@ def _compare_top_level_keys(self, want, have, vrf_name): if self.state != "deleted": for _afi, routes in want.items(): self._compare( - s_want=routes, s_have=have.pop(_afi, {}), afi=_afi + s_want=routes, + s_have=have.pop(_afi, {}), + afi=_afi, ) if self.state in ["overridden", "deleted"]: @@ -187,7 +191,8 @@ def list_to_dict(self, param, operation): for nxh in rts.get("next_hops", []): _forw_rtr_add = nxh.get( - "forward_router_address", "" + "forward_router_address", + "", ).upper() _intf = nxh.get("interface", "") _key = _dest + "_" + _forw_rtr_add + _intf @@ -202,9 +207,7 @@ def list_to_dict(self, param, operation): if _intf: dummy_sr["interface"] = _intf if _forw_rtr_add: - dummy_sr[ - "forward_router_address" - ] = _forw_rtr_add + dummy_sr["forward_router_address"] = _forw_rtr_add dummy_sr.update(nxh) _routes[_key] = dummy_sr diff --git a/plugins/module_utils/network/nxos/config/telemetry/telemetry.py b/plugins/module_utils/network/nxos/config/telemetry/telemetry.py index f561215fd..3b79bb6e3 100644 --- a/plugins/module_utils/network/nxos/config/telemetry/telemetry.py +++ b/plugins/module_utils/network/nxos/config/telemetry/telemetry.py @@ -18,9 +18,7 @@ from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import ( ConfigBase, ) -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( - to_list, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.cmdref.telemetry.telemetry import ( TMS_DESTGROUP, @@ -28,12 +26,8 @@ TMS_SENSORGROUP, TMS_SUBSCRIPTION, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( - NxosCmdRef, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import NxosCmdRef from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.telemetry.telemetry import ( get_module_params_subsection, get_setval_path, @@ -90,13 +84,13 @@ def execute_module(self): state = self._module.params["state"] if "overridden" in state: self._module.fail_json( - msg="State is invalid for this module." + msg="State is invalid for this module.", ) # When state is 'deleted', the module_params should not contain data # under the 'config' key if "deleted" in state and self._module.params.get("config"): self._module.fail_json( - msg="Remove config key from playbook when state is " + msg="Remove config key from playbook when state is ", ) if self._module.params["config"] is None: @@ -104,9 +98,7 @@ def execute_module(self): # Normalize interface name. int = self._module.params["config"].get("source_interface") if int: - self._module.params["config"][ - "source_interface" - ] = normalize_interface(int) + self._module.params["config"]["source_interface"] = normalize_interface(int) if self.state in self.ACTION_STATES: existing_telemetry_facts = self.get_telemetry_facts() @@ -182,10 +174,11 @@ def set_state(self, want, have): # Build Telemetry Global NxosCmdRef Object cmd_ref["TMS_GLOBAL"]["ref"] = [] self._module.params["config"] = get_module_params_subsection( - ALL_MP, "TMS_GLOBAL" + ALL_MP, + "TMS_GLOBAL", ) cmd_ref["TMS_GLOBAL"]["ref"].append( - NxosCmdRef(self._module, TMS_GLOBAL) + NxosCmdRef(self._module, TMS_GLOBAL), ) ref = cmd_ref["TMS_GLOBAL"]["ref"][0] ref.set_context() @@ -204,26 +197,24 @@ def build_cmdref_objects(td): saved_ids.append(playvals["id"]) resource_key = td["cmd"].format(playvals["id"]) # Only build the NxosCmdRef object for the td['name'] module parameters. - self._module.params[ - "config" - ] = get_module_params_subsection( + self._module.params["config"] = get_module_params_subsection( ALL_MP, td["type"], playvals["id"], ) cmd_ref[td["type"]]["ref"].append( - NxosCmdRef(self._module, td["obj"]) + NxosCmdRef(self._module, td["obj"]), ) ref = cmd_ref[td["type"]]["ref"][-1] ref.set_context([resource_key]) if td["type"] == "TMS_SENSORGROUP" and get_setval_path( - self._module + self._module, ): # Sensor group path setting can contain optional values. # Call get_setval_path helper function to process any # optional setval keys. ref._ref["path"]["setval"] = get_setval_path( - self._module + self._module, ) ref.get_existing(device_cache) ref.get_playvals() @@ -279,7 +270,9 @@ def _state_replaced(want, have): ref["tms_destgroup"] = NxosCmdRef([], TMS_DESTGROUP, ref_only=True) ref["tms_sensorgroup"] = NxosCmdRef([], TMS_SENSORGROUP, ref_only=True) ref["tms_subscription"] = NxosCmdRef( - [], TMS_SUBSCRIPTION, ref_only=True + [], + TMS_SUBSCRIPTION, + ref_only=True, ) # Order matters for state replaced. @@ -379,28 +372,20 @@ def _state_replaced(want, have): have_resources = massaged_have.get("destination_groups") if resource == "TMS_SENSORGROUP": name = "sensor-group" - global_ctx = ref["tms_sensorgroup"]._ref["_template"][ - "context" - ] + global_ctx = ref["tms_sensorgroup"]._ref["_template"]["context"] setval = {} - setval["data_source"] = ref["tms_sensorgroup"]._ref[ - "data_source" - ]["setval"] + setval["data_source"] = ref["tms_sensorgroup"]._ref["data_source"]["setval"] setval["path"] = ref["tms_sensorgroup"]._ref["path"]["setval"] want_resources = massaged_want.get("sensor_groups") have_resources = massaged_have.get("sensor_groups") if resource == "TMS_SUBSCRIPTION": name = "subscription" - global_ctx = ref["tms_subscription"]._ref["_template"][ - "context" - ] + global_ctx = ref["tms_subscription"]._ref["_template"]["context"] setval = {} - setval["destination_group"] = ref["tms_subscription"]._ref[ - "destination_group" - ]["setval"] - setval["sensor_group"] = ref["tms_subscription"]._ref[ - "sensor_group" - ]["setval"] + setval["destination_group"] = ref["tms_subscription"]._ref["destination_group"][ + "setval" + ] + setval["sensor_group"] = ref["tms_subscription"]._ref["sensor_group"]["setval"] want_resources = massaged_want.get("subscriptions") have_resources = massaged_have.get("subscriptions") @@ -430,15 +415,15 @@ def _state_replaced(want, have): if item.get("data_source"): cmd["data_source"] = [ setval["data_source"].format( - item["data_source"] + item["data_source"], ), ] if item.get("path"): setval["path"] = get_setval_path( - item.get("path") + item.get("path"), ) cmd["path"] = [ - setval["path"].format(**item["path"]) + setval["path"].format(**item["path"]), ] add[resource].extend(global_ctx) if property_ctx[0] not in add[resource]: @@ -458,7 +443,7 @@ def _state_replaced(want, have): if item.get("sensor_group"): cmd["sensor_group"] = [ setval["sensor_group"].format( - **item["sensor_group"] + **item["sensor_group"], ), ] add[resource].extend(global_ctx) @@ -466,7 +451,7 @@ def _state_replaced(want, have): add[resource].extend(property_ctx) if cmd.get("destination_group"): add[resource].extend( - cmd["destination_group"] + cmd["destination_group"], ) if cmd.get("sensor_group"): add[resource].extend(cmd["sensor_group"]) @@ -481,7 +466,7 @@ def _state_replaced(want, have): continue # item wanted but does not exist so add it property_ctx = [ - "{0} {1}".format(name, want_key) + "{0} {1}".format(name, want_key), ] if resource == "TMS_DESTGROUP": cmd = [setval.format(**item[cmd_property])] @@ -494,24 +479,24 @@ def _state_replaced(want, have): if item.get("data_source"): cmd["data_source"] = [ setval["data_source"].format( - item["data_source"] + item["data_source"], ), ] if item.get("path"): setval["path"] = get_setval_path( - item.get("path") + item.get("path"), ) cmd["path"] = [ setval["path"].format( - **item["path"] - ) + **item["path"], + ), ] add[resource].extend(global_ctx) if property_ctx[0] not in add[resource]: add[resource].extend(property_ctx) if cmd.get("data_source"): add[resource].extend( - cmd["data_source"] + cmd["data_source"], ) if cmd.get("path"): add[resource].extend(cmd["path"]) @@ -526,7 +511,7 @@ def _state_replaced(want, have): if item.get("sensor_group"): cmd["sensor_group"] = [ setval["sensor_group"].format( - **item["sensor_group"] + **item["sensor_group"], ), ] add[resource].extend(global_ctx) @@ -534,11 +519,11 @@ def _state_replaced(want, have): add[resource].extend(property_ctx) if cmd.get("destination_group"): add[resource].extend( - cmd["destination_group"] + cmd["destination_group"], ) if cmd.get("sensor_group"): add[resource].extend( - cmd["sensor_group"] + cmd["sensor_group"], ) # process haves: @@ -558,12 +543,11 @@ def _state_replaced(want, have): continue # have item not wanted so remove it property_ctx = [ - "{0} {1}".format(name, have_key) + "{0} {1}".format(name, have_key), ] if resource == "TMS_DESTGROUP": cmd = [ - "no " - + setval.format(**item[cmd_property]) + "no " + setval.format(**item[cmd_property]), ] delete[resource].extend(global_ctx) if property_ctx[0] not in delete[resource]: @@ -575,17 +559,17 @@ def _state_replaced(want, have): cmd["data_source"] = [ "no " + setval["data_source"].format( - item["data_source"] + item["data_source"], ), ] if item.get("path"): setval["path"] = get_setval_path( - item.get("path") + item.get("path"), ) cmd["path"] = [ "no " + setval["path"].format( - **item["path"] + **item["path"], ), ] delete[resource].extend(global_ctx) @@ -593,7 +577,7 @@ def _state_replaced(want, have): delete[resource].extend(property_ctx) if cmd.get("data_source"): delete[resource].extend( - cmd["data_source"] + cmd["data_source"], ) if cmd.get("path"): delete[resource].extend(cmd["path"]) @@ -602,9 +586,7 @@ def _state_replaced(want, have): if item.get("destination_group"): cmd["destination_group"] = [ "no " - + setval[ - "destination_group" - ].format( + + setval["destination_group"].format( item["destination_group"], ), ] @@ -612,7 +594,7 @@ def _state_replaced(want, have): cmd["sensor_group"] = [ "no " + setval["sensor_group"].format( - **item["sensor_group"] + **item["sensor_group"], ), ] delete[resource].extend(global_ctx) @@ -620,11 +602,11 @@ def _state_replaced(want, have): delete[resource].extend(property_ctx) if cmd.get("destination_group"): delete[resource].extend( - cmd["destination_group"] + cmd["destination_group"], ) if cmd.get("sensor_group"): delete[resource].extend( - cmd["sensor_group"] + cmd["sensor_group"], ) add[resource] = remove_duplicate_context(add[resource]) diff --git a/plugins/module_utils/network/nxos/config/vlans/vlans.py b/plugins/module_utils/network/nxos/config/vlans/vlans.py index 5f5775ddf..845a8c9fa 100644 --- a/plugins/module_utils/network/nxos/config/vlans/vlans.py +++ b/plugins/module_utils/network/nxos/config/vlans/vlans.py @@ -27,9 +27,7 @@ to_list, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( search_obj_in_list, ) @@ -152,13 +150,10 @@ def set_state(self, want, have): to the desired configuration """ state = self._module.params["state"] - if ( - state in ("overridden", "merged", "replaced", "rendered") - and not want - ): + if state in ("overridden", "merged", "replaced", "rendered") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( - state + state, ), ) diff --git a/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py b/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py index 18df7c068..ca0890f9f 100644 --- a/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/acl_interfaces/acl_interfaces.py @@ -19,9 +19,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acl_interfaces.acl_interfaces import ( Acl_interfacesArgs, @@ -65,7 +63,8 @@ def populate_facts(self, connection, ansible_facts, data=None): intf = data[i].split("\n") for l in range(1, len(intf)): if not re.search( - "ip(v6)?( port)? (access-group|traffic-filter)", intf[l] + "ip(v6)?( port)? (access-group|traffic-filter)", + intf[l], ): intf[l] = "" intf = list(filter(None, intf)) @@ -82,7 +81,8 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) params = utils.remove_empties(params) facts["acl_interfaces"] = params["config"] diff --git a/plugins/module_utils/network/nxos/facts/acls/acls.py b/plugins/module_utils/network/nxos/facts/acls/acls.py index ad1efbe0a..5b4351740 100644 --- a/plugins/module_utils/network/nxos/facts/acls/acls.py +++ b/plugins/module_utils/network/nxos/facts/acls/acls.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acls.acls import ( AclsArgs, @@ -49,7 +47,7 @@ def __init__(self, module, subspec="config", options="options"): def get_device_data(self, connection): data = connection.get( - "show running-config | section '^ip(v6)* access-list'" + "show running-config | section '^ip(v6)* access-list'", ) if data == "{}": return "" @@ -90,7 +88,8 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) params = utils.remove_empties(params) facts["acls"] = params["config"] @@ -129,13 +128,14 @@ def get_endpoint(self, ace, pro): port_pro = re.search(r"(eq|lt|gt|neq) (\S+)", ace) if port_pro: port_protocol.update( - {port_pro.group(1): port_pro.group(2)} + {port_pro.group(1): port_pro.group(2)}, ) ace = re.sub(port_pro.group(1), "", ace, 1) ace = re.sub(port_pro.group(2), "", ace, 1) else: limit = re.search( - r"range\s(?P\S+)\s(?P\S+)", ace + r"range\s(?P\S+)\s(?P\S+)", + ace, ) if limit: rstart = limit.groupdict()["rstart"] @@ -264,7 +264,8 @@ def render_config(self, spec, conf): acl = [a.strip() for a in acl] acl = list(filter(None, acl)) acls["name"] = re.match( - r"(ip)?(v6)?\s?access-list (.*)", acl[0] + r"(ip)?(v6)?\s?access-list (.*)", + acl[0], ).group( 3, ) @@ -330,14 +331,10 @@ def render_config(self, spec, conf): option = re.sub("_", "-", option) if option in ace: if option == "echo" and ( - "echo_request" in options - or "echo_reply" in options + "echo_request" in options or "echo_reply" in options ): continue - elif ( - option == "unreachable" - and "port_unreachable" in options - ): + elif option == "unreachable" and "port_unreachable" in options: continue option = re.sub("-", "_", option) options.update({option: True}) diff --git a/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py b/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py index cbdb8dab2..4434db735 100644 --- a/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/bfd_interfaces/bfd_interfaces.py @@ -16,9 +16,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bfd_interfaces.bfd_interfaces import ( Bfd_interfacesArgs, @@ -57,7 +55,7 @@ def populate_facts(self, connection, ansible_facts, data=None): if not data: data = connection.get( - "show running-config | section '^interface|^feature bfd'" + "show running-config | section '^interface|^feature bfd'", ) # Some of the bfd attributes @@ -77,7 +75,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["bfd_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["bfd_interfaces"].append(utils.remove_empties(cfg)) @@ -104,13 +103,7 @@ def render_config(self, spec, conf): config["name"] = intf # 'bfd'/'bfd echo' do not nvgen when enabled thus set to 'enable' when None. # 'bfd' is not supported on some platforms - config["bfd"] = ( - utils.parse_conf_cmd_arg(conf, "bfd", "enable", "disable") - or "enable" - ) - config["echo"] = ( - utils.parse_conf_cmd_arg(conf, "bfd echo", "enable", "disable") - or "enable" - ) + config["bfd"] = utils.parse_conf_cmd_arg(conf, "bfd", "enable", "disable") or "enable" + config["echo"] = utils.parse_conf_cmd_arg(conf, "bfd echo", "enable", "disable") or "enable" return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py b/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py index 9efdd88dc..066be41ee 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/facts/bgp_address_family/bgp_address_family.py @@ -16,9 +16,7 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_address_family.bgp_address_family import ( Bgp_address_familyArgs, @@ -61,7 +59,7 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Bgp_address_family template bgp_address_family_parser = Bgp_address_familyTemplate( - lines=data.splitlines() + lines=data.splitlines(), ) objs = bgp_address_family_parser.parse() if objs: @@ -84,7 +82,8 @@ def populate_facts(self, connection, ansible_facts, data=None): ) if "networks" in x: x["networks"] = sorted( - x["networks"], key=lambda k, s="prefix": k[s] + x["networks"], + key=lambda k, s="prefix": k[s], ) if "redistribute" in x: x["redistribute"] = sorted( @@ -101,11 +100,12 @@ def populate_facts(self, connection, ansible_facts, data=None): ) ansible_facts["ansible_network_resources"].pop( - "bgp_address_family", None + "bgp_address_family", + None, ) params = utils.remove_empties( - utils.validate_config(self.argument_spec, {"config": objs}) + utils.validate_config(self.argument_spec, {"config": objs}), ) facts["bgp_address_family"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py b/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py index cef7b52b4..3ef980512 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/nxos/facts/bgp_global/bgp_global.py @@ -16,9 +16,7 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_global.bgp_global import ( Bgp_globalArgs, @@ -60,7 +58,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Bgp_global template bgp_global_parser = Bgp_globalTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) obj = bgp_global_parser.parse() @@ -76,7 +75,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # transform vrfs into a list if vrfs: obj["vrfs"] = sorted( - list(obj["vrfs"].values()), key=lambda k, sk="vrf": k[sk] + list(obj["vrfs"].values()), + key=lambda k, sk="vrf": k[sk], ) for vrf in obj["vrfs"]: self._post_parse(vrf) @@ -88,7 +88,9 @@ def populate_facts(self, connection, ansible_facts, data=None): ansible_facts["ansible_network_resources"].pop("bgp_global", None) params = utils.remove_empties( bgp_global_parser.validate_config( - self.argument_spec, {"config": obj}, redact=True + self.argument_spec, + {"config": obj}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py index 5b0eed8b3..62a8575c2 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/facts/bgp_neighbor_address_family/bgp_neighbor_address_family.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_neighbor_address_family.bgp_neighbor_address_family import ( Bgp_neighbor_address_familyArgs, @@ -59,15 +57,14 @@ def populate_facts(self, connection, ansible_facts, data=None): data = self._flatten_config(data) # parse native config using the Bgp_neighbor_address_family template - bgp_neighbor_address_family_parser = ( - Bgp_neighbor_address_familyTemplate(lines=data) - ) + bgp_neighbor_address_family_parser = Bgp_neighbor_address_familyTemplate(lines=data) objs = bgp_neighbor_address_family_parser.parse() if objs: top_lvl_nbrs = objs.get("vrfs", {}).pop("vrf_", {}) objs["neighbors"] = self._post_parse(top_lvl_nbrs).get( - "neighbors", [] + "neighbors", + [], ) if "vrfs" in objs: @@ -76,11 +73,12 @@ def populate_facts(self, connection, ansible_facts, data=None): objs["vrfs"] = list(objs["vrfs"].values()) ansible_facts["ansible_network_resources"].pop( - "bgp_neighbor_address_family", None + "bgp_neighbor_address_family", + None, ) params = utils.remove_empties( - utils.validate_config(self.argument_spec, {"config": objs}) + utils.validate_config(self.argument_spec, {"config": objs}), ) facts["bgp_neighbor_address_family"] = params.get("config", {}) diff --git a/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py b/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py index 8f24cfc45..080228937 100644 --- a/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/facts/bgp_templates/bgp_templates.py @@ -16,9 +16,7 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.bgp_templates.bgp_templates import ( Bgp_templatesArgs, @@ -40,10 +38,10 @@ def get_config(self, connection): This method exists solely to allow the unit test framework to mock device connection calls. """ as_number = connection.get( - "show running-config bgp | include 'router bgp'" + "show running-config bgp | include 'router bgp'", ) templates = connection.get( - "show running-config bgp | section 'template'" + "show running-config bgp | section 'template'", ) return as_number + "\n" + templates @@ -67,7 +65,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Bgp_templates template bgp_templates_parser = Bgp_templatesTemplate( - lines=data, module=self._module + lines=data, + module=self._module, ) parsed = bgp_templates_parser.parse() @@ -81,7 +80,7 @@ def populate_facts(self, connection, ansible_facts, data=None): for x in objs[k]: if "address_family" in x: x["address_family"] = list( - x["address_family"].values() + x["address_family"].values(), ) for nbr in objs.get("neighbor", []): @@ -99,7 +98,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( bgp_templates_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/facts.py b/plugins/module_utils/network/nxos/facts/facts.py index 4f1baa5f8..2f75b7810 100644 --- a/plugins/module_utils/network/nxos/facts/facts.py +++ b/plugins/module_utils/network/nxos/facts/facts.py @@ -178,7 +178,10 @@ def get_resource_subsets(self): return facts_resource_subsets def get_facts( - self, legacy_facts_type=None, resource_facts_type=None, data=None + self, + legacy_facts_type=None, + resource_facts_type=None, + data=None, ): """Collect the facts for nxos :param legacy_facts_type: List of legacy facts types @@ -191,12 +194,15 @@ def get_facts( if frozenset(VALID_RESOURCE_SUBSETS.keys()): self.get_network_resources_facts( - VALID_RESOURCE_SUBSETS, resource_facts_type, data + VALID_RESOURCE_SUBSETS, + resource_facts_type, + data, ) if self.VALID_LEGACY_GATHER_SUBSETS: self.get_network_legacy_facts( - FACT_LEGACY_SUBSETS, legacy_facts_type + FACT_LEGACY_SUBSETS, + legacy_facts_type, ) return self.ansible_facts, self._warnings diff --git a/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py b/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py index 6f25c4deb..3bd71d790 100644 --- a/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/fc_interfaces/fc_interfaces.py @@ -8,9 +8,7 @@ import operator import re -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.fc_interfaces.fc_interfaces import ( Fc_interfacesArgs, @@ -58,7 +56,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Fc_interfaces template fc_interfaces_parser = Fc_interfacesTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = list(fc_interfaces_parser.parse().values()) @@ -91,11 +90,7 @@ def populate_facts(self, connection, ansible_facts, data=None): sorted_dict = sorted(modified_objs, key=operator.itemgetter("m", "p")) objs = [ - { - key: value - for key, value in eachdict.items() - if key not in ["m", "p"] - } + {key: value for key, value in eachdict.items() if key not in ["m", "p"]} for eachdict in sorted_dict ] @@ -103,7 +98,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( fc_interfaces_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/hostname/hostname.py b/plugins/module_utils/network/nxos/facts/hostname/hostname.py index 56300fc1a..3024689fe 100644 --- a/plugins/module_utils/network/nxos/facts/hostname/hostname.py +++ b/plugins/module_utils/network/nxos/facts/hostname/hostname.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.hostname.hostname import ( HostnameArgs, @@ -58,7 +56,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Hostname template hostname_parser = HostnameTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = hostname_parser.parse() @@ -66,7 +65,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( hostname_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py b/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py index f8bb5a3b9..a9a9923b0 100644 --- a/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/hsrp_interfaces/hsrp_interfaces.py @@ -16,9 +16,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.hsrp_interfaces.hsrp_interfaces import ( Hsrp_interfacesArgs, @@ -70,7 +68,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["hsrp_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["hsrp_interfaces"].append(utils.remove_empties(cfg)) @@ -96,7 +95,10 @@ def render_config(self, spec, conf): return {} config["name"] = intf config["bfd"] = utils.parse_conf_cmd_arg( - conf, "hsrp bfd", "enable", "disable" + conf, + "hsrp bfd", + "enable", + "disable", ) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py b/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py index 155afd358..d871c50a8 100644 --- a/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py +++ b/plugins/module_utils/network/nxos/facts/interfaces/interfaces.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.interfaces.interfaces import ( InterfacesArgs, @@ -71,7 +69,8 @@ def populate_facts(self, connection, ansible_facts, data=None): facts["interfaces"] = [] if objs: params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["interfaces"].append(utils.remove_empties(cfg)) @@ -100,11 +99,17 @@ def render_config(self, spec, conf): config["mtu"] = utils.parse_conf_arg(conf, "mtu") config["duplex"] = utils.parse_conf_arg(conf, "duplex") config["mode"] = utils.parse_conf_cmd_arg( - conf, "switchport", "layer2", "layer3" + conf, + "switchport", + "layer2", + "layer3", ) config["enabled"] = utils.parse_conf_cmd_arg( - conf, "shutdown", False, True + conf, + "shutdown", + False, + True, ) config["fabric_forwarding_anycast_gateway"] = utils.parse_conf_cmd_arg( @@ -113,7 +118,9 @@ def render_config(self, spec, conf): True, ) config["ip_forward"] = utils.parse_conf_cmd_arg( - conf, "ip forward", True + conf, + "ip forward", + True, ) interfaces_cfg = utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py b/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py index 90a534488..cd3579a5c 100644 --- a/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/l2_interfaces/l2_interfaces.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.l2_interfaces.l2_interfaces import ( L2_interfacesArgs, @@ -71,7 +69,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["l2_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["l2_interfaces"].append(utils.remove_empties(cfg)) @@ -99,14 +98,16 @@ def render_config(self, spec, conf): config["mode"] = utils.parse_conf_arg(conf, "switchport mode") config["ip_forward"] = utils.parse_conf_arg(conf, "ip forward") config["access"]["vlan"] = utils.parse_conf_arg( - conf, "switchport access vlan" + conf, + "switchport access vlan", ) config["trunk"]["allowed_vlans"] = utils.parse_conf_arg( conf, "switchport trunk allowed vlan", ) config["trunk"]["native_vlan"] = utils.parse_conf_arg( - conf, "switchport trunk native vlan" + conf, + "switchport trunk native vlan", ) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py index d93be1f43..2728d261a 100644 --- a/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/l3_interfaces/l3_interfaces.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.l3_interfaces.l3_interfaces import ( L3_interfacesArgs, @@ -71,7 +69,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["l3_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["l3_interfaces"].append(utils.remove_empties(cfg)) @@ -96,16 +95,26 @@ def render_config(self, spec, conf): config["name"] = intf config["dot1q"] = utils.parse_conf_arg(conf, "encapsulation dot1[qQ]") config["redirects"] = utils.parse_conf_cmd_arg( - conf, "no ip redirects", False, True + conf, + "no ip redirects", + False, + True, ) config["ipv6_redirects"] = utils.parse_conf_cmd_arg( - conf, "no ipv6 redirects", False, True + conf, + "no ipv6 redirects", + False, + True, ) config["unreachables"] = utils.parse_conf_cmd_arg( - conf, "ip unreachables", True, False + conf, + "ip unreachables", + True, + False, ) config["evpn_multisite_tracking"] = utils.parse_conf_arg( - conf, "evpn multisite" + conf, + "evpn multisite", ) ipv4_match = re.compile(r"\n ip address (.*)") matches = ipv4_match.findall(conf) @@ -124,7 +133,7 @@ def render_config(self, spec, conf): if len(ipv4_conf) == 4: if ipv4_conf[2] == "tag": config_dict.update( - {"tag": int(ipv4_conf[-1])} + {"tag": int(ipv4_conf[-1])}, ) elif d == "tag": config_dict.update({"tag": int(ipv4_conf[-1])}) diff --git a/plugins/module_utils/network/nxos/facts/lacp/lacp.py b/plugins/module_utils/network/nxos/facts/lacp/lacp.py index 31c29c0ef..cf6c02b80 100644 --- a/plugins/module_utils/network/nxos/facts/lacp/lacp.py +++ b/plugins/module_utils/network/nxos/facts/lacp/lacp.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lacp.lacp import ( LacpArgs, @@ -60,7 +58,8 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) facts["lacp"] = utils.remove_empties(params["config"]) ansible_facts["ansible_network_resources"].update(facts) @@ -87,7 +86,9 @@ def render_config(self, spec, conf): address = a_match.group(1) config["system"]["mac"]["address"] = address r_match = re.search( - r"lacp system-mac {0} role (\S+)".format(address), conf, re.M + r"lacp system-mac {0} role (\S+)".format(address), + conf, + re.M, ) if r_match: config["system"]["mac"]["role"] = r_match.group(1) diff --git a/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py b/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py index 2d9e7beff..955c413fb 100644 --- a/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/lacp_interfaces/lacp_interfaces.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lacp_interfaces.lacp_interfaces import ( Lacp_interfacesArgs, @@ -72,7 +70,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["lacp_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["lacp_interfaces"].append(utils.remove_empties(cfg)) @@ -98,7 +97,8 @@ def render_config(self, spec, conf): return {} config["name"] = intf config["port_priority"] = utils.parse_conf_arg( - conf, "lacp port-priority" + conf, + "lacp port-priority", ) config["rate"] = utils.parse_conf_arg(conf, "lacp rate") config["mode"] = utils.parse_conf_arg(conf, "lacp mode") diff --git a/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py b/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py index 1f0fb0289..688350a7f 100644 --- a/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/lag_interfaces/lag_interfaces.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lag_interfaces.lag_interfaces import ( Lag_interfacesArgs, @@ -62,7 +60,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["lag_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["lag_interfaces"].append(utils.remove_empties(cfg)) @@ -101,7 +100,7 @@ def render_config(self, spec, conf, connection): if member and member.get("port_channel", None): port_channel = "port-channel{0}".format( - member.pop("port_channel") + member.pop("port_channel"), ) for x in result: if x["name"] == port_channel: diff --git a/plugins/module_utils/network/nxos/facts/legacy/base.py b/plugins/module_utils/network/nxos/facts/legacy/base.py index 6cc5447ea..40b91718c 100644 --- a/plugins/module_utils/network/nxos/facts/legacy/base.py +++ b/plugins/module_utils/network/nxos/facts/legacy/base.py @@ -60,8 +60,7 @@ def run(self, command, output="text"): return resp[0] except IndexError: self.warnings.append( - "command %s failed, facts for this command will not be populated" - % command_string, + "command %s failed, facts for this command will not be populated" % command_string, ) return None @@ -157,12 +156,8 @@ def populate(self): if data: if isinstance(data, dict): - self.facts["memtotal_mb"] = ( - int(data["memory_usage_total"]) / 1024 - ) - self.facts["memfree_mb"] = ( - int(data["memory_usage_free"]) / 1024 - ) + self.facts["memtotal_mb"] = int(data["memory_usage_total"]) / 1024 + self.facts["memfree_mb"] = int(data["memory_usage_free"]) / 1024 else: self.facts["memtotal_mb"] = self.parse_memtotal_mb(data) self.facts["memfree_mb"] = self.parse_memfree_mb(data) @@ -229,11 +224,11 @@ class Interfaces(FactsBase): ) INTERFACE_IPV4_MAP = frozenset( - [("eth_ip_addr", "address"), ("eth_ip_mask", "masklen")] + [("eth_ip_addr", "address"), ("eth_ip_mask", "masklen")], ) INTERFACE_SVI_IPV4_MAP = frozenset( - [("svi_ip_addr", "address"), ("svi_ip_mask", "masklen")] + [("svi_ip_addr", "address"), ("svi_ip_mask", "masklen")], ) INTERFACE_IPV6_MAP = frozenset([("addr", "address"), ("prefix", "subnet")]) @@ -259,7 +254,7 @@ def populate(self): if data: if isinstance(data, dict): self.facts["interfaces"] = self.populate_structured_interfaces( - data + data, ) else: interfaces = self.parse_interfaces(data) @@ -280,7 +275,7 @@ def populate(self): if data: if isinstance(data, dict): self.facts["neighbors"].update( - self.populate_structured_neighbors_lldp(data) + self.populate_structured_neighbors_lldp(data), ) else: self.facts["neighbors"].update(self.populate_neighbors(data)) @@ -289,11 +284,11 @@ def populate(self): if data: if isinstance(data, dict): self.facts["neighbors"].update( - self.populate_structured_neighbors_cdp(data) + self.populate_structured_neighbors_cdp(data), ) else: self.facts["neighbors"].update( - self.populate_neighbors_cdp(data) + self.populate_neighbors_cdp(data), ) self.facts["neighbors"].pop(None, None) # Remove null key @@ -316,13 +311,15 @@ def populate_structured_interfaces(self, data): if "eth_ip_addr" in item: intf["ipv4"] = self.transform_dict( - item, self.INTERFACE_IPV4_MAP + item, + self.INTERFACE_IPV4_MAP, ) self.facts["all_ipv4_addresses"].append(item["eth_ip_addr"]) if "svi_ip_addr" in item: intf["ipv4"] = self.transform_dict( - item, self.INTERFACE_SVI_IPV4_MAP + item, + self.INTERFACE_SVI_IPV4_MAP, ) self.facts["all_ipv4_addresses"].append(item["svi_ip_addr"]) @@ -340,14 +337,13 @@ def populate_structured_ipv6_interfaces(self, data): name = item["ROW_intf"]["intf-name"] intf = self.facts["interfaces"][name] intf["ipv6"] = self.transform_dict( - item, self.INTERFACE_IPV6_MAP + item, + self.INTERFACE_IPV6_MAP, ) try: addr = item["ROW_intf"]["addr"] except KeyError: - addr = item["ROW_intf"]["TABLE_addr"]["ROW_addr"][ - "addr" - ] + addr = item["ROW_intf"]["TABLE_addr"]["ROW_addr"]["addr"] self.facts["all_ipv6_addresses"].append(addr) else: return "" @@ -373,9 +369,7 @@ def populate_structured_neighbors_lldp(self, data): def populate_structured_neighbors_cdp(self, data): objects = dict() - data = data["TABLE_cdp_neighbor_detail_info"][ - "ROW_cdp_neighbor_detail_info" - ] + data = data["TABLE_cdp_neighbor_detail_info"]["ROW_cdp_neighbor_detail_info"] if isinstance(data, dict): data = [data] @@ -407,7 +401,7 @@ def parse_interfaces(self, data): if match: key = match.group(1) if not key.startswith("admin") or not key.startswith( - "IPv6 Interface" + "IPv6 Interface", ): parsed[key] = line return parsed @@ -419,16 +413,19 @@ def populate_interfaces(self, interfaces): if get_interface_type(key) == "svi": intf["state"] = self.parse_state(key, value, intf_type="svi") intf["macaddress"] = self.parse_macaddress( - value, intf_type="svi" + value, + intf_type="svi", ) intf["mtu"] = self.parse_mtu(value, intf_type="svi") intf["bandwidth"] = self.parse_bandwidth( - value, intf_type="svi" + value, + intf_type="svi", ) intf["type"] = self.parse_type(value, intf_type="svi") if "Internet Address" in value: intf["ipv4"] = self.parse_ipv4_address( - value, intf_type="svi" + value, + intf_type="svi", ) facts[key] = intf else: @@ -653,9 +650,7 @@ def populate(self): data = self.run("show interface", output="json") if data: if isinstance(data, dict): - self.facts[ - "interfaces_list" - ] = self.parse_structured_interfaces(data) + self.facts["interfaces_list"] = self.parse_structured_interfaces(data) else: self.facts["interfaces_list"] = self.parse_interfaces(data) @@ -683,12 +678,10 @@ def populate(self): data = self.run("show environment power", output="json") if data: if isinstance(data, dict): - self.facts[ - "power_supply_info" - ] = self.parse_structured_power_supply_info(data) + self.facts["power_supply_info"] = self.parse_structured_power_supply_info(data) else: self.facts["power_supply_info"] = self.parse_power_supply_info( - data + data, ) def parse_structured_interfaces(self, data): @@ -722,7 +715,7 @@ def parse_structured_module(self, data): if isinstance(entry, dict): entry = [entry] entry_objects = list( - self.transform_iterable(entry, self.MODULE_MAP) + self.transform_iterable(entry, self.MODULE_MAP), ) objects.extend(entry_objects) return objects diff --git a/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py b/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py index b7693886f..5fd35c884 100644 --- a/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py +++ b/plugins/module_utils/network/nxos/facts/lldp_global/lldp_global.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lldp_global.lldp_global import ( Lldp_globalArgs, @@ -62,7 +60,8 @@ def populate_facts(self, connection, ansible_facts, data=None): facts = {} if objs: params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) facts["lldp_global"] = params["config"] facts = utils.remove_empties(facts) @@ -83,7 +82,8 @@ def render_config(self, spec, conf): conf = re.split("\n", conf) for command in conf: param = re.search( - r"(.*)lldp (\w+(-?)\w+)", command + r"(.*)lldp (\w+(-?)\w+)", + command, ) # get the word after 'lldp' if param: # get the nested-dict/value for that param @@ -98,9 +98,7 @@ def render_config(self, spec, conf): key2 = key2.split() key2[0] = key2[0].replace("-", "_") if len(key2) == 1: - if ( - "port" in key2[0] or "system" in key2[0] - ): # nested dicts + if "port" in key2[0] or "system" in key2[0]: # nested dicts key2 = key2[0].split("_") # config[tlv_select][system][name]=False config[key1][key2[0]][key2[1]] = False diff --git a/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py b/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py index 58b2edf40..96fcc1ba3 100644 --- a/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/lldp_interfaces/lldp_interfaces.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lldp_interfaces.lldp_interfaces import ( Lldp_interfacesArgs, @@ -86,7 +84,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["lldp_interfaces"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["lldp_interfaces"].append(utils.remove_empties(cfg)) diff --git a/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py b/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py index 3d59d5a59..7cf2a11a9 100644 --- a/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py +++ b/plugins/module_utils/network/nxos/facts/logging_global/logging_global.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.logging_global.logging_global import ( Logging_globalArgs, @@ -62,7 +60,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Logging_global template logging_global_parser = Logging_globalTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = logging_global_parser.parse() diff --git a/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py b/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py index f66471676..1580b14af 100644 --- a/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py +++ b/plugins/module_utils/network/nxos/facts/ntp_global/ntp_global.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ntp_global.ntp_global import ( Ntp_globalArgs, @@ -58,7 +56,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Ntp_global template ntp_global_parser = Ntp_globalTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = ntp_global_parser.parse() @@ -85,7 +84,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( ntp_global_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py b/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py index 82a1b26e4..837fae53b 100644 --- a/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/facts/ospf_interfaces/ospf_interfaces.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ospf_interfaces.ospf_interfaces import ( Ospf_interfacesArgs, @@ -72,14 +70,14 @@ def populate_facts(self, connection, ansible_facts, data=None): if af.get("multi_areas"): af["multi_areas"].sort() item["address_family"] = sorted( - item["address_family"], key=lambda i: i["afi"] + item["address_family"], + key=lambda i: i["afi"], ) objs = sorted( objs, key=lambda i: [ - int(k) if k.isdigit() else k - for k in i["name"].replace(".", "/").split("/") + int(k) if k.isdigit() else k for k in i["name"].replace(".", "/").split("/") ], ) diff --git a/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py b/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py index ba495b526..9ef3ae33a 100644 --- a/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py +++ b/plugins/module_utils/network/nxos/facts/ospfv2/ospfv2.py @@ -17,9 +17,7 @@ from copy import deepcopy from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ospfv2.ospfv2 import ( Ospfv2Args, @@ -51,7 +49,7 @@ def get_config(self, connection): This method exists solely to allow the unit test framework to mock device connection calls. """ return connection.get( - "show running-config | section '^router ospf .*'" + "show running-config | section '^router ospf .*'", ) def populate_facts(self, connection, ansible_facts, data=None): diff --git a/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py b/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py index 5a8b33ba2..796dacfb5 100644 --- a/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py +++ b/plugins/module_utils/network/nxos/facts/ospfv3/ospfv3.py @@ -16,9 +16,7 @@ """ from ansible.module_utils.six import iteritems -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.ospfv3.ospfv3 import ( Ospfv3Args, diff --git a/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py b/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py index 79b4b256d..4eb62dadc 100644 --- a/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py +++ b/plugins/module_utils/network/nxos/facts/prefix_lists/prefix_lists.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.prefix_lists.prefix_lists import ( Prefix_listsArgs, @@ -39,7 +37,7 @@ def get_config(self, connection): This method exists solely to allow the unit test framework to mock device connection calls. """ return connection.get( - "show running-config | section 'ip(.*) prefix-list'" + "show running-config | section 'ip(.*) prefix-list'", ) def populate_facts(self, connection, ansible_facts, data=None): @@ -59,7 +57,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Prefix_lists template prefix_lists_parser = Prefix_listsTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = list(prefix_lists_parser.parse().values()) @@ -73,14 +72,17 @@ def populate_facts(self, connection, ansible_facts, data=None): for x in item["prefix_lists"]: if "entries" in x: x["entries"] = sorted( - x["entries"], key=lambda k: k["sequence"] + x["entries"], + key=lambda k: k["sequence"], ) objs = sorted(objs, key=lambda k: k["afi"]) ansible_facts["ansible_network_resources"].pop("prefix_lists", None) params = utils.remove_empties( prefix_lists_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) facts["prefix_lists"] = params.get("config", []) diff --git a/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py b/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py index 82c13a8d9..745c647d3 100644 --- a/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py +++ b/plugins/module_utils/network/nxos/facts/route_maps/route_maps.py @@ -15,9 +15,7 @@ based on the configuration. """ -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.route_maps.route_maps import ( Route_mapsArgs, @@ -58,7 +56,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Route_maps template route_maps_parser = Route_mapsTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = list(route_maps_parser.parse().values()) @@ -70,7 +69,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( route_maps_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py b/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py index 99a1e41d0..e5b137bae 100644 --- a/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py +++ b/plugins/module_utils/network/nxos/facts/snmp_server/snmp_server.py @@ -15,9 +15,7 @@ based on the configuration. """ from ansible.module_utils._text import to_text -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.snmp_server.snmp_server import ( Snmp_serverArgs, @@ -58,13 +56,15 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Snmp_server template snmp_server_parser = Snmp_serverTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = snmp_server_parser.parse() if "communities" in objs: objs["communities"] = sorted( - objs["communities"], key=lambda k: to_text(k["name"]) + objs["communities"], + key=lambda k: to_text(k["name"]), ) if "users" in objs: @@ -83,7 +83,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( snmp_server_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py b/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py index 4b041f66c..3bfe99b08 100644 --- a/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py +++ b/plugins/module_utils/network/nxos/facts/static_routes/static_routes.py @@ -15,9 +15,7 @@ __metaclass__ = type -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.static_routes.static_routes import ( Static_routesArgs, @@ -36,10 +34,10 @@ def __init__(self, module, subspec="config", options="options"): def get_static_routes_data(self, connection): non_vrf_data = connection.get( - "show running-config | include '^ip(v6)* route'" + "show running-config | include '^ip(v6)* route'", ) vrf_data = connection.get( - "show running-config | section '^vrf context'" + "show running-config | section '^vrf context'", ) if vrf_data: non_vrf_data += "\n" + vrf_data @@ -91,11 +89,11 @@ def structure_static_routes(self, strout): if afi_v4: _triv_static_route["address_families"].append( - {"afi": "ipv4", "routes": afi_v4} + {"afi": "ipv4", "routes": afi_v4}, ) if afi_v6: _triv_static_route["address_families"].append( - {"afi": "ipv6", "routes": afi_v6} + {"afi": "ipv6", "routes": afi_v6}, ) _static_route_facts.append(_triv_static_route) @@ -111,11 +109,11 @@ def structure_static_routes(self, strout): if afi_v4: _vrf_static_route["address_families"].append( - {"afi": "ipv4", "routes": afi_v4} + {"afi": "ipv4", "routes": afi_v4}, ) if afi_v6: _vrf_static_route["address_families"].append( - {"afi": "ipv6", "routes": afi_v6} + {"afi": "ipv6", "routes": afi_v6}, ) _static_route_facts.append(_vrf_static_route) @@ -140,7 +138,8 @@ def populate_facts(self, connection, ansible_facts, data=None): # parse native config using the Static_routes template static_routes_parser = Static_routesTemplate( - lines=data.splitlines(), module=self._module + lines=data.splitlines(), + module=self._module, ) objs = static_routes_parser.parse() @@ -151,7 +150,9 @@ def populate_facts(self, connection, ansible_facts, data=None): params = utils.remove_empties( static_routes_parser.validate_config( - self.argument_spec, {"config": objs}, redact=True + self.argument_spec, + {"config": objs}, + redact=True, ), ) diff --git a/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py b/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py index 0fc62950c..6a5cef844 100644 --- a/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py +++ b/plugins/module_utils/network/nxos/facts/telemetry/telemetry.py @@ -18,9 +18,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.telemetry.telemetry import ( TelemetryArgs, @@ -31,9 +29,7 @@ TMS_SENSORGROUP, TMS_SUBSCRIPTION, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( - NxosCmdRef, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import NxosCmdRef from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.telemetry.telemetry import ( cr_key_lookup, get_instance_data, @@ -84,7 +80,7 @@ def populate_facts(self, connection, ansible_facts, data=None): # Get Telemetry Global Data cmd_ref["TMS_GLOBAL"]["ref"] = [] cmd_ref["TMS_GLOBAL"]["ref"].append( - NxosCmdRef(self._module, TMS_GLOBAL) + NxosCmdRef(self._module, TMS_GLOBAL), ) ref = cmd_ref["TMS_GLOBAL"]["ref"][0] ref.set_context() @@ -102,7 +98,7 @@ def populate_facts(self, connection, ansible_facts, data=None): if re.search(r"destination-group", line): resource_key = line.strip() cmd_ref["TMS_DESTGROUP"]["ref"].append( - NxosCmdRef(self._module, TMS_DESTGROUP) + NxosCmdRef(self._module, TMS_DESTGROUP), ) ref = cmd_ref["TMS_DESTGROUP"]["ref"][-1] ref.set_context([resource_key]) @@ -115,7 +111,7 @@ def populate_facts(self, connection, ansible_facts, data=None): if re.search(r"sensor-group", line): resource_key = line.strip() cmd_ref["TMS_SENSORGROUP"]["ref"].append( - NxosCmdRef(self._module, TMS_SENSORGROUP) + NxosCmdRef(self._module, TMS_SENSORGROUP), ) ref = cmd_ref["TMS_SENSORGROUP"]["ref"][-1] ref.set_context([resource_key]) @@ -173,38 +169,30 @@ def render_config(self, spec, cmd_ref): cr_keys = cr_key_lookup(key, mo) for cr_key in cr_keys: if cr._ref.get(cr_key) and cr._ref[cr_key].get( - "existing" + "existing", ): if isinstance(config[key], dict): for k in config[key].keys(): - for existing_key in cr._ref[cr_key][ - "existing" - ].keys(): - config[key][k] = cr._ref[cr_key][ - "existing" - ][existing_key][k] + for existing_key in cr._ref[cr_key]["existing"].keys(): + config[key][k] = cr._ref[cr_key]["existing"][existing_key][ + k + ] continue if isinstance(config[key], list): - for existing_key in cr._ref[cr_key][ - "existing" - ].keys(): + for existing_key in cr._ref[cr_key]["existing"].keys(): data = get_instance_data( - key, cr_key, cr, existing_key + key, + cr_key, + cr, + existing_key, ) config[key].append(data) continue - for existing_key in cr._ref[cr_key][ - "existing" - ].keys(): - config[key] = cr._ref[cr_key]["existing"][ - existing_key - ] + for existing_key in cr._ref[cr_key]["existing"].keys(): + config[key] = cr._ref[cr_key]["existing"][existing_key] elif cr._ref.get(cr_key): data = get_instance_data(key, cr_key, cr, None) - if ( - isinstance(config[key], list) - and data not in config[key] - ): + if isinstance(config[key], list) and data not in config[key]: config[key].append(data) return utils.remove_empties(config) diff --git a/plugins/module_utils/network/nxos/facts/vlans/vlans.py b/plugins/module_utils/network/nxos/facts/vlans/vlans.py index 380754c85..92f068037 100644 --- a/plugins/module_utils/network/nxos/facts/vlans/vlans.py +++ b/plugins/module_utils/network/nxos/facts/vlans/vlans.py @@ -20,9 +20,7 @@ from copy import deepcopy -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( - utils, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( parse_conf_arg, ) @@ -77,17 +75,20 @@ def populate_facts(self, connection, ansible_facts, data=None): # Not all devices support | json-pretty but is a workaround for # libssh issue https://github.com/ansible/pylibssh/issues/208 structured = self.get_device_data( - connection, "show vlan | json-pretty" + connection, + "show vlan | json-pretty", ) except Exception: # When json-pretty is not supported, we fall back to | json structured = self.get_device_data( - connection, "show vlan | json" + connection, + "show vlan | json", ) # Raw cli config is needed for mapped_vni, which is not included in structured. run_cfg_output = self.get_device_data( - connection, "show running-config | section ^vlan" + connection, + "show running-config | section ^vlan", ) else: running_config = data.split("\n\n") @@ -106,7 +107,8 @@ def populate_facts(self, connection, ansible_facts, data=None): if objs: facts["vlans"] = [] params = utils.validate_config( - self.argument_spec, {"config": objs} + self.argument_spec, + {"config": objs}, ) for cfg in params["config"]: facts["vlans"].append(utils.remove_empties(cfg)) @@ -137,9 +139,7 @@ def render_config(self, spec, vlan): obj["mode"] = vlan["vlanshowinfo-vlanmode"].replace("-vlan", "") # enabled: shutdown, noshutdown - obj["enabled"] = ( - True if "noshutdown" in vlan["vlanshowbr-shutstate"] else False - ) + obj["enabled"] = True if "noshutdown" in vlan["vlanshowbr-shutstate"] else False # state: active, suspend obj["state"] = vlan["vlanshowbr-vlanstate"] diff --git a/plugins/module_utils/network/nxos/nxos.py b/plugins/module_utils/network/nxos/nxos.py index 6eecac49e..19ef857ea 100644 --- a/plugins/module_utils/network/nxos/nxos.py +++ b/plugins/module_utils/network/nxos/nxos.py @@ -105,7 +105,7 @@ def get_config(self, flags=None): out = connection.get_config(flags=flags) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) cfg = to_text(out, errors="surrogate_then_replace").strip() + "\n" @@ -125,13 +125,13 @@ def run_commands(self, commands, check_rc=True): if network_api == "cliconf" and out: for index, resp in enumerate(out): if ( - "Invalid command at" in resp - or "Ambiguous command at" in resp + "Invalid command at" in resp or "Ambiguous command at" in resp ) and "json" in resp: if commands[index]["output"] == "json": commands[index]["output"] = "text" out = connection.run_commands( - commands, check_rc + commands, + check_rc, ) return out except ConnectionError as exc: @@ -156,10 +156,7 @@ def load_config(self, config, return_error=False, opts=None, replace=None): responses.append(err) return responses elif code and "no graceful-restart" in err: - if ( - "ISSU/HA will be affected if Graceful Restart is disabled" - in err - ): + if "ISSU/HA will be affected if Graceful Restart is disabled" in err: msg = [""] responses.extend(msg) return responses @@ -192,7 +189,7 @@ def get_diff( ) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) return response @@ -206,7 +203,7 @@ def get_capabilities(self): capabilities = connection.get_capabilities() except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) self._module._capabilities = json.loads(capabilities) return self._module._capabilities @@ -217,7 +214,7 @@ def read_module_context(self, module_key): module_context = connection.read_module_context(module_key) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) return module_context @@ -228,7 +225,7 @@ def save_module_context(self, module_key, module_context): connection.save_module_context(module_key, module_context) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) return None @@ -282,7 +279,7 @@ def get_config(self, flags=None): out = self._connection.send_request(cmd) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) cfg = to_text(out).strip() @@ -307,7 +304,9 @@ def get_diff( if running and diff_match != "none" and diff_replace != "config": # running configuration running_obj = NetworkConfig( - indent=2, contents=running, ignore_lines=diff_ignore_lines + indent=2, + contents=running, + ignore_lines=diff_ignore_lines, ) configdiffobjs = candidate_obj.difference( running_obj, @@ -319,13 +318,15 @@ def get_diff( else: configdiffobjs = candidate_obj.items - diff["config_diff"] = ( - dumps(configdiffobjs, "commands") if configdiffobjs else "" - ) + diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else "" return diff def load_config( - self, commands, return_error=False, opts=None, replace=None + self, + commands, + return_error=False, + opts=None, + replace=None, ): """Sends the ordered set of commands to the device""" if opts is None: @@ -344,10 +345,7 @@ def load_config( elif opts.get("catch_clierror") and "400" in code: return [code, err] elif code and "no graceful-restart" in err: - if ( - "ISSU/HA will be affected if Graceful Restart is disabled" - in err - ): + if "ISSU/HA will be affected if Graceful Restart is disabled" in err: msg = [""] responses.extend(msg) return responses @@ -360,7 +358,11 @@ def load_config( return responses def edit_config( - self, candidate=None, commit=True, replace=None, comment=None + self, + candidate=None, + commit=True, + replace=None, + comment=None, ): resp = list() @@ -384,19 +386,23 @@ def get_capabilities(self): capabilities = self._connection.get_capabilities() except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) return json.loads(capabilities) def check_edit_config_capability( - self, candidate=None, commit=True, replace=None, comment=None + self, + candidate=None, + commit=True, + replace=None, + comment=None, ): operations = self._connection.get_device_operations() if not candidate and not replace: raise ValueError( - "must provide a candidate or replace to load configuration" + "must provide a candidate or replace to load configuration", ) if commit not in (True, False): @@ -413,7 +419,7 @@ def read_module_context(self, module_key): module_context = self._connection.read_module_context(module_key) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) return module_context @@ -423,7 +429,7 @@ def save_module_context(self, module_key, module_context): self._connection.save_module_context(module_key, module_context) except ConnectionError as exc: self._module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) return None @@ -537,7 +543,8 @@ def get_platform_shortname(self): # Supported Platforms: N3K,N5K,N6K,N7K,N9K,N3K-F,N9K-F m = re.match( - "(?PN[35679][K57])-(?PC35)*", network_os_platform + "(?PN[35679][K57])-(?PC35)*", + network_os_platform, ) if not m: return None @@ -627,8 +634,8 @@ def pattern_match_existing(self, output, k): if len(match) > 1 and not multiple: raise ValueError( "get_existing: multiple matches found for property {0}".format( - k - ) + k, + ), ) else: match = [m.groups() for m in match_lines if m] @@ -637,8 +644,8 @@ def pattern_match_existing(self, output, k): if len(match) > 1 and not multiple: raise ValueError( "get_existing: multiple matches found for property {0}".format( - k - ) + k, + ), ) for item in match: index = match.index(item) @@ -703,10 +710,7 @@ def get_existing(self, cache_output=None): # We need to remove the last item in context for state absent case. if ref["_state"] in self.absent_states and ref["_context"]: - if ( - ref["_resource_key"] - and ref["_resource_key"] == ref["_context"][-1] - ): + if ref["_resource_key"] and ref["_resource_key"] == ref["_context"][-1]: if ref["_context"][-1] in output: ref["_context"][-1] = "no " + ref["_context"][-1] else: @@ -740,7 +744,7 @@ def get_existing(self, cache_output=None): else: raise ValueError( "get_existing: unknown 'kind' value specified for key '{0}'".format( - k + k, ), ) @@ -817,12 +821,13 @@ def build_cmd_set(self, playval, existing, k): else: raise ValueError( "get_proposed: unknown 'kind' value specified for key '{0}'".format( - k - ) + k, + ), ) if cmd: if ref["_state"] in self.absent_states and not re.search( - r"^no", cmd + r"^no", + cmd, ): cmd = "no " + cmd # Commands may require parent commands for proper context. @@ -853,15 +858,11 @@ def compare(playval, existing): return False elif str(playval) == str(existing): return True - elif ( - isinstance(existing, dict) and playval in existing.values() - ): + elif isinstance(existing, dict) and playval in existing.values(): return True if ref["_state"] in self.absent_states: - if isinstance(existing, dict) and all( - x is None for x in existing.values() - ): + if isinstance(existing, dict) and all(x is None for x in existing.values()): existing = None if existing is None or playval not in existing.values(): return True @@ -881,9 +882,7 @@ def compare(playval, existing): for ekey, evalue in existing.items(): if isinstance(evalue, dict): # Remove values set to string 'None' from dvalue - evalue = dict( - (k, v) for k, v in evalue.items() if v != "None" - ) + evalue = dict((k, v) for k, v in evalue.items() if v != "None") for pkey, pvalue in playval.items(): if compare(pvalue, evalue): if playval_copy.get(pkey): diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py b/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py index f271cefc6..02ceb1fa5 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_address_family.py @@ -69,7 +69,8 @@ def _tmplt_redistribute(redis): class Bgp_address_familyTemplate(NetworkTemplate): def __init__(self, lines=None): super(Bgp_address_familyTemplate, self).__init__( - lines=lines, tmplt=self + lines=lines, + tmplt=self, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_global.py b/plugins/module_utils/network/nxos/rm_templates/bgp_global.py index 437f30fe6..570ddb2ae 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_global.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_global.py @@ -59,7 +59,9 @@ def _tmplt_bfd(proc): class Bgp_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Bgp_globalTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py b/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py index ca8c62b14..3e0df945e 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_neighbor_address_family.py @@ -37,7 +37,8 @@ def _tmplt_maximum_prefix(data): class Bgp_neighbor_address_familyTemplate(NetworkTemplate): def __init__(self, lines=None): super(Bgp_neighbor_address_familyTemplate, self).__init__( - lines=lines, tmplt=self + lines=lines, + tmplt=self, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py b/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py index 6ea434f91..960e2cfc7 100644 --- a/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py +++ b/plugins/module_utils/network/nxos/rm_templates/bgp_templates.py @@ -50,7 +50,9 @@ def _tmplt_path_attribute(proc): class Bgp_templatesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Bgp_templatesTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py b/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py index 5a5153a68..f43f661df 100644 --- a/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py +++ b/plugins/module_utils/network/nxos/rm_templates/fc_interfaces.py @@ -49,15 +49,15 @@ "SD", ] -allowed_values_pattern = "|".join( - re.escape(val) for val in allowed_speed_values -) +allowed_values_pattern = "|".join(re.escape(val) for val in allowed_speed_values) class Fc_interfacesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Fc_interfacesTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/hostname.py b/plugins/module_utils/network/nxos/rm_templates/hostname.py index 623c3cd6e..1be361fe0 100644 --- a/plugins/module_utils/network/nxos/rm_templates/hostname.py +++ b/plugins/module_utils/network/nxos/rm_templates/hostname.py @@ -25,7 +25,9 @@ class HostnameTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(HostnameTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/logging_global.py b/plugins/module_utils/network/nxos/rm_templates/logging_global.py index b728f6714..e299e2460 100644 --- a/plugins/module_utils/network/nxos/rm_templates/logging_global.py +++ b/plugins/module_utils/network/nxos/rm_templates/logging_global.py @@ -24,9 +24,7 @@ def _tmplt_hosts(data): cmd = "logging server {host}" - data["client_identity"] = ( - data.get("secure", {}).get("trustpoint", {}).get("client_identity") - ) + data["client_identity"] = data.get("secure", {}).get("trustpoint", {}).get("client_identity") if "severity" in data: cmd += " {severity}" @@ -47,7 +45,9 @@ def _tmplt_hosts(data): class Logging_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Logging_globalTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/ntp_global.py b/plugins/module_utils/network/nxos/rm_templates/ntp_global.py index 20f48ebeb..121d6133c 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ntp_global.py +++ b/plugins/module_utils/network/nxos/rm_templates/ntp_global.py @@ -25,7 +25,9 @@ class Ntp_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Ntp_globalTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py b/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py index 3d149a71f..48ff0c770 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py +++ b/plugins/module_utils/network/nxos/rm_templates/ospf_interfaces.py @@ -39,7 +39,9 @@ def _tmplt_authentication(data): class Ospf_interfacesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Ospf_interfacesTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/ospfv2.py b/plugins/module_utils/network/nxos/rm_templates/ospfv2.py index 39086405c..3dbecfbe5 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ospfv2.py +++ b/plugins/module_utils/network/nxos/rm_templates/ospfv2.py @@ -21,10 +21,7 @@ def _tmplt_area_range(arange): def _tmplt_default_information(proc): command = "default-information originate" - if ( - "always" in proc["default_information"] - and proc["default_information"]["always"] - ): + if "always" in proc["default_information"] and proc["default_information"]["always"]: command += " always" if "route_map" in proc["default_information"]: command += " route-map" @@ -112,7 +109,7 @@ def _tmplt_max_metric(proc): command += " {wait_period}".format(**on_startup) if on_startup.get("wait_for_bgp_asn"): command += " wait-for bgp {wait_for_bgp_asn}".format( - **on_startup + **on_startup, ) if summary_lsa: command += " summary-lsa" diff --git a/plugins/module_utils/network/nxos/rm_templates/ospfv3.py b/plugins/module_utils/network/nxos/rm_templates/ospfv3.py index 443f5eec9..f803c5712 100644 --- a/plugins/module_utils/network/nxos/rm_templates/ospfv3.py +++ b/plugins/module_utils/network/nxos/rm_templates/ospfv3.py @@ -91,11 +91,13 @@ def _tmplt_max_metric(proc): else: external_lsa = max_metric.get("router_lsa", {}).get("external_lsa", {}) stub_prefix_lsa = max_metric.get("router_lsa", {}).get( - "stub_prefix_lsa", {} + "stub_prefix_lsa", + {}, ) on_startup = max_metric.get("router_lsa", {}).get("on_startup", {}) inter_area_prefix_lsa = max_metric.get("router_lsa", {}).get( - "inter_area_prefix_lsa", {} + "inter_area_prefix_lsa", + {}, ) if external_lsa: command += " external-lsa" @@ -109,13 +111,13 @@ def _tmplt_max_metric(proc): command += " {wait_period}".format(**on_startup) if on_startup.get("wait_for_bgp_asn"): command += " wait-for bgp {wait_for_bgp_asn}".format( - **on_startup + **on_startup, ) if inter_area_prefix_lsa: command += " inter-area-prefix-lsa" if inter_area_prefix_lsa.get("max_metric_value"): command += " {max_metric_value}".format( - **inter_area_prefix_lsa + **inter_area_prefix_lsa, ) return command diff --git a/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py b/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py index 66232c1d2..57ab522be 100644 --- a/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py +++ b/plugins/module_utils/network/nxos/rm_templates/prefix_lists.py @@ -25,7 +25,9 @@ class Prefix_listsTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Prefix_listsTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/route_maps.py b/plugins/module_utils/network/nxos/rm_templates/route_maps.py index af6a8c24d..cab39a0f2 100644 --- a/plugins/module_utils/network/nxos/rm_templates/route_maps.py +++ b/plugins/module_utils/network/nxos/rm_templates/route_maps.py @@ -114,7 +114,9 @@ def _tmplt_set_ip_next_hop_verify_availability(data): class Route_mapsTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Route_mapsTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/snmp_server.py b/plugins/module_utils/network/nxos/rm_templates/snmp_server.py index 637f08481..c50cb2225 100644 --- a/plugins/module_utils/network/nxos/rm_templates/snmp_server.py +++ b/plugins/module_utils/network/nxos/rm_templates/snmp_server.py @@ -79,7 +79,9 @@ def _tmplt_users_auth(data): class Snmp_serverTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Snmp_serverTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/rm_templates/static_routes.py b/plugins/module_utils/network/nxos/rm_templates/static_routes.py index f7a3433c9..967c96bd9 100644 --- a/plugins/module_utils/network/nxos/rm_templates/static_routes.py +++ b/plugins/module_utils/network/nxos/rm_templates/static_routes.py @@ -25,7 +25,9 @@ class Static_routesTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): super(Static_routesTemplate, self).__init__( - lines=lines, tmplt=self, module=module + lines=lines, + tmplt=self, + module=module, ) # fmt: off diff --git a/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py b/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py index 38b557414..97ac847a1 100644 --- a/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py +++ b/plugins/module_utils/network/nxos/utils/telemetry/telemetry.py @@ -62,7 +62,8 @@ def valiate_input(playvals, type, module): msg += " Parameter under is required" module.fail_json(msg=msg) if playvals.get("destination") and not isinstance( - playvals["destination"], dict + playvals["destination"], + dict, ): msg = "Invalid playbook value: {0}.".format(playvals) msg += " Parameter under must be a dict" @@ -70,7 +71,9 @@ def valiate_input(playvals, type, module): if not playvals.get("destination") and len(playvals) > 1: msg = "Invalid playbook value: {0}.".format(playvals) msg += " Playbook entry contains unrecongnized parameters." - msg += " Make sure keys under are specified as follows:" + msg += ( + " Make sure keys under are specified as follows:" + ) msg += " destination: {ip: , port: , protocol: , encoding: }}" module.fail_json(msg=msg) @@ -81,9 +84,7 @@ def valiate_input(playvals, type, module): module.fail_json(msg=msg) if playvals.get("path") and "name" not in playvals["path"].keys(): msg = "Invalid playbook value: {0}.".format(playvals) - msg += ( - " Parameter under requires key" - ) + msg += " Parameter under requires key" module.fail_json(msg=msg) @@ -149,9 +150,7 @@ def remove_duplicate_context(cmds): """Helper method to remove duplicate telemetry context commands""" if not cmds: return cmds - feature_indices = [ - i for i, x in enumerate(cmds) if x == "feature telemetry" - ] + feature_indices = [i for i, x in enumerate(cmds) if x == "feature telemetry"] telemetry_indices = [i for i, x in enumerate(cmds) if x == "telemetry"] if len(feature_indices) == 1 and len(telemetry_indices) == 1: return cmds @@ -182,7 +181,7 @@ def get_setval_path(module_or_path_data): path = module_or_path_data else: path = module_or_path_data.params["config"]["sensor_groups"][0].get( - "path" + "path", ) if path is None: return path @@ -229,16 +228,12 @@ def massage_data(have_or_want): if item.get("destination"): if item.get("destination").get("port"): item["destination"]["port"] = str( - item["destination"]["port"] + item["destination"]["port"], ) if item.get("destination").get("protocol"): - item["destination"]["protocol"] = item["destination"][ - "protocol" - ].lower() + item["destination"]["protocol"] = item["destination"]["protocol"].lower() if item.get("destination").get("encoding"): - item["destination"]["encoding"] = item["destination"][ - "encoding" - ].lower() + item["destination"]["encoding"] = item["destination"]["encoding"].lower() if item.get("path"): for key in [ "filter_condition", @@ -254,7 +249,7 @@ def massage_data(have_or_want): if item.get("sensor_group"): if item.get("sensor_group").get("id"): item["sensor_group"]["id"] = str( - item["sensor_group"]["id"] + item["sensor_group"]["id"], ) if item.get("sensor_group").get("sample_interval"): item["sensor_group"]["sample_interval"] = str( diff --git a/plugins/module_utils/network/nxos/utils/utils.py b/plugins/module_utils/network/nxos/utils/utils.py index 8e5c50b3e..01468edd5 100644 --- a/plugins/module_utils/network/nxos/utils/utils.py +++ b/plugins/module_utils/network/nxos/utils/utils.py @@ -124,9 +124,7 @@ def remove_rsvd_interfaces(interfaces): """Exclude reserved interfaces from user management""" if not interfaces: return [] - return [ - i for i in interfaces if get_interface_type(i["name"]) != "management" - ] + return [i for i in interfaces if get_interface_type(i["name"]) != "management"] def vlan_range_to_list(vlans): diff --git a/plugins/modules/nxos_aaa_server.py b/plugins/modules/nxos_aaa_server.py index dcf71b92e..187fc6adf 100644 --- a/plugins/modules/nxos_aaa_server.py +++ b/plugins/modules/nxos_aaa_server.py @@ -207,7 +207,7 @@ def config_aaa_server(params, server_type): if server_timeout is not None: cmds.append( - "{0}-server timeout {1}".format(server_type, server_timeout) + "{0}-server timeout {1}".format(server_type, server_timeout), ) if directed_request is not None: @@ -219,8 +219,10 @@ def config_aaa_server(params, server_type): if global_key is not None: cmds.append( "{0}-server key {1} {2}".format( - server_type, encrypt_type, global_key - ) + server_type, + encrypt_type, + global_key, + ), ) return cmds @@ -235,29 +237,24 @@ def default_aaa_server(existing, params, server_type): global_key = params.get("global_key") existing_key = existing.get("global_key") - if ( - deadtime is not None - and existing.get("deadtime") != PARAM_TO_DEFAULT_KEYMAP["deadtime"] - ): + if deadtime is not None and existing.get("deadtime") != PARAM_TO_DEFAULT_KEYMAP["deadtime"]: cmds.append("no {0}-server deadtime 1".format(server_type)) if ( server_timeout is not None - and existing.get("server_timeout") - != PARAM_TO_DEFAULT_KEYMAP["server_timeout"] + and existing.get("server_timeout") != PARAM_TO_DEFAULT_KEYMAP["server_timeout"] ): cmds.append("no {0}-server timeout 1".format(server_type)) if ( directed_request is not None - and existing.get("directed_request") - != PARAM_TO_DEFAULT_KEYMAP["directed_request"] + and existing.get("directed_request") != PARAM_TO_DEFAULT_KEYMAP["directed_request"] ): cmds.append("no {0}-server directed-request".format(server_type)) if global_key is not None and existing_key is not None: cmds.append( - "no {0}-server key 7 {1}".format(server_type, existing_key) + "no {0}-server key 7 {1}".format(server_type, existing_key), ) return cmds @@ -266,20 +263,24 @@ def default_aaa_server(existing, params, server_type): def main(): argument_spec = dict( server_type=dict( - type="str", choices=["radius", "tacacs"], required=True + type="str", + choices=["radius", "tacacs"], + required=True, ), global_key=dict(type="str", no_log=True), encrypt_type=dict(type="str", choices=["0", "7"]), deadtime=dict(type="str"), server_timeout=dict(type="str"), directed_request=dict( - type="str", choices=["enabled", "disabled", "default"] + type="str", + choices=["enabled", "disabled", "default"], ), state=dict(choices=["default", "present"], default="present"), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -317,7 +318,7 @@ def main(): raise ValueError except ValueError: module.fail_json( - msg="deadtime must be an integer between 0 and 1440" + msg="deadtime must be an integer between 0 and 1440", ) if server_timeout: @@ -326,7 +327,7 @@ def main(): raise ValueError except ValueError: module.fail_json( - msg="server_timeout must be an integer between 1 and 60" + msg="server_timeout must be an integer between 1 and 60", ) delta = dict(set(proposed.items()).difference(existing.items())) @@ -339,8 +340,7 @@ def main(): for key, value in proposed.items(): if key != "server_type" and value != "default": module.fail_json( - msg='Parameters must be set to "default"' - "when state=default" + msg='Parameters must be set to "default"' "when state=default", ) command = default_aaa_server(existing, proposed, server_type) if command: diff --git a/plugins/modules/nxos_aaa_server_host.py b/plugins/modules/nxos_aaa_server_host.py index 158fb47e8..9a7ab143d 100644 --- a/plugins/modules/nxos_aaa_server_host.py +++ b/plugins/modules/nxos_aaa_server_host.py @@ -198,19 +198,23 @@ def get_aaa_host_info(module, server_type, address): aaa_host_info["key"] = match.group(1) if aaa_host_info["key"]: aaa_host_info["key"] = aaa_host_info["key"].replace( - '"', "" + '"', + "", ) aaa_host_info["encrypt_type"] = "7" aaa_host_info["auth_port"] = match.group(2) aaa_host_info["acct_port"] = match.group(3) aaa_host_info["host_timeout"] = match.group(4) elif "tacacs" in body: - pattern = r"\S+ host \S+(?:\s+key 7\s+(\S+))?(?:\s+port (\d+))?(?:\s+timeout (\d+))?" + pattern = ( + r"\S+ host \S+(?:\s+key 7\s+(\S+))?(?:\s+port (\d+))?(?:\s+timeout (\d+))?" + ) match = re.search(pattern, body) aaa_host_info["key"] = match.group(1) if aaa_host_info["key"]: aaa_host_info["key"] = aaa_host_info["key"].replace( - '"', "" + '"', + "", ) aaa_host_info["encrypt_type"] = "7" aaa_host_info["tacacs_port"] = match.group(2) @@ -282,7 +286,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -316,13 +321,12 @@ def main(): if tacacs_port and server_type != "tacacs": module.fail_json( - msg="tacacs_port can only be used with server_type=tacacs" + msg="tacacs_port can only be used with server_type=tacacs", ) if (auth_port or acct_port) and server_type != "radius": module.fail_json( - msg="auth_port and acct_port can only be used" - "when server_type=radius", + msg="auth_port and acct_port can only be used" "when server_type=radius", ) existing = get_aaa_host_info(module, server_type, address) diff --git a/plugins/modules/nxos_acls.py b/plugins/modules/nxos_acls.py index 4bd5657b2..8c68c5d3c 100644 --- a/plugins/modules/nxos_acls.py +++ b/plugins/modules/nxos_acls.py @@ -1402,9 +1402,7 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.acls.acls import ( AclsArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acls.acls import ( - Acls, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acls.acls import Acls def main(): @@ -1414,7 +1412,8 @@ def main(): :returns: the result form module invocation """ module = AnsibleModule( - argument_spec=AclsArgs.argument_spec, supports_check_mode=True + argument_spec=AclsArgs.argument_spec, + supports_check_mode=True, ) result = Acls(module).execute_module() diff --git a/plugins/modules/nxos_banner.py b/plugins/modules/nxos_banner.py index 7fffe8dbe..1a170783a 100644 --- a/plugins/modules/nxos_banner.py +++ b/plugins/modules/nxos_banner.py @@ -219,10 +219,7 @@ def main(): err_str = item["clierror"] else: err_str = item - if ( - "more than 40 lines" in err_str - or "buffer overflowed" in err_str - ): + if "more than 40 lines" in err_str or "buffer overflowed" in err_str: load_config(module, commands) result["changed"] = True diff --git a/plugins/modules/nxos_bfd_global.py b/plugins/modules/nxos_bfd_global.py index 1613e5fe0..4d71d7f40 100644 --- a/plugins/modules/nxos_bfd_global.py +++ b/plugins/modules/nxos_bfd_global.py @@ -308,7 +308,8 @@ def main(): fabricpath_vlan=dict(required=False, type="int"), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_command.py b/plugins/modules/nxos_command.py index 2032816a7..bbc8641f8 100644 --- a/plugins/modules/nxos_command.py +++ b/plugins/modules/nxos_command.py @@ -144,9 +144,7 @@ transform_commands, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( - run_commands, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands def parse_commands(module, warnings): @@ -183,7 +181,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -226,7 +225,7 @@ def main(): module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update( - {"stdout": responses, "stdout_lines": list(to_lines(responses))} + {"stdout": responses, "stdout_lines": list(to_lines(responses))}, ) module.exit_json(**result) diff --git a/plugins/modules/nxos_config.py b/plugins/modules/nxos_config.py index 71e021781..c3b24202b 100644 --- a/plugins/modules/nxos_config.py +++ b/plugins/modules/nxos_config.py @@ -330,9 +330,7 @@ NetworkConfig, dumps, ) -from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( - to_list, -) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( get_config, @@ -403,7 +401,8 @@ def main(): before=dict(type="list", elements="str"), after=dict(type="list", elements="str"), match=dict( - default="line", choices=["line", "strict", "exact", "none"] + default="line", + choices=["line", "strict", "exact", "none"], ), replace=dict(default="line", choices=["line", "block", "config"]), running_config=dict(aliases=["config"]), @@ -451,12 +450,10 @@ def main(): if replace_src: if module.params["replace"] != "config": module.fail_json( - msg="replace: config is required with replace_src" + msg="replace: config is required with replace_src", ) - if module.params["backup"] or ( - module._diff and module.params["diff_against"] == "running" - ): + if module.params["backup"] or (module._diff and module.params["diff_against"] == "running"): contents = get_config(module, flags=flags) config = NetworkConfig(indent=2, contents=contents) if module.params["backup"]: @@ -488,7 +485,7 @@ def main(): ) except ConnectionError as exc: module.fail_json( - msg=to_text(exc, errors="surrogate_then_replace") + msg=to_text(exc, errors="surrogate_then_replace"), ) config_diff = response["config_diff"] @@ -594,7 +591,7 @@ def main(): ) if result.get("changed") and any( - (module.params["src"], module.params["lines"]) + (module.params["src"], module.params["lines"]), ): msg = ( "To ensure idempotency and correct diff the input configuration lines should be" diff --git a/plugins/modules/nxos_devicealias.py b/plugins/modules/nxos_devicealias.py index 3c74da6b7..f79feb3bb 100644 --- a/plugins/modules/nxos_devicealias.py +++ b/plugins/modules/nxos_devicealias.py @@ -268,7 +268,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -304,7 +305,7 @@ def main(): + ". Note that name cannot be more than 64 alphanumeric chars, " + "it must start with a letter, and can only contain these characters: " + ", ".join( - ["'{0}'".format(c) for c in VALID_DA_CHARS] + ["'{0}'".format(c) for c in VALID_DA_CHARS], ), ) if not isPwwnValid(pwwn): @@ -392,7 +393,7 @@ def main(): # but switch mode is enhanced, so set it to basic commands.append("no device-alias mode enhanced") messages.append( - "device-alias mode changed from enhanced to basic" + "device-alias mode changed from enhanced to basic", ) else: messages.append( @@ -405,7 +406,7 @@ def main(): # but switch mode is basic, so set it to enhanced commands.append("device-alias mode enhanced") messages.append( - "device-alias mode changed from basic to enhanced" + "device-alias mode changed from basic to enhanced", ) else: messages.append( @@ -415,15 +416,11 @@ def main(): if commands: if distribute: commands.append("device-alias commit") - commands = ( - ["terminal dont-ask"] + commands + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] else: if distribute is None and d == "enabled": commands.append("device-alias commit") - commands = ( - ["terminal dont-ask"] + commands + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) @@ -484,7 +481,7 @@ def main(): else: commands.append( - "device-alias name " + name + " pwwn " + pwwn + "device-alias name " + name + " pwwn " + pwwn, ) da_add_list.append(name) @@ -492,17 +489,11 @@ def main(): commands = ["device-alias database"] + commands if distribute: commands.append("device-alias commit") - commands = ( - ["terminal dont-ask"] + commands + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] else: if distribute is None and d == "enabled": commands.append("device-alias commit") - commands = ( - ["terminal dont-ask"] - + commands - + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) if cmds: @@ -515,13 +506,11 @@ def main(): load_config(module, cmds) if len(da_remove_list) != 0: messages.append( - "the required device-alias were removed. " - + ",".join(da_remove_list), + "the required device-alias were removed. " + ",".join(da_remove_list), ) if len(da_add_list) != 0: messages.append( - "the required device-alias were added. " - + ",".join(da_add_list), + "the required device-alias were added. " + ",".join(da_add_list), ) # Step 5: Process rename @@ -541,7 +530,7 @@ def main(): ) if shDADatabaseObj.isNameInDaDatabase(oldname): commands.append( - "device-alias rename " + oldname + " " + newname + "device-alias rename " + oldname + " " + newname, ) else: module.fail_json( @@ -555,17 +544,11 @@ def main(): commands = ["device-alias database"] + commands if distribute: commands.append("device-alias commit") - commands = ( - ["terminal dont-ask"] + commands + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] else: if distribute is None and d == "enabled": commands.append("device-alias commit") - commands = ( - ["terminal dont-ask"] - + commands - + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) if cmds: commands_to_execute = commands_to_execute + cmds diff --git a/plugins/modules/nxos_evpn_global.py b/plugins/modules/nxos_evpn_global.py index 383658e02..7ad7894e1 100644 --- a/plugins/modules/nxos_evpn_global.py +++ b/plugins/modules/nxos_evpn_global.py @@ -67,7 +67,8 @@ def main(): argument_spec = dict(nv_overlay_evpn=dict(required=True, type="bool")) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) result = {"changed": False} @@ -84,7 +85,7 @@ def main(): if "3K" in os_platform: module.fail_json( - msg="This module is not supported on Nexus 3000 series" + msg="This module is not supported on Nexus 3000 series", ) if module.params["nv_overlay_evpn"] is True: diff --git a/plugins/modules/nxos_evpn_vni.py b/plugins/modules/nxos_evpn_vni.py index 4ada03d17..e99b07e61 100644 --- a/plugins/modules/nxos_evpn_vni.py +++ b/plugins/modules/nxos_evpn_vni.py @@ -224,7 +224,7 @@ def state_present(module, existing, proposed): if existing.get(key.replace("-", "_").replace(" ", "_")): for exi in existing.get( - key.replace("-", "_").replace(" ", "_") + key.replace("-", "_").replace(" ", "_"), ): if exi not in value: commands.append("no {0} {1}".format(key, exi)) @@ -257,12 +257,15 @@ def main(): route_target_import=dict(required=False, type="list", elements="str"), route_target_export=dict(required=False, type="list", elements="str"), state=dict( - choices=["present", "absent"], default="present", required=False + choices=["present", "absent"], + default="present", + required=False, ), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -271,9 +274,7 @@ def main(): state = module.params["state"] args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) - proposed_args = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) commands = [] parents = [] diff --git a/plugins/modules/nxos_facts.py b/plugins/modules/nxos_facts.py index f506f5bf5..ad3ff1f00 100644 --- a/plugins/modules/nxos_facts.py +++ b/plugins/modules/nxos_facts.py @@ -219,9 +219,7 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.facts.facts import ( FactsArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import ( - Facts, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.facts import Facts def get_chassis_type(connection): @@ -249,7 +247,8 @@ def main(): argument_spec = FactsArgs.argument_spec module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) connection = Connection(module._socket_path) facts = Facts(module, chassis_type=get_chassis_type(connection)) @@ -259,7 +258,7 @@ def main(): ansible_facts = {} if module.params.get("available_network_resources"): ansible_facts["available_network_resources"] = sorted( - facts.get_resource_subsets().keys() + facts.get_resource_subsets().keys(), ) result = facts.get_facts() diff --git a/plugins/modules/nxos_feature.py b/plugins/modules/nxos_feature.py index aa58aaee2..d8903e62f 100644 --- a/plugins/modules/nxos_feature.py +++ b/plugins/modules/nxos_feature.py @@ -117,10 +117,7 @@ def get_available_features(feature, module): if feature not in available_features: available_features[feature] = state else: - if ( - available_features[feature] == "disabled" - and state == "enabled" - ): + if available_features[feature] == "disabled" and state == "enabled": available_features[feature] = state # certain configurable features do not @@ -272,7 +269,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_file_copy.py b/plugins/modules/nxos_file_copy.py index 23b3a25a8..7ed45e914 100644 --- a/plugins/modules/nxos_file_copy.py +++ b/plugins/modules/nxos_file_copy.py @@ -253,7 +253,8 @@ def md5sum_check(self, dst, file_system): command = "show file {0}{1} md5sum".format(file_system, dst) remote_filehash = self._connection.run_commands(command)[0] remote_filehash = to_bytes( - remote_filehash, errors="surrogate_or_strict" + remote_filehash, + errors="surrogate_or_strict", ) local_file = self._module.params["local_file"] @@ -262,7 +263,7 @@ def md5sum_check(self, dst, file_system): filecontent = f.read() except (OSError, IOError) as exc: self._module.fail_json( - "Error reading the file: {0}".format(to_text(exc)) + "Error reading the file: {0}".format(to_text(exc)), ) filecontent = to_bytes(filecontent, errors="surrogate_or_strict") @@ -296,13 +297,13 @@ def get_flash_size(self, file_system): match = re.search(r"No such file or directory", body) if match: self._module.fail_json( - "Invalid nxos filesystem {0}".format(file_system) + "Invalid nxos filesystem {0}".format(file_system), ) else: self._module.fail_json( "Unable to determine size of filesystem {0}".format( - file_system - ) + file_system, + ), ) def enough_space(self, file, file_system): @@ -319,7 +320,7 @@ def transfer_file_to_device(self, remote_file): if not self.enough_space(local_file, file_system): self._module.fail_json( - "Could not transfer file. Not enough space on device." + "Could not transfer file. Not enough space on device.", ) # frp = full_remote_path, flp = full_local_path @@ -334,12 +335,10 @@ def transfer_file_to_device(self, remote_file): destination=frp, proto="scp", timeout=self._connection.get_option( - "persistent_command_timeout" + "persistent_command_timeout", ), ) - self.result[ - "transfer_status" - ] = "Sent: File copied to remote device." + self.result["transfer_status"] = "Sent: File copied to remote device." except Exception as exc: self.result["failed"] = True self.result["msg"] = "Exception received : %s" % exc @@ -347,13 +346,13 @@ def transfer_file_to_device(self, remote_file): def run(self): local_file = self._module.params["local_file"] remote_file = self._module.params["remote_file"] or os.path.basename( - local_file + local_file, ) file_system = self._module.params["file_system"] if not os.path.isfile(local_file): self._module.fail_json( - "Local file {0} not found".format(local_file) + "Local file {0} not found".format(local_file), ) remote_file = remote_file or os.path.basename(local_file) @@ -363,9 +362,7 @@ def run(self): self.result["changed"] = True file_exists = False else: - self.result[ - "transfer_status" - ] = "No Transfer: File already copied to remote device." + self.result["transfer_status"] = "No Transfer: File already copied to remote device." file_exists = True if not self._module.check_mode and not file_exists: @@ -439,7 +436,8 @@ def copy_file_from_remote(self, local, local_file_directory, file_system): self.result["copy_cmd"] = copy_cmd pulled = self._connection.pull_file( - command=copy_cmd, remotepassword=rserverpassword + command=copy_cmd, + remotepassword=rserverpassword, ) if pulled: self.result[ @@ -451,9 +449,7 @@ def copy_file_from_remote(self, local, local_file_directory, file_system): def run(self): self.result["failed"] = False remote_file = self._module.params["remote_file"] - local_file = ( - self._module.params["local_file"] or remote_file.split("/")[-1] - ) + local_file = self._module.params["local_file"] or remote_file.split("/")[-1] file_system = self._module.params["file_system"] # Note: This is the local file directory on the remote nxos device. local_file_dir = self._module.params["local_file_directory"] @@ -467,9 +463,7 @@ def run(self): else: dir = "" self.result["local_file"] = file_system + dir + "/" + local_file - self.result["remote_scp_server"] = self._module.params[ - "remote_scp_server" - ] + self.result["remote_scp_server"] = self._module.params["remote_scp_server"] self.result["file_system"] = self._module.params["file_system"] if not self.result["failed"]: @@ -503,7 +497,7 @@ def main(): module = AnsibleModule( argument_spec=argument_spec, required_if=[ - ("file_pull", True, ("remote_file", "remote_scp_server")) + ("file_pull", True, ("remote_file", "remote_scp_server")), ], required_together=[("remote_scp_server", "remote_scp_server_user")], supports_check_mode=True, diff --git a/plugins/modules/nxos_gir.py b/plugins/modules/nxos_gir.py index 1a35b7c69..61da83673 100644 --- a/plugins/modules/nxos_gir.py +++ b/plugins/modules/nxos_gir.py @@ -203,15 +203,11 @@ def get_commands(module, state, mode): commands = list() if module.params["system_mode_maintenance"] is True and mode == "normal": commands.append("system mode maintenance") - elif ( - module.params["system_mode_maintenance"] is False - and mode == "maintenance" - ): + elif module.params["system_mode_maintenance"] is False and mode == "maintenance": commands.append("no system mode maintenance") elif ( - module.params["system_mode_maintenance_dont_generate_profile"] is True - and mode == "normal" + module.params["system_mode_maintenance_dont_generate_profile"] is True and mode == "normal" ): commands.append("system mode maintenance dont-generate-profile") elif ( @@ -222,65 +218,46 @@ def get_commands(module, state, mode): elif module.params["system_mode_maintenance_timeout"]: timeout = get_maintenance_timeout(module) - if ( - state == "present" - and timeout != module.params["system_mode_maintenance_timeout"] - ): + if state == "present" and timeout != module.params["system_mode_maintenance_timeout"]: commands.append( "system mode maintenance timeout {0}".format( module.params["system_mode_maintenance_timeout"], ), ) - elif ( - state == "absent" - and timeout == module.params["system_mode_maintenance_timeout"] - ): + elif state == "absent" and timeout == module.params["system_mode_maintenance_timeout"]: commands.append( "no system mode maintenance timeout {0}".format( module.params["system_mode_maintenance_timeout"], ), ) - elif ( - module.params["system_mode_maintenance_shutdown"] and mode == "normal" - ): + elif module.params["system_mode_maintenance_shutdown"] and mode == "normal": commands.append("system mode maintenance shutdown") - elif ( - module.params["system_mode_maintenance_shutdown"] is False - and mode == "maintenance" - ): + elif module.params["system_mode_maintenance_shutdown"] is False and mode == "maintenance": commands.append("no system mode maintenance") elif module.params["system_mode_maintenance_on_reload_reset_reason"]: reset_reasons = get_reset_reasons(module) if ( state == "present" - and module.params[ - "system_mode_maintenance_on_reload_reset_reason" - ].lower() + and module.params["system_mode_maintenance_on_reload_reset_reason"].lower() not in reset_reasons.lower() ): commands.append( "system mode maintenance on-reload " "reset-reason {0}".format( - module.params[ - "system_mode_maintenance_on_reload_reset_reason" - ], + module.params["system_mode_maintenance_on_reload_reset_reason"], ), ) elif ( state == "absent" - and module.params[ - "system_mode_maintenance_on_reload_reset_reason" - ].lower() + and module.params["system_mode_maintenance_on_reload_reset_reason"].lower() in reset_reasons.lower() ): commands.append( "no system mode maintenance on-reload " "reset-reason {0}".format( - module.params[ - "system_mode_maintenance_on_reload_reset_reason" - ], + module.params["system_mode_maintenance_on_reload_reset_reason"], ), ) @@ -293,7 +270,8 @@ def main(): argument_spec = dict( system_mode_maintenance=dict(required=False, type="bool"), system_mode_maintenance_dont_generate_profile=dict( - required=False, type="bool" + required=False, + type="bool", ), system_mode_maintenance_timeout=dict(required=False, type="str"), system_mode_maintenance_shutdown=dict(required=False, type="bool"), @@ -313,7 +291,9 @@ def main(): ], ), state=dict( - choices=["absent", "present"], default="present", required=False + choices=["absent", "present"], + default="present", + required=False, ), ) diff --git a/plugins/modules/nxos_gir_profile_management.py b/plugins/modules/nxos_gir_profile_management.py index 5b42ad844..4cf651e8e 100644 --- a/plugins/modules/nxos_gir_profile_management.py +++ b/plugins/modules/nxos_gir_profile_management.py @@ -171,7 +171,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_hsrp.py b/plugins/modules/nxos_hsrp.py index 7427d5d1d..25c56d608 100644 --- a/plugins/modules/nxos_hsrp.py +++ b/plugins/modules/nxos_hsrp.py @@ -216,7 +216,9 @@ def get_hsrp_group(group, interface, module): del hsrp_key["sh_keystring_attr"] if "unknown enum:" in str(hsrp_table): hsrp_table = get_hsrp_group_unknown_enum( - module, command, hsrp_table + module, + command, + hsrp_table, ) except (AttributeError, IndexError, TypeError, KeyError): return {} @@ -255,9 +257,7 @@ def get_hsrp_group_unknown_enum(module, command, hsrp_table): if "unknown enum:" in hsrp_table["sh_preempt"]: cmd = {"output": "text", "command": command.split("|")[0]} out = run_commands(module, cmd)[0] - hsrp_table["sh_preempt"] = ( - "enabled" if ("may preempt" in out) else "disabled" - ) + hsrp_table["sh_preempt"] = "enabled" if ("may preempt" in out) else "disabled" return hsrp_table @@ -290,7 +290,7 @@ def get_commands_config_hsrp(delta, interface, args, existing): if priority: if priority == "default": if existing and existing.get( - "priority" + "priority", ) != PARAM_TO_DEFAULT_KEYMAP.get("priority"): delta["priority"] = "no priority" else: @@ -301,7 +301,7 @@ def get_commands_config_hsrp(delta, interface, args, existing): if vip: if vip == "default": if existing and existing.get("vip") != PARAM_TO_DEFAULT_KEYMAP.get( - "vip" + "vip", ): delta["vip"] = "no ip" else: @@ -329,7 +329,8 @@ def get_commands_config_hsrp(delta, interface, args, existing): if auth_string != "default": if auth_type == "md5": command = "authentication md5 key-string {0} {1}".format( - auth_enc, auth_string + auth_enc, + auth_string, ) commands.append(command) elif auth_type == "text": @@ -337,7 +338,7 @@ def get_commands_config_hsrp(delta, interface, args, existing): commands.append(command) else: if existing and existing.get( - "auth_string" + "auth_string", ) != PARAM_TO_DEFAULT_KEYMAP.get( "auth_string", ): @@ -383,7 +384,8 @@ def validate_config(body, vip, module): new_body = "".join(body) if "invalid ip address" in new_body.lower(): module.fail_json( - msg="Invalid VIP. Possible duplicate IP address.", vip=vip + msg="Invalid VIP. Possible duplicate IP address.", + vip=vip, ) @@ -394,18 +396,23 @@ def main(): version=dict(choices=["1", "2"], default="1", required=False), priority=dict(type="str", required=False), preempt=dict( - type="str", choices=["disabled", "enabled"], required=False + type="str", + choices=["disabled", "enabled"], + required=False, ), vip=dict(type="str", required=False), auth_type=dict(choices=["text", "md5"], required=False), auth_string=dict(type="str", required=False), state=dict( - choices=["absent", "present"], required=False, default="present" + choices=["absent", "present"], + required=False, + default="present", ), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -453,16 +460,14 @@ def main(): mode = get_interface_mode(interface, intf_type, module) if mode == "layer2": module.fail_json( - msg="That interface is a layer2 port.\nMake it " - "a layer 3 port first.", + msg="That interface is a layer2 port.\nMake it " "a layer 3 port first.", interface=interface, ) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json( - msg="When using auth parameters, you need BOTH " - "auth_type AND auth_string.", + msg="When using auth parameters, you need BOTH " "auth_type AND auth_string.", ) args = dict( @@ -484,16 +489,13 @@ def main(): if proposed.get("auth_type", None) == "md5": if proposed["version"] == "1": module.fail_json( - msg="It's recommended to use HSRP v2 " "when auth_type=md5" + msg="It's recommended to use HSRP v2 " "when auth_type=md5", ) elif not proposed.get("auth_type", None) and existing: - if ( - proposed["version"] == "1" and existing["auth_type"] == "md5" - ) and state == "present": + if (proposed["version"] == "1" and existing["auth_type"] == "md5") and state == "present": module.fail_json( - msg="Existing auth_type is md5. It's recommended " - "to use HSRP v2 when using md5", + msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5", ) commands = [] @@ -501,7 +503,10 @@ def main(): delta = dict(set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_hsrp( - delta, interface, args, existing + delta, + interface, + args, + existing, ) commands.extend(command) diff --git a/plugins/modules/nxos_igmp.py b/plugins/modules/nxos_igmp.py index 64ca218b2..f2cbe15a6 100644 --- a/plugins/modules/nxos_igmp.py +++ b/plugins/modules/nxos_igmp.py @@ -95,7 +95,8 @@ def get_current(module): output = run_commands( - module, {"command": "show running-config", "output": "text"} + module, + {"command": "show running-config", "output": "text"}, ) return { "flush_routes": "ip igmp flush-routes" in output[0], @@ -119,7 +120,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_igmp_interface.py b/plugins/modules/nxos_igmp_interface.py index 8d6763f1e..68b5f8712 100644 --- a/plugins/modules/nxos_igmp_interface.py +++ b/plugins/modules/nxos_igmp_interface.py @@ -279,7 +279,7 @@ def get_igmp_interface(module, interface): igmp["report_llg"] = False immediate_leave = str( - resource["ImmediateLeave"] + resource["ImmediateLeave"], ).lower() # returns en or dis if re.search(r"^en|^true|^enabled", immediate_leave): igmp["immediate_leave"] = True @@ -292,15 +292,15 @@ def get_igmp_interface(module, interface): command = "show run interface {0} | inc oif".format(interface) body = execute_show_command( - command, module, command_type="cli_show_ascii" + command, + module, + command_type="cli_show_ascii", )[0] staticoif = [] if body: split_body = body.split("\n") - route_map_regex = ( - r".*ip igmp static-oif route-map\s+(?P\S+).*" - ) + route_map_regex = r".*ip igmp static-oif route-map\s+(?P\S+).*" prefix_source_regex = ( r".*ip igmp static-oif\s+(?P" r"((\d+.){3}\d+))(\ssource\s" @@ -317,7 +317,9 @@ def get_igmp_interface(module, interface): try: match_prefix_source = re.match( - prefix_source_regex, line, re.DOTALL + prefix_source_regex, + line, + re.DOTALL, ) prefix_source_group = match_prefix_source.groupdict() prefix = prefix_source_group["prefix"] @@ -383,7 +385,7 @@ def config_igmp_interface(delta, existing, existing_oif_prefix_source): src = each["source"] if src: commands.append( - CMDS.get("oif_prefix_source").format(pf, src) + CMDS.get("oif_prefix_source").format(pf, src), ) else: commands.append(CMDS.get("oif_prefix").format(pf)) @@ -396,12 +398,11 @@ def config_igmp_interface(delta, existing, existing_oif_prefix_source): src = each["source"] if src: commands.append( - "no " - + CMDS.get("oif_prefix_source").format(pf, src), + "no " + CMDS.get("oif_prefix_source").format(pf, src), ) else: commands.append( - "no " + CMDS.get("oif_prefix").format(pf) + "no " + CMDS.get("oif_prefix").format(pf), ) elif key == "oif_routemap": if value == "default": @@ -455,9 +456,7 @@ def get_igmp_interface_defaults(): immediate_leave=immediate_leave, ) - default = dict( - (param, value) for (param, value) in args.items() if value is not None - ) + default = dict((param, value) for (param, value) in args.items() if value is not None) return default @@ -486,7 +485,7 @@ def config_remove_oif(existing, existing_oif_prefix_source): if existing.get("oif_routemap"): commands.append( "no ip igmp static-oif route-map {0}".format( - existing.get("oif_routemap") + existing.get("oif_routemap"), ), ) elif existing_oif_prefix_source: @@ -498,7 +497,7 @@ def config_remove_oif(existing, existing_oif_prefix_source): ) elif each.get("prefix"): command = "no ip igmp static-oif {0}".format( - each.get("prefix") + each.get("prefix"), ) if command: commands.append(command) @@ -511,7 +510,9 @@ def main(): argument_spec = dict( interface=dict(required=True, type="str"), version=dict( - required=False, type="str", choices=["2", "3", "default"] + required=False, + type="str", + choices=["2", "3", "default"], ), startup_query_interval=dict(required=False, type="str"), startup_query_count=dict(required=False, type="str"), @@ -528,7 +529,8 @@ def main(): oif_ps=dict(required=False, type="raw"), restart=dict(type="bool", default=False), state=dict( - choices=["present", "absent", "default"], default="present" + choices=["present", "absent", "default"], + default="present", ), ) @@ -593,9 +595,7 @@ def main(): changed = False commands = [] - proposed = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) CANNOT_ABSENT = [ "version", @@ -616,9 +616,7 @@ def main(): for each in CANNOT_ABSENT: if each in proposed: module.fail_json( - msg="only params: " - "oif_ps, oif_routemap can be used when " - "state=absent", + msg="only params: " "oif_ps, oif_routemap can be used when " "state=absent", ) # delta check for all params except oif_ps @@ -633,7 +631,9 @@ def main(): if state == "present": if delta: command = config_igmp_interface( - delta, existing, existing_oif_prefix_source + delta, + existing, + existing_oif_prefix_source, ) if command: commands.append(command) diff --git a/plugins/modules/nxos_igmp_snooping.py b/plugins/modules/nxos_igmp_snooping.py index d0c27a640..e5b26c77a 100644 --- a/plugins/modules/nxos_igmp_snooping.py +++ b/plugins/modules/nxos_igmp_snooping.py @@ -161,7 +161,7 @@ def get_igmp_snooping(module): link_local_grp_supp = str(body.get("glinklocalgrpsup")).lower() if "none" in link_local_grp_supp: link_local_grp_supp = str( - body.get("GlobalLinkLocalGroupSupression") + body.get("GlobalLinkLocalGroupSupression"), ).lower() if link_local_grp_supp == "true" or link_local_grp_supp == "enabled": existing["link_local_grp_supp"] = True @@ -201,7 +201,7 @@ def config_igmp_snooping(delta, existing, default=False): if default and key == "group_timeout": if existing.get(key): gt_command = "no " + CMDS.get(key).format( - existing.get(key) + existing.get(key), ) elif value == "default" and key == "group_timeout": if existing.get(key): @@ -236,9 +236,7 @@ def get_igmp_snooping_defaults(): group_timeout=group_timeout, ) - default = dict( - (param, value) for (param, value) in args.items() if value is not None - ) + default = dict((param, value) for (param, value) in args.items() if value is not None) return default @@ -269,7 +267,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -290,9 +289,7 @@ def main(): group_timeout=group_timeout, ) - proposed = dict( - (param, value) for (param, value) in args.items() if value is not None - ) + proposed = dict((param, value) for (param, value) in args.items() if value is not None) existing = get_igmp_snooping(module) diff --git a/plugins/modules/nxos_install_os.py b/plugins/modules/nxos_install_os.py index ecba9df36..df96c27f4 100644 --- a/plugins/modules/nxos_install_os.py +++ b/plugins/modules/nxos_install_os.py @@ -431,10 +431,7 @@ def check_mode_legacy(module, issu, image, kick=None): if target_image["error"]: data["error"] = True data["raw"] = target_image["raw"] - if ( - current["kickstart_ver_str"] != target_image["version"] - and not data["error"] - ): + if current["kickstart_ver_str"] != target_image["version"] and not data["error"]: data["upgrade_needed"] = True data["disruptive"] = True upgrade_msg = "Switch upgraded: system: %s" % tsver @@ -447,10 +444,7 @@ def check_mode_legacy(module, issu, image, kick=None): if target_kick["error"]: data["error"] = True data["raw"] = target_kick["raw"] - if ( - current["kickstart_ver_str"] != target_kick["version"] - and not data["error"] - ): + if current["kickstart_ver_str"] != target_kick["version"] and not data["error"]: data["upgrade_needed"] = True data["disruptive"] = True upgrade_msg = upgrade_msg + " kickstart: %s" % tkver @@ -541,7 +535,11 @@ def do_install_all(module, issu, image, kick=None): # Not all platforms support the 'force' keyword. Check for this # condition and re-try without the 'force' keyword if needed. commands = build_install_cmd_set( - issu, image, kick, "install", False + issu, + image, + kick, + "install", + False, ) upgrade = check_install_in_progress(module, commands, opts) upgrade["upgrade_cmd"] = commands @@ -575,7 +573,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_lacp.py b/plugins/modules/nxos_lacp.py index 197853f61..257c1384e 100644 --- a/plugins/modules/nxos_lacp.py +++ b/plugins/modules/nxos_lacp.py @@ -246,9 +246,7 @@ from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.argspec.lacp.lacp import ( LacpArgs, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.lacp.lacp import ( - Lacp, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.lacp.lacp import Lacp def main(): diff --git a/plugins/modules/nxos_logging.py b/plugins/modules/nxos_logging.py index 8ed8f13c6..dfdc821f4 100644 --- a/plugins/modules/nxos_logging.py +++ b/plugins/modules/nxos_logging.py @@ -266,12 +266,12 @@ def map_obj_to_commands(module, updates): if ( not w["dest"] and not w["facility_link_status"] - and w["facility"] - not in DEFAULT_LOGGING_LEVEL[int(w["facility_level"])] + and w["facility"] not in DEFAULT_LOGGING_LEVEL[int(w["facility_level"])] ): commands.append( "no logging level {0} {1}".format( - w["facility"], w["facility_level"] + w["facility"], + w["facility_level"], ), ) @@ -291,7 +291,7 @@ def map_obj_to_commands(module, updates): if w["dest"] == "server": commands.append( - "no logging server {0}".format(w["remote_server"]) + "no logging server {0}".format(w["remote_server"]), ) if w["interface"]: @@ -312,8 +312,9 @@ def map_obj_to_commands(module, updates): if w["dest"] not in ("logfile", "server"): commands.append( "logging {0} {1}".format( - w["dest"], w["dest_level"] - ) + w["dest"], + w["dest_level"], + ), ) elif w["dest"] == "logfile": @@ -328,7 +329,8 @@ def map_obj_to_commands(module, updates): else: commands.append( "logging logfile {0} {1}".format( - w["name"], w["dest_level"] + w["name"], + w["dest_level"], ), ) @@ -361,8 +363,8 @@ def map_obj_to_commands(module, updates): else: commands.append( "logging server {0}".format( - w["remote_server"] - ) + w["remote_server"], + ), ) if w["facility"]: @@ -411,18 +413,21 @@ def map_obj_to_commands(module, updates): ) else: if not match_facility_default( - module, w["facility"], w["facility_level"] + module, + w["facility"], + w["facility_level"], ): commands.append( "logging level {0} {1}".format( - w["facility"], w["facility_level"] + w["facility"], + w["facility_level"], ), ) if w["interface"]: commands.append( "logging source-interface {0} {1}".format( - *split_interface(w["interface"]) + *split_interface(w["interface"]), ), ) @@ -459,11 +464,7 @@ def match_facility_default(module, facility, want_level): facility_data = run_commands(module, cmd) for line in facility_data[0].split("\n"): mo = re.search(regexl, line) - if ( - mo - and int(mo.group(1)) == int(want_level) - and int(mo.group(2)) == int(want_level) - ): + if mo and int(mo.group(1)) == int(want_level) and int(mo.group(2)) == int(want_level): matches_default = True return matches_default @@ -480,7 +481,9 @@ def parse_facility_link_status(line, facility, status): if facility is not None: match = re.search( - r"logging level {0} {1} (\S+)".format(facility, status), line, re.M + r"logging level {0} {1} (\S+)".format(facility, status), + line, + re.M, ) if match: facility_link_status = status + "-" + match.group(1) @@ -492,7 +495,9 @@ def parse_event_status(line, event): status = None match = re.search( - r"logging event {0} (\S+)".format(event + "-status"), line, re.M + r"logging event {0} (\S+)".format(event + "-status"), + line, + re.M, ) if match: state = match.group(1) @@ -520,7 +525,9 @@ def parse_message(line): message = None match = re.search( - r"logging message interface type ethernet description", line, re.M + r"logging message interface type ethernet description", + line, + re.M, ) if match: message = "add-interface-description" @@ -532,7 +539,9 @@ def parse_file_size(line, name, level): file_size = None match = re.search( - r"logging logfile {0} {1} size (\S+)".format(name, level), line, re.M + r"logging logfile {0} {1} size (\S+)".format(name, level), + line, + re.M, ) if match: file_size = match.group(1) @@ -592,7 +601,9 @@ def parse_match(match): if dest and dest != "server": if dest == "logfile": match = re.search( - r"logging logfile {0} (\S+)".format(name), line, re.M + r"logging logfile {0} (\S+)".format(name), + line, + re.M, ) if match: dest_level = parse_match(match) @@ -619,7 +630,9 @@ def parse_facility_level(line, facility, dest): elif facility is not None: match = re.search( - r"logging level {0} (\S+)".format(facility), line, re.M + r"logging level {0} (\S+)".format(facility), + line, + re.M, ) if match: facility_level = match.group(1) @@ -646,7 +659,9 @@ def parse_use_vrf(line, dest): if dest and dest == "server": match = re.search( - r"logging server (?:\S+) (?:\d+) use-vrf (\S+)", line, re.M + r"logging server (?:\S+) (?:\d+) use-vrf (\S+)", + line, + re.M, ) if match: use_vrf = match.group(1) @@ -711,7 +726,9 @@ def map_config_to_obj(module): facility_level = level else: facility_link_status = parse_facility_link_status( - line, facility, level + line, + facility, + level, ) elif match.group(1) == "event" and state == "present": @@ -768,10 +785,7 @@ def map_config_to_obj(module): if match.group(1) == "console" and match.group(2) == "critical": dest_level = "2" flag = True - elif ( - match.group(1) == "monitor" - and match.group(2) == "notifications" - ): + elif match.group(1) == "monitor" and match.group(2) == "notifications": dest_level = "5" flag = True if flag: @@ -971,7 +985,8 @@ def main(): if module.params.get("purge"): pcommands = map_obj_to_commands( - module, (outliers(have, merged_wants), have) + module, + (outliers(have, merged_wants), have), ) if pcommands: if not module.check_mode: diff --git a/plugins/modules/nxos_ntp.py b/plugins/modules/nxos_ntp.py index f1d596a55..99bd59440 100644 --- a/plugins/modules/nxos_ntp.py +++ b/plugins/modules/nxos_ntp.py @@ -151,7 +151,9 @@ def get_ntp_source(module): source = None command = "show run | inc ntp.source" output = execute_show_command( - command, module, command_type="cli_show_ascii" + command, + module, + command_type="cli_show_ascii", ) if output: @@ -172,7 +174,9 @@ def get_ntp_peer(module): command = "show run | inc ntp.(server|peer)" ntp_peer_list = [] response = execute_show_command( - command, module, command_type="cli_show_ascii" + command, + module, + command_type="cli_show_ascii", ) if response: @@ -306,25 +310,27 @@ def config_ntp(delta, existing): if existing.get("peer_type") and existing.get("address"): ntp_cmds.append( "no ntp {0} {1}".format( - existing.get("peer_type"), existing.get("address") + existing.get("peer_type"), + existing.get("address"), ), ) ntp_cmds.append( - set_ntp_server_peer(peer_type, address, prefer, key_id, vrf_name) + set_ntp_server_peer(peer_type, address, prefer, key_id, vrf_name), ) if source: existing_source_type = existing.get("source_type") existing_source = existing.get("source") if existing_source_type and source_type != existing_source_type: ntp_cmds.append( - "no ntp {0} {1}".format(existing_source_type, existing_source) + "no ntp {0} {1}".format(existing_source_type, existing_source), ) if source == "default": if existing_source_type and existing_source: ntp_cmds.append( "no ntp {0} {1}".format( - existing_source_type, existing_source - ) + existing_source_type, + existing_source, + ), ) else: ntp_cmds.append("ntp {0} {1}".format(source_type, source)) @@ -418,7 +424,8 @@ def main(): elif state == "absent": if existing.get("peer_type") and existing.get("address"): command = "no ntp {0} {1}".format( - existing["peer_type"], existing["address"] + existing["peer_type"], + existing["address"], ) if command: commands.append([command]) @@ -432,7 +439,8 @@ def main(): if proposed_source_type == existing_source_type: if proposed_source == existing_source: command = "no ntp {0} {1}".format( - existing_source_type, existing_source + existing_source_type, + existing_source, ) if command: commands.append([command]) diff --git a/plugins/modules/nxos_ntp_auth.py b/plugins/modules/nxos_ntp_auth.py index df3f7ee4f..1983f3fe5 100644 --- a/plugins/modules/nxos_ntp_auth.py +++ b/plugins/modules/nxos_ntp_auth.py @@ -165,7 +165,9 @@ def get_ntp_trusted_key(module): def get_ntp_auth_key(key_id, module): authentication_key = {} command = "show run | inc ntp.authentication-key.{0}".format(key_id) - auth_regex = r".*ntp\sauthentication-key\s(?P\d+)\smd5\s(?P\S+)\s(?P\S+).*" + auth_regex = ( + r".*ntp\sauthentication-key\s(?P\d+)\smd5\s(?P\S+)\s(?P\S+).*" + ) body = execute_show_command(command, module)[0] @@ -210,14 +212,20 @@ def auth_type_to_num(auth_type): def set_ntp_auth_key( - key_id, md5string, auth_type, trusted_key, authentication + key_id, + md5string, + auth_type, + trusted_key, + authentication, ): ntp_auth_cmds = [] if key_id and md5string: auth_type_num = auth_type_to_num(auth_type) ntp_auth_cmds.append( "ntp authentication-key {0} md5 {1} {2}".format( - key_id, md5string, auth_type_num + key_id, + md5string, + auth_type_num, ), ) @@ -235,14 +243,20 @@ def set_ntp_auth_key( def remove_ntp_auth_key( - key_id, md5string, auth_type, trusted_key, authentication + key_id, + md5string, + auth_type, + trusted_key, + authentication, ): auth_remove_cmds = [] if key_id: auth_type_num = auth_type_to_num(auth_type) auth_remove_cmds.append( "no ntp authentication-key {0} md5 {1} {2}".format( - key_id, md5string, auth_type_num + key_id, + md5string, + auth_type_num, ), ) @@ -262,7 +276,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -313,7 +328,11 @@ def main(): if not existing.get("key_id"): key_id = None command = remove_ntp_auth_key( - key_id, md5string, auth_type, trusted_key, auth_toggle + key_id, + md5string, + auth_type, + trusted_key, + auth_toggle, ) if command: commands.append(command) diff --git a/plugins/modules/nxos_ntp_options.py b/plugins/modules/nxos_ntp_options.py index 260ebb3ea..ac7f1b407 100644 --- a/plugins/modules/nxos_ntp_options.py +++ b/plugins/modules/nxos_ntp_options.py @@ -119,7 +119,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_nxapi.py b/plugins/modules/nxos_nxapi.py index 6bac79609..0c841b12a 100644 --- a/plugins/modules/nxos_nxapi.py +++ b/plugins/modules/nxos_nxapi.py @@ -165,9 +165,7 @@ load_config, run_commands, ) -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import ( - Version, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.utils.utils import Version def check_args(module, warnings, capabilities): @@ -253,14 +251,12 @@ def needs_update(x): if os_platform and os_version: if (os_platform == "N9K" or os_platform == "N3K") and Version( - os_version + os_version, ) >= "9.2": if needs_update("ssl_strong_ciphers"): commands["ssl_strong_ciphers"] = "nxapi ssl ciphers weak" if want["ssl_strong_ciphers"] is True: - commands[ - "ssl_strong_ciphers" - ] = "no nxapi ssl ciphers weak" + commands["ssl_strong_ciphers"] = "no nxapi ssl ciphers weak" have_ssl_protocols = "" want_ssl_protocols = "" @@ -272,7 +268,7 @@ def needs_update(x): if needs_update(key): if want.get(key) is True: want_ssl_protocols = " ".join( - [want_ssl_protocols, value] + [want_ssl_protocols, value], ) elif have.get(key) is True: have_ssl_protocols = " ".join([have_ssl_protocols, value]) @@ -320,9 +316,7 @@ def parse_https(data): def parse_sandbox(data): - sandbox = [ - item for item in data.split("\n") if re.search(r".*sandbox.*", item) - ] + sandbox = [item for item in data.split("\n") if re.search(r".*sandbox.*", item)] value = False if sandbox and sandbox[0] == "nxapi sandbox": value = True @@ -404,17 +398,18 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() - warning_msg = ( - "Module nxos_nxapi currently defaults to configure 'http port 80'. " - ) + warning_msg = "Module nxos_nxapi currently defaults to configure 'http port 80'. " warning_msg += "Default behavior is changing to configure 'https port 443'" warning_msg += " when params 'http, http_port, https, https_port' are not set in the playbook" module.deprecate( - msg=warning_msg, date="2022-06-01", collection_name="cisco.nxos" + msg=warning_msg, + date="2022-06-01", + collection_name="cisco.nxos", ) capabilities = get_capabilities(module) diff --git a/plugins/modules/nxos_overlay_global.py b/plugins/modules/nxos_overlay_global.py index 2a41cac9b..0de0c7729 100644 --- a/plugins/modules/nxos_overlay_global.py +++ b/plugins/modules/nxos_overlay_global.py @@ -71,7 +71,7 @@ PARAM_TO_COMMAND_KEYMAP = { - "anycast_gateway_mac": "fabric forwarding anycast-gateway-mac" + "anycast_gateway_mac": "fabric forwarding anycast-gateway-mac", } @@ -82,7 +82,9 @@ def get_existing(module, args): for arg in args: command = PARAM_TO_COMMAND_KEYMAP[arg] has_command = re.findall( - r"(?:{0}\s)(?P.*)$".format(command), config, re.M + r"(?:{0}\s)(?P.*)$".format(command), + config, + re.M, ) value = "" if has_command: @@ -159,7 +161,8 @@ def normalize_mac(proposed_mac, module): raise ValueError except ValueError: module.fail_json( - msg="Invalid MAC address format", proposed_mac=proposed_mac + msg="Invalid MAC address format", + proposed_mac=proposed_mac, ) joined_mac = "".join(splitted_mac) @@ -173,7 +176,8 @@ def main(): argument_spec = dict(anycast_gateway_mac=dict(required=True, type="str")) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -182,9 +186,7 @@ def main(): args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) - proposed = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) candidate = CustomNetworkConfig(indent=3) get_commands(module, existing, proposed, candidate) diff --git a/plugins/modules/nxos_pim.py b/plugins/modules/nxos_pim.py index b49a96fa1..f1597e966 100644 --- a/plugins/modules/nxos_pim.py +++ b/plugins/modules/nxos_pim.py @@ -158,12 +158,16 @@ def main(): argument_spec = dict( bfd=dict(required=False, type="str", choices=["enable", "disable"]), ssm_range=dict( - required=False, type="list", default=[], elements="str" + required=False, + type="list", + default=[], + elements="str", ), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() result = {"changed": False, "commands": [], "warnings": warnings} diff --git a/plugins/modules/nxos_pim_interface.py b/plugins/modules/nxos_pim_interface.py index d9e31d6f9..068c8eb69 100644 --- a/plugins/modules/nxos_pim_interface.py +++ b/plugins/modules/nxos_pim_interface.py @@ -316,12 +316,11 @@ def get_pim_interface(module, interface): pim_interface["sparse"] = True elif "bfd-instance" in each: m = re.search( - r"ip pim bfd-instance(?P disable)?", each + r"ip pim bfd-instance(?P disable)?", + each, ) if m: - pim_interface["bfd"] = ( - "disable" if m.group("disable") else "enable" - ) + pim_interface["bfd"] = "disable" if m.group("disable") else "enable" elif "border" in each: pim_interface["border"] = True elif "hello-interval" in each: @@ -331,7 +330,8 @@ def get_pim_interface(module, interface): ).group(1) elif "dr-priority" in each: pim_interface["dr_prio"] = re.search( - r"ip pim dr-priority (\d+)", body + r"ip pim dr-priority (\d+)", + body, ).group(1) return pim_interface @@ -340,10 +340,7 @@ def get_pim_interface(module, interface): def fix_delta(delta, existing): for key in list(delta): if key in ["dr_prio", "hello_interval", "sparse", "border"]: - if ( - delta.get(key) == PARAM_TO_DEFAULT_KEYMAP.get(key) - and existing.get(key) is None - ): + if delta.get(key) == PARAM_TO_DEFAULT_KEYMAP.get(key) and existing.get(key) is None: delta.pop(key) return delta @@ -358,11 +355,11 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): if delta.get("jp_policy_in") or delta.get("jp_policy_out"): if existing.get("jp_type_in") == "prefix": command = "no ip pim jp-policy prefix-list {0}".format( - existing.get("jp_policy_in") + existing.get("jp_policy_in"), ) else: command = "no ip pim jp-policy {0}".format( - existing.get("jp_policy_in") + existing.get("jp_policy_in"), ) if command: commands.append(command) @@ -396,7 +393,7 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): ]: if k in ["neighbor_policy", "neighbor_type"]: temp = delta.get("neighbor_policy") or existing.get( - "neighbor_policy" + "neighbor_policy", ) if delta.get("neighbor_type") == "prefix": command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp) @@ -408,7 +405,7 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): command = "ip pim neighbor-policy {0}".format(temp) elif k in ["jp_policy_in", "jp_type_in"]: temp = delta.get("jp_policy_in") or existing.get( - "jp_policy_in" + "jp_policy_in", ) if delta.get("jp_type_in") == "prefix": command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp) @@ -420,7 +417,7 @@ def config_pim_interface(delta, existing, jp_bidir, isauth): command = "ip pim jp-policy {0} in".format(temp) elif k in ["jp_policy_out", "jp_type_out"]: temp = delta.get("jp_policy_out") or existing.get( - "jp_policy_out" + "jp_policy_out", ) if delta.get("jp_type_out") == "prefix": command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp) @@ -451,9 +448,7 @@ def get_pim_interface_defaults(): hello_auth_key=PARAM_TO_DEFAULT_KEYMAP.get("hello_auth_key"), ) - default = dict( - (param, value) for (param, value) in args.items() if value is not None - ) + default = dict((param, value) for (param, value) in args.items() if value is not None) return default @@ -465,7 +460,7 @@ def default_pim_interface_policies(existing, jp_bidir): if existing.get("jp_policy_in") or existing.get("jp_policy_out"): if existing.get("jp_type_in") == "prefix": command = "no ip pim jp-policy prefix-list {0}".format( - existing.get("jp_policy_in") + existing.get("jp_policy_in"), ) if command: commands.append(command) @@ -476,22 +471,18 @@ def default_pim_interface_policies(existing, jp_bidir): if k == "jp_policy_in": if existing.get("jp_policy_in"): if existing.get("jp_type_in") == "prefix": - command = ( - "no ip pim jp-policy prefix-list {0} in".format( - existing.get("jp_policy_in"), - ) + command = "no ip pim jp-policy prefix-list {0} in".format( + existing.get("jp_policy_in"), ) else: command = "no ip pim jp-policy {0} in".format( - existing.get("jp_policy_in") + existing.get("jp_policy_in"), ) elif k == "jp_policy_out": if existing.get("jp_policy_out"): if existing.get("jp_type_out") == "prefix": - command = ( - "no ip pim jp-policy prefix-list {0} out".format( - existing.get("jp_policy_out"), - ) + command = "no ip pim jp-policy prefix-list {0} out".format( + existing.get("jp_policy_out"), ) else: command = "no ip pim jp-policy {0} out".format( @@ -586,26 +577,24 @@ def main(): if jp_policy_in: if not jp_type_in: module.fail_json( - msg="jp_type_in required when using jp_policy_in." + msg="jp_type_in required when using jp_policy_in.", ) if jp_policy_out: if not jp_type_out: module.fail_json( - msg="jp_type_out required when using jp_policy_out." + msg="jp_type_out required when using jp_policy_out.", ) if neighbor_policy: if not neighbor_type: module.fail_json( - msg="neighbor_type required when using neighbor_policy." + msg="neighbor_type required when using neighbor_policy.", ) get_existing = get_pim_interface(module, interface) existing, jp_bidir, isauth = local_existing(get_existing) args = PARAM_TO_COMMAND_KEYMAP.keys() - proposed = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) normalize_proposed_values(proposed, module) delta = dict(set(proposed.items()).difference(existing.items())) diff --git a/plugins/modules/nxos_pim_rp_address.py b/plugins/modules/nxos_pim_rp_address.py index a6feb8c98..1cf5a2120 100644 --- a/plugins/modules/nxos_pim_rp_address.py +++ b/plugins/modules/nxos_pim_rp_address.py @@ -145,7 +145,8 @@ def build_command(param_dict, command): for param in ["group_list", "prefix_list", "route_map"]: if param_dict.get(param): command += " {0} {1}".format( - param.replace("_", "-"), param_dict.get(param) + param.replace("_", "-"), + param_dict.get(param), ) if param_dict.get("bidir"): command += " bidir" @@ -190,7 +191,9 @@ def main(): route_map=dict(required=False, type="str"), bidir=dict(required=False, type="bool"), state=dict( - choices=["present", "absent"], default="present", required=False + choices=["present", "absent"], + default="present", + required=False, ), ) @@ -211,9 +214,7 @@ def main(): args = ["rp_address", "group_list", "prefix_list", "route_map", "bidir"] - proposed_args = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) if module.params["group_list"]: existing = get_existing(module, args, True) diff --git a/plugins/modules/nxos_ping.py b/plugins/modules/nxos_ping.py index c1c8a9685..460da6a7b 100644 --- a/plugins/modules/nxos_ping.py +++ b/plugins/modules/nxos_ping.py @@ -132,9 +132,7 @@ """ from ansible.module_utils.basic import AnsibleModule -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( - run_commands, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands def get_summary(results_list, reference_point): @@ -205,7 +203,9 @@ def get_ping_results(command, module): reference_point = get_statistics_summary_line(splitted_ping) summary, ping_pass = get_summary(splitted_ping, reference_point) rtt = get_rtt( - splitted_ping, summary["packet_loss"], reference_point + 2 + splitted_ping, + summary["packet_loss"], + reference_point + 2, ) return (summary, rtt, ping_pass) @@ -220,12 +220,15 @@ def main(): size=dict(required=False, type="int"), df_bit=dict(required=False, default=False, type="bool"), state=dict( - required=False, choices=["present", "absent"], default="present" + required=False, + choices=["present", "absent"], + default="present", ), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) destination = module.params["dest"] diff --git a/plugins/modules/nxos_reboot.py b/plugins/modules/nxos_reboot.py index 5f917438e..3110f9830 100644 --- a/plugins/modules/nxos_reboot.py +++ b/plugins/modules/nxos_reboot.py @@ -60,9 +60,7 @@ from ansible.module_utils.basic import AnsibleModule -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( - load_config, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import load_config def reboot(module): @@ -75,7 +73,8 @@ def main(): argument_spec = dict(confirm=dict(default=False, type="bool")) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_rollback.py b/plugins/modules/nxos_rollback.py index ebd6519bd..a79938282 100644 --- a/plugins/modules/nxos_rollback.py +++ b/plugins/modules/nxos_rollback.py @@ -77,9 +77,7 @@ from ansible.module_utils.basic import AnsibleModule -from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import ( - run_commands, -) +from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands def checkpoint(filename, module): @@ -102,7 +100,8 @@ def rollback(filename, module): def main(): argument_spec = dict( - checkpoint_file=dict(required=False), rollback_to=dict(required=False) + checkpoint_file=dict(required=False), + rollback_to=dict(required=False), ) module = AnsibleModule( diff --git a/plugins/modules/nxos_rpm.py b/plugins/modules/nxos_rpm.py index 1f4896828..96af4d1c5 100644 --- a/plugins/modules/nxos_rpm.py +++ b/plugins/modules/nxos_rpm.py @@ -202,8 +202,7 @@ def activate_reload(module, pkg, flag): if "socket is closed" in msg[0].lower(): return cmd if ( - "another install operation is in progress" - in msg[0].lower() + "another install operation is in progress" in msg[0].lower() or "failed" in msg[0].lower() ): time.sleep(2) @@ -264,8 +263,12 @@ def install_remove_rpm(module, full_pkg, file_system, state): if pkg not in inactive_body and pkg not in active_body: commands.append( add_operation( - module, show_inactive, file_system, full_pkg, pkg - ) + module, + show_inactive, + file_system, + full_pkg, + pkg, + ), ) patch_type_body = execute_show_command(show_pkg_info, module) @@ -286,11 +289,11 @@ def install_remove_rpm(module, full_pkg, file_system, state): if pkg in patch_body: # This is smu/patch rpm commands.append( - commit_operation(module, show_commit, pkg, False) + commit_operation(module, show_commit, pkg, False), ) else: err = 'Operation "install activate {0} forced" Failed'.format( - pkg + pkg, ) module.fail_json(msg=err) @@ -309,13 +312,13 @@ def install_remove_rpm(module, full_pkg, file_system, state): return commands else: commands.append( - deactivate_operation(module, show_active, pkg, True) + deactivate_operation(module, show_active, pkg, True), ) commit_body = execute_show_command(show_commit, module) if pkg in commit_body: # This is smu/patch rpm commands.append( - commit_operation(module, show_commit, pkg, True) + commit_operation(module, show_commit, pkg, True), ) commands.extend(remove_operation(module, show_inactive, pkg)) @@ -331,7 +334,7 @@ def install_remove_rpm(module, full_pkg, file_system, state): return commands else: commands.append( - deactivate_operation(module, show_inactive, pkg, False) + deactivate_operation(module, show_inactive, pkg, False), ) commands.extend(remove_operation(module, show_inactive, pkg)) @@ -357,7 +360,7 @@ def main(): remove_default_spec(aggregate_spec) argument_spec = dict( - aggregate=dict(type="list", elements="dict", options=aggregate_spec) + aggregate=dict(type="list", elements="dict", options=aggregate_spec), ) argument_spec.update(element_spec) @@ -396,16 +399,21 @@ def main(): for obj in objects: if obj["state"] == "present": remote_exists = remote_file_exists( - module, obj["pkg"], file_system=obj["file_system"] + module, + obj["pkg"], + file_system=obj["file_system"], ) if not remote_exists: module.fail_json( - msg="The requested package doesn't exist on the device" + msg="The requested package doesn't exist on the device", ) cmds = install_remove_rpm( - module, obj["pkg"], obj["file_system"], obj["state"] + module, + obj["pkg"], + obj["file_system"], + obj["state"], ) if cmds: diff --git a/plugins/modules/nxos_snapshot.py b/plugins/modules/nxos_snapshot.py index 2479b69de..f5c08754c 100644 --- a/plugins/modules/nxos_snapshot.py +++ b/plugins/modules/nxos_snapshot.py @@ -291,7 +291,7 @@ def action_delete(module, existing_snapshots): if exist: commands.append( - "snapshot delete {0}".format(module.params["snapshot_name"]) + "snapshot delete {0}".format(module.params["snapshot_name"]), ) return commands @@ -373,8 +373,8 @@ def main(): if not os.path.isdir(module.params["path"]): module.fail_json( msg="{0} is not a valid directory name.".format( - module.params["path"] - ) + module.params["path"], + ), ) existing_snapshots = invoke("get_existing", module) @@ -391,7 +391,8 @@ def main(): snapshot2 = module.params["snapshot2"] compare_option = module.params["compare_option"] command = "show snapshot compare {0} {1}".format( - snapshot1, snapshot2 + snapshot1, + snapshot2, ) if compare_option: command += " {0}".format(compare_option) @@ -410,12 +411,14 @@ def main(): and module.params["save_snapshot_locally"] ): command = "show snapshot dump {0} | json".format( - module.params["snapshot_name"] + module.params["snapshot_name"], ) content = execute_show_command(command, module)[0] if content: write_on_file( - str(content), module.params["snapshot_name"], module + str(content), + module.params["snapshot_name"], + module, ) module.exit_json(**result) diff --git a/plugins/modules/nxos_snmp_community.py b/plugins/modules/nxos_snmp_community.py index fd5f9c43e..c9639c23f 100644 --- a/plugins/modules/nxos_snmp_community.py +++ b/plugins/modules/nxos_snmp_community.py @@ -215,7 +215,7 @@ def main(): if group not in configured_groups: module.fail_json( - msg="Group not on switch. Please add before moving forward" + msg="Group not on switch. Please add before moving forward", ) existing = get_snmp_community(module, community) diff --git a/plugins/modules/nxos_snmp_contact.py b/plugins/modules/nxos_snmp_contact.py index 9a540e7cd..030672505 100644 --- a/plugins/modules/nxos_snmp_contact.py +++ b/plugins/modules/nxos_snmp_contact.py @@ -117,7 +117,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_snmp_host.py b/plugins/modules/nxos_snmp_host.py index b982313fd..ccb6e6366 100644 --- a/plugins/modules/nxos_snmp_host.py +++ b/plugins/modules/nxos_snmp_host.py @@ -202,11 +202,7 @@ def get_snmp_host(host, udp, module): vrf_filt = each.get("TABLE_vrf_filters") if vrf_filt: - vrf_filter = ( - vrf_filt["ROW_vrf_filters"]["vrf_filter"] - .split(":")[1] - .split(",") - ) + vrf_filter = vrf_filt["ROW_vrf_filters"]["vrf_filter"].split(":")[1].split(",") filters = [vrf.strip() for vrf in vrf_filter] host_resource["vrf_filter"] = filters @@ -223,18 +219,14 @@ def get_snmp_host(host, udp, module): resource_table = [resource_table] for each in resource_table: - key = ( - str(each["address"]) + "_" + str(each["port"]).strip() - ) + key = str(each["address"]) + "_" + str(each["port"]).strip() src = each.get("src_intf") host_resource = apply_key_map(host_map_5k, each) if src: host_resource["src_intf"] = src if re.search(r"interface:", src): - host_resource["src_intf"] = src.split(":")[ - 1 - ].strip() + host_resource["src_intf"] = src.split(":")[1].strip() vrf = each.get("use_vrf_name") if vrf: @@ -242,9 +234,7 @@ def get_snmp_host(host, udp, module): vrf_filt = each.get("TABLE_filter_vrf") if vrf_filt: - vrf_filter = vrf_filt["ROW_filter_vrf"][ - "filter_vrf_name" - ].split(",") + vrf_filter = vrf_filt["ROW_filter_vrf"]["filter_vrf_name"].split(",") filters = [vrf.strip() for vrf in vrf_filter] host_resource["vrf_filter"] = filters @@ -418,7 +408,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -458,8 +449,7 @@ def main(): if (version == "v1" or version == "v2c") and v3: module.fail_json( - msg='param: "v3" should not be used when ' - "using version v1 or v2c" + msg='param: "v3" should not be used when ' "using version v1 or v2c", ) if not any([vrf_filter, vrf, src_intf]): @@ -510,7 +500,7 @@ def main(): commands.append(remove_vrf(snmp_host, udp, proposed, existing)) if proposed.get("vrf_filter"): commands.append( - remove_filter(snmp_host, udp, proposed, existing) + remove_filter(snmp_host, udp, proposed, existing), ) elif state == "present": diff --git a/plugins/modules/nxos_snmp_location.py b/plugins/modules/nxos_snmp_location.py index ad4cd1d28..55887e293 100644 --- a/plugins/modules/nxos_snmp_location.py +++ b/plugins/modules/nxos_snmp_location.py @@ -122,7 +122,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_snmp_traps.py b/plugins/modules/nxos_snmp_traps.py index 27d4dfd9a..94c0687aa 100644 --- a/plugins/modules/nxos_snmp_traps.py +++ b/plugins/modules/nxos_snmp_traps.py @@ -178,7 +178,7 @@ def get_snmp_traps(group, module): if "all" in group and "N3K-C35" in get_platform_id(module): module.warn( - "Platform does not support bfd traps; bfd ignored for 'group: all' request" + "Platform does not support bfd traps; bfd ignored for 'group: all' request", ) feature_list.remove("bfd") @@ -228,7 +228,7 @@ def get_trap_commands(group, state, existing, module): for feature in existing: if existing[feature]: trap_command = "no snmp-server enable traps {0}".format( - feature + feature, ) commands.append(trap_command) @@ -236,7 +236,7 @@ def get_trap_commands(group, state, existing, module): for feature in existing: if existing[feature] is False: trap_command = "snmp-server enable traps {0}".format( - feature + feature, ) commands.append(trap_command) @@ -249,13 +249,13 @@ def get_trap_commands(group, state, existing, module): if state == "disabled" and enabled: commands.append( - ["no snmp-server enable traps {0}".format(group)] + ["no snmp-server enable traps {0}".format(group)], ) elif state == "enabled" and disabled: commands.append(["snmp-server enable traps {0}".format(group)]) else: module.fail_json( - msg="{0} is not a currently " "enabled feature.".format(group) + msg="{0} is not a currently " "enabled feature.".format(group), ) return commands @@ -302,7 +302,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_snmp_user.py b/plugins/modules/nxos_snmp_user.py index 55f099721..a3b0b5fa8 100644 --- a/plugins/modules/nxos_snmp_user.py +++ b/plugins/modules/nxos_snmp_user.py @@ -252,9 +252,7 @@ def get_non_structured_snmp_user(body_text): return resource resource["user"] = m.group("user") resource["auth"] = m.group("auth") - resource["encrypt"] = ( - "aes-128" if "aes" in str(m.group("priv")) else "none" - ) + resource["encrypt"] = "aes-128" if "aes" in str(m.group("priv")) else "none" resource["group"] = [m.group("group")] more_groups = re.findall(r"^\s+([\w\d-]+)\s*$", output, re.M) @@ -333,8 +331,7 @@ def main(): if privacy and encrypt: if not pwd and authentication: module.fail_json( - msg="pwd and authentication must be provided " - "when using privacy and encrypt", + msg="pwd and authentication must be provided " "when using privacy and encrypt", ) if group and group not in get_snmp_groups(module): diff --git a/plugins/modules/nxos_system.py b/plugins/modules/nxos_system.py index a405038a5..a5ba240cb 100644 --- a/plugins/modules/nxos_system.py +++ b/plugins/modules/nxos_system.py @@ -374,7 +374,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_telemetry.py b/plugins/modules/nxos_telemetry.py index 0a52db82d..b0db9e912 100644 --- a/plugins/modules/nxos_telemetry.py +++ b/plugins/modules/nxos_telemetry.py @@ -328,7 +328,8 @@ def main(): :returns: the result form module invocation """ module = AnsibleModule( - argument_spec=TelemetryArgs.argument_spec, supports_check_mode=True + argument_spec=TelemetryArgs.argument_spec, + supports_check_mode=True, ) result = Telemetry(module).execute_module() diff --git a/plugins/modules/nxos_udld.py b/plugins/modules/nxos_udld.py index 09921df32..7b7a69eb8 100644 --- a/plugins/modules/nxos_udld.py +++ b/plugins/modules/nxos_udld.py @@ -147,16 +147,12 @@ def get_commands_config_udld_global(delta, reset, existing): commands = [] for param, value in delta.items(): if param == "aggressive": - command = ( - "udld aggressive" - if value == "enabled" - else "no udld aggressive" - ) + command = "udld aggressive" if value == "enabled" else "no udld aggressive" commands.append(command) elif param == "msg_time": if value == "default": if existing.get("msg_time") != PARAM_TO_DEFAULT_KEYMAP.get( - "msg_time" + "msg_time", ): commands.append("no udld message-time") else: @@ -203,7 +199,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -229,7 +226,9 @@ def main(): if state == "present": if delta: command = get_commands_config_udld_global( - dict(delta), reset, existing + dict(delta), + reset, + existing, ) commands.append(command) diff --git a/plugins/modules/nxos_udld_interface.py b/plugins/modules/nxos_udld_interface.py index ce48089c2..c1ea6c7bd 100644 --- a/plugins/modules/nxos_udld_interface.py +++ b/plugins/modules/nxos_udld_interface.py @@ -143,9 +143,7 @@ def get_udld_interface(module, interface): mode = None mode_str = None try: - body = run_commands(module, [{"command": command, "output": "text"}])[ - 0 - ] + body = run_commands(module, [{"command": command, "output": "text"}])[0] if "aggressive" in body: mode = "aggressive" mode_str = "aggressive" @@ -230,14 +228,16 @@ def get_commands_remove_udld_interface(delta, interface, module, existing): def main(): argument_spec = dict( mode=dict( - choices=["enabled", "disabled", "aggressive"], required=True + choices=["enabled", "disabled", "aggressive"], + required=True, ), interface=dict(type="str", required=True), state=dict(choices=["absent", "present"], default="present"), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -258,7 +258,10 @@ def main(): if state == "present": if delta: command = get_commands_config_udld_interface1( - delta, interface, module, existing + delta, + interface, + module, + existing, ) commands.append(command) cmds = flatten_list(commands) @@ -271,7 +274,10 @@ def main(): if delta["mode"] == "enabled" or delta["mode"] == "disabled": commands = [] command = get_commands_config_udld_interface2( - delta, interface, module, existing + delta, + interface, + module, + existing, ) commands.append(command) cmds = flatten_list(commands) @@ -284,7 +290,10 @@ def main(): common = set(proposed.items()).intersection(existing.items()) if common: command = get_commands_remove_udld_interface( - dict(common), interface, module, existing + dict(common), + interface, + module, + existing, ) cmds = flatten_list(commands) if module.check_mode: diff --git a/plugins/modules/nxos_user.py b/plugins/modules/nxos_user.py index aff3269d2..33c74c05a 100644 --- a/plugins/modules/nxos_user.py +++ b/plugins/modules/nxos_user.py @@ -321,7 +321,8 @@ def parse_roles(data): def map_config_to_obj(module): out = run_commands( - module, [{"command": "show user-account", "output": "json"}] + module, + [{"command": "show user-account", "output": "json"}], ) data = out[0] @@ -421,7 +422,8 @@ def main(): configured_password=dict(no_log=True), hashed_password=dict(no_log=True), update_password=dict( - default="always", choices=["on_create", "always"] + default="always", + choices=["on_create", "always"], ), roles=dict(type="list", aliases=["role"], elements="str"), sshkey=dict(no_log=False), @@ -481,7 +483,8 @@ def main(): # check if provided hashed password is infact a hash if module.params["hashed_password"] is not None: if not re.match( - r"^\$5\$......\$.*$", module.params["hashed_password"] + r"^\$5\$......\$.*$", + module.params["hashed_password"], ): module.fail_json(msg="Provided hash is not valid") @@ -493,11 +496,7 @@ def main(): module.fail_json(msg=resp) else: result["warnings"].extend( - [ - x[9:] - for x in resp.splitlines() - if x.startswith("WARNING: ") - ], + [x[9:] for x in resp.splitlines() if x.startswith("WARNING: ")], ) result["changed"] = True diff --git a/plugins/modules/nxos_vlans.py b/plugins/modules/nxos_vlans.py index 958dead17..a327076f4 100644 --- a/plugins/modules/nxos_vlans.py +++ b/plugins/modules/nxos_vlans.py @@ -430,7 +430,8 @@ def main(): :returns: the result form module invocation """ module = AnsibleModule( - argument_spec=VlansArgs.argument_spec, supports_check_mode=True + argument_spec=VlansArgs.argument_spec, + supports_check_mode=True, ) result = Vlans(module).execute_module() diff --git a/plugins/modules/nxos_vpc.py b/plugins/modules/nxos_vpc.py index 8d81d8e93..bab74ae8a 100644 --- a/plugins/modules/nxos_vpc.py +++ b/plugins/modules/nxos_vpc.py @@ -388,9 +388,7 @@ def main(): auto_recovery = module.params["auto_recovery"] auto_recovery_reload_delay = module.params["auto_recovery_reload_delay"] delay_restore = module.params["delay_restore"] - delay_restore_interface_vlan = module.params[ - "delay_restore_interface_vlan" - ] + delay_restore_interface_vlan = module.params["delay_restore_interface_vlan"] delay_restore_orphan_port = module.params["delay_restore_orphan_port"] state = module.params["state"] @@ -412,19 +410,16 @@ def main(): if not pkl_dest: if pkl_src: module.fail_json( - msg="dest IP for peer-keepalive is required" - " when src IP is present" + msg="dest IP for peer-keepalive is required" " when src IP is present", ) elif pkl_vrf: if pkl_vrf != "management": module.fail_json( - msg="dest and src IP for peer-keepalive are required" - " when vrf is present", + msg="dest and src IP for peer-keepalive are required" " when vrf is present", ) else: module.fail_json( - msg="dest IP for peer-keepalive is required" - " when vrf is present", + msg="dest IP for peer-keepalive is required" " when vrf is present", ) if pkl_vrf: if pkl_vrf.lower() not in get_vrf_list(module): @@ -449,15 +444,17 @@ def main(): if delta: pkl_dependencies(module, delta, existing) command = get_commands_to_config_vpc( - module, delta, domain, existing + module, + delta, + domain, + existing, ) commands.append(command) elif state == "absent": if existing: if domain != existing["domain"]: module.fail_json( - msg="You are trying to remove a domain that " - "does not exist on the device", + msg="You are trying to remove a domain that " "does not exist on the device", ) else: commands.append("terminal dont-ask") diff --git a/plugins/modules/nxos_vpc_interface.py b/plugins/modules/nxos_vpc_interface.py index de4d0b92a..eb9f0502e 100644 --- a/plugins/modules/nxos_vpc_interface.py +++ b/plugins/modules/nxos_vpc_interface.py @@ -198,7 +198,10 @@ def get_portchannel_vpc_config(module, portchannel): def get_commands_to_config_vpc_interface( - portchannel, delta, config_value, existing + portchannel, + delta, + config_value, + existing, ): commands = [] @@ -222,7 +225,10 @@ def state_present(portchannel, delta, config_value, existing): commands = [] command = get_commands_to_config_vpc_interface( - portchannel, delta, config_value, existing + portchannel, + delta, + config_value, + existing, ) commands.append(command) @@ -271,7 +277,7 @@ def main(): if portchannel not in get_portchannel_list(module): if not portchannel.isdigit() or int( - portchannel + portchannel, ) not in get_portchannel_list(module): module.fail_json( msg="The portchannel you are trying to make a" @@ -314,8 +320,7 @@ def main(): if active_peer_link != portchannel: if peer_link: module.fail_json( - msg="A peer link already exists on" - " the device. Remove it first", + msg="A peer link already exists on" " the device. Remove it first", current_peer_link="Po{0}".format(active_peer_link), ) config_value = "peer-link" @@ -327,7 +332,10 @@ def main(): delta = dict(set(proposed.items()).difference(existing.items())) if delta: commands = state_present( - portchannel, delta, config_value, existing + portchannel, + delta, + config_value, + existing, ) elif state == "absent" and existing: diff --git a/plugins/modules/nxos_vrf.py b/plugins/modules/nxos_vrf.py index 6b0e158b7..5b6fb5c78 100644 --- a/plugins/modules/nxos_vrf.py +++ b/plugins/modules/nxos_vrf.py @@ -340,10 +340,10 @@ def map_obj_to_commands(updates, module): # If vni is already configured on vrf, unconfigure it first. if vni: if obj_in_have.get("vni") and vni != obj_in_have.get( - "vni" + "vni", ): commands.append( - "no vni {0}".format(obj_in_have.get("vni")) + "no vni {0}".format(obj_in_have.get("vni")), ) for item in args: @@ -356,7 +356,7 @@ def map_obj_to_commands(updates, module): cmd = item + " " + str(candidate) commands.append(cmd) if admin_state and admin_state != obj_in_have.get( - "admin_state" + "admin_state", ): if admin_state == "up": commands.append("no shutdown") @@ -442,7 +442,8 @@ def validate_vrf(name, module): module.fail_json(msg="cannot use default as name of a VRF") elif len(name) > 32: module.fail_json( - msg="VRF name exceeded max length of 32", name=name + msg="VRF name exceeded max length of 32", + name=name, ) else: return name @@ -470,9 +471,7 @@ def map_params_to_obj(module): "admin_state": module.params["admin_state"], "state": module.params["state"], "interfaces": module.params["interfaces"], - "associated_interfaces": module.params[ - "associated_interfaces" - ], + "associated_interfaces": module.params["associated_interfaces"], }, ) return obj @@ -554,8 +553,7 @@ def check_declarative_intent_params(want, module, element_spec, result): interfaces = obj_in_have.get("interfaces") if interfaces is not None and i not in interfaces: module.fail_json( - msg="Interface %s not configured on vrf %s" - % (i, w["name"]), + msg="Interface %s not configured on vrf %s" % (i, w["name"]), ) @@ -566,11 +564,13 @@ def vrf_error_check(module, commands, responses): # Allow delay/retry for VRF changes time.sleep(15) responses = load_config( - module, commands, opts={"catch_clierror": True} + module, + commands, + opts={"catch_clierror": True}, ) if re.search(pattern, str(responses)): module.fail_json( - msg="VRF config (and retry) failure: %s " % responses + msg="VRF config (and retry) failure: %s " % responses, ) module.warn("VRF config delayed by VRF deletion - passed on retry") @@ -587,7 +587,9 @@ def main(): associated_interfaces=dict(type="list", elements="str"), delay=dict(type="int", default=10), state=dict( - type="str", default="present", choices=["present", "absent"] + type="str", + default="present", + choices=["present", "absent"], ), ) @@ -625,7 +627,9 @@ def main(): if commands and not module.check_mode: responses = load_config( - module, commands, opts={"catch_clierror": True} + module, + commands, + opts={"catch_clierror": True}, ) vrf_error_check(module, commands, responses) result["changed"] = True diff --git a/plugins/modules/nxos_vrf_af.py b/plugins/modules/nxos_vrf_af.py index 713bb5d24..9dfa4b51c 100644 --- a/plugins/modules/nxos_vrf_af.py +++ b/plugins/modules/nxos_vrf_af.py @@ -193,7 +193,8 @@ def main(): options=dict( rt=dict(type="str", required=True), direction=dict( - choices=["import", "export", "both"], default="both" + choices=["import", "export", "both"], + default="both", ), state=dict(choices=["present", "absent"], default="present"), ), @@ -201,7 +202,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -243,12 +245,13 @@ def main(): if module.params["route_targets"] is not None: for rt in module.params["route_targets"]: if rt.get("direction") == "both" or not rt.get("direction"): - platform = get_capabilities(module)["device_info"][ - "network_os_platform" - ] + platform = get_capabilities(module)["device_info"]["network_os_platform"] if platform.startswith("N9K") and rt.get("rt") == "auto": rt_commands = match_current_rt( - rt, "both", current, rt_commands + rt, + "both", + current, + rt_commands, ) else: rt_commands = match_current_rt( @@ -276,7 +279,8 @@ def main(): if commands and current: commands.insert( - 0, "address-family %s unicast" % module.params["afi"] + 0, + "address-family %s unicast" % module.params["afi"], ) if commands: diff --git a/plugins/modules/nxos_vrf_interface.py b/plugins/modules/nxos_vrf_interface.py index 59b09ccec..816dd265b 100644 --- a/plugins/modules/nxos_vrf_interface.py +++ b/plugins/modules/nxos_vrf_interface.py @@ -182,12 +182,15 @@ def main(): vrf=dict(required=True), interface=dict(type="str", required=True), state=dict( - default="present", choices=["present", "absent"], required=False + default="present", + choices=["present", "absent"], + required=False, ), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -203,7 +206,7 @@ def main(): current_vrfs = get_vrf_list(module) if vrf not in current_vrfs: warnings.append( - "The VRF is not present/active on the device. Use nxos_vrf to fix this." + "The VRF is not present/active on the device. Use nxos_vrf to fix this.", ) intf_type = get_interface_type(interface) diff --git a/plugins/modules/nxos_vrrp.py b/plugins/modules/nxos_vrrp.py index ce3608d4f..63db89aa6 100644 --- a/plugins/modules/nxos_vrrp.py +++ b/plugins/modules/nxos_vrrp.py @@ -327,8 +327,7 @@ def validate_params(param, module): raise ValueError except ValueError: module.fail_json( - msg="Warning! 'priority' must be an integer " - "between 1 and 254", + msg="Warning! 'priority' must be an integer " "between 1 and 254", priority=value, ) @@ -349,11 +348,14 @@ def main(): ), authentication=dict(required=False, type="str", no_log=True), state=dict( - choices=["absent", "present"], required=False, default="present" + choices=["absent", "present"], + required=False, + default="present", ), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -391,8 +393,7 @@ def main(): mode, name = get_interface_mode(interface, intf_type, module) if mode == "layer2": module.fail_json( - msg="That interface is a layer2 port.\nMake it " - "a layer 3 port first.", + msg="That interface is a layer2 port.\nMake it " "a layer 3 port first.", interface=interface, ) diff --git a/plugins/modules/nxos_vsan.py b/plugins/modules/nxos_vsan.py index 60e1f8646..365b86e0f 100644 --- a/plugins/modules/nxos_vsan.py +++ b/plugins/modules/nxos_vsan.py @@ -203,7 +203,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() messages = list() @@ -225,8 +226,7 @@ def main(): if int(vsanid) < 1 or int(vsanid) >= 4095: module.fail_json( - msg=vsanid - + " - This is an invalid vsan. Supported vsan range is 1-4094", + msg=vsanid + " - This is an invalid vsan. Supported vsan range is 1-4094", ) if vsanid in dictSwVsanObjs.keys(): @@ -244,8 +244,7 @@ def main(): # Negative case: if vsanid == "4079" or vsanid == "4094": messages.append( - str(vsanid) - + " is a reserved vsan, hence cannot be removed", + str(vsanid) + " is a reserved vsan, hence cannot be removed", ) continue if vsanid == sw_vsanid: @@ -262,8 +261,7 @@ def main(): # Negative case: if vsanid == "4079" or vsanid == "4094": messages.append( - str(vsanid) - + " is a reserved vsan, and always present on the switch", + str(vsanid) + " is a reserved vsan, and always present on the switch", ) else: if vsanid == sw_vsanid: @@ -293,21 +291,17 @@ def main(): ) else: commands.append( - "vsan " + str(vsanid) + " name " + vsanname + "vsan " + str(vsanid) + " name " + vsanname, ) messages.append( - "setting vsan name to " - + vsanname - + " for vsan " - + str(vsanid), + "setting vsan name to " + vsanname + " for vsan " + str(vsanid), ) if vsansuspend: # Negative case: if vsanid == "4079" or vsanid == "4094": messages.append( - str(vsanid) - + " is a reserved vsan, and cannot be suspended", + str(vsanid) + " is a reserved vsan, and cannot be suspended", ) else: if sw_vsanstate == "suspended": @@ -344,25 +338,14 @@ def main(): ) else: commands.append( - "vsan " - + str(vsanid) - + " interface " - + each_interface_name, + "vsan " + str(vsanid) + " interface " + each_interface_name, ) messages.append( - "adding interface " - + each_interface_name - + " to vsan " - + str(vsanid), + "adding interface " + each_interface_name + " to vsan " + str(vsanid), ) if len(commands) != 0: - commands = ( - ["terminal dont-ask"] - + ["vsan database"] - + commands - + ["no terminal dont-ask"] - ) + commands = ["terminal dont-ask"] + ["vsan database"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) commands_executed = cmds diff --git a/plugins/modules/nxos_vtp_domain.py b/plugins/modules/nxos_vtp_domain.py index 6f25968f4..6e4870b92 100644 --- a/plugins/modules/nxos_vtp_domain.py +++ b/plugins/modules/nxos_vtp_domain.py @@ -171,7 +171,8 @@ def main(): argument_spec = dict(domain=dict(type="str", required=True)) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_vtp_password.py b/plugins/modules/nxos_vtp_password.py index 846edfb44..317c6c9a2 100644 --- a/plugins/modules/nxos_vtp_password.py +++ b/plugins/modules/nxos_vtp_password.py @@ -201,7 +201,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -241,8 +242,7 @@ def main(): else: if not existing.get("domain"): module.fail_json( - msg="Cannot remove a vtp password " - "before vtp domain is set." + msg="Cannot remove a vtp password " "before vtp domain is set.", ) elif existing["vtp_password"] != ("\\"): @@ -252,7 +252,7 @@ def main(): if delta: if not existing.get("domain"): module.fail_json( - msg="Cannot set vtp password " "before vtp domain is set." + msg="Cannot set vtp password " "before vtp domain is set.", ) else: diff --git a/plugins/modules/nxos_vtp_version.py b/plugins/modules/nxos_vtp_version.py index c981d3dc0..2ac9beb64 100644 --- a/plugins/modules/nxos_vtp_version.py +++ b/plugins/modules/nxos_vtp_version.py @@ -162,11 +162,12 @@ def get_vtp_password(module): def main(): argument_spec = dict( - version=dict(type="str", choices=["1", "2", "3"], required=True) + version=dict(type="str", choices=["1", "2", "3"], required=True), ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() diff --git a/plugins/modules/nxos_vxlan_vtep.py b/plugins/modules/nxos_vxlan_vtep.py index 86ae45f22..b22ad674f 100644 --- a/plugins/modules/nxos_vxlan_vtep.py +++ b/plugins/modules/nxos_vxlan_vtep.py @@ -178,10 +178,12 @@ def get_value(arg, config, module): if arg in BOOL_PARAMS: REGEX = re.compile( - r"\s+{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M + r"\s+{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), + re.M, ) NO_REGEX = re.compile( - r"\s+no\s{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M + r"\s+no\s{0}\s*$".format(PARAM_TO_COMMAND_KEYMAP[arg]), + re.M, ) NO_SHUT_REGEX = re.compile(r"\s+no shutdown\s*$", re.M) value = False @@ -213,7 +215,8 @@ def get_value(arg, config, module): re.M, ) NO_DESC_REGEX = re.compile( - r"\s+{0}\s*$".format("no description"), re.M + r"\s+{0}\s*$".format("no description"), + re.M, ) SOURCE_INTF_REGEX = re.compile( r"(?:{0}\s)(?P\S+)$".format(PARAM_TO_COMMAND_KEYMAP[arg]), @@ -229,11 +232,7 @@ def get_value(arg, config, module): for line in config.splitlines(): try: if PARAM_TO_COMMAND_KEYMAP[arg] in config: - value = ( - SOURCE_INTF_REGEX.search(config) - .group("value") - .strip() - ) + value = SOURCE_INTF_REGEX.search(config).group("value").strip() break except AttributeError: value = "" @@ -257,11 +256,7 @@ def get_value(arg, config, module): for line in config.splitlines(): try: if PARAM_TO_COMMAND_KEYMAP[arg] in config: - value = ( - SOURCE_INTF_REGEX.search(config) - .group("value") - .strip() - ) + value = SOURCE_INTF_REGEX.search(config).group("value").strip() break except AttributeError: value = "" @@ -274,11 +269,12 @@ def get_value(arg, config, module): def get_existing(module, args): existing = {} netcfg = CustomNetworkConfig( - indent=2, contents=get_config(module, flags=["all"]) + indent=2, + contents=get_config(module, flags=["all"]), ) interface_string = "interface {0}".format( - module.params["interface"].lower() + module.params["interface"].lower(), ) parents = [interface_string] config = netcfg.get_section(parents) @@ -356,7 +352,7 @@ def gsa_tcam_check(module): Note that changing tcam_size requires a switch reboot to take effect. """ cmds = [ - {"command": "show hardware access-list tcam region", "output": "json"} + {"command": "show hardware access-list tcam region", "output": "json"}, ] body = run_commands(module, cmds) if body: @@ -365,8 +361,7 @@ def gsa_tcam_check(module): [ i for i in tcam_region - if i["type"].startswith("Ingress ARP-Ether ACL") - and i["tcam_size"] == "0" + if i["type"].startswith("Ingress ARP-Ether ACL") and i["tcam_size"] == "0" ], ): msg = ( @@ -414,7 +409,7 @@ def state_present(module, existing, proposed, candidate): else: if not existing and module.params["interface"]: commands = [ - "interface {0}".format(module.params["interface"].lower()) + "interface {0}".format(module.params["interface"].lower()), ] candidate.add(commands, parents=[]) @@ -437,14 +432,16 @@ def main(): source_interface=dict(required=False, type="str"), source_interface_hold_down_time=dict(required=False, type="str"), state=dict( - choices=["present", "absent"], default="present", required=False + choices=["present", "absent"], + default="present", + required=False, ), multisite_border_gateway_interface=dict(required=False, type="str"), advertise_virtual_rmac=dict(required=False, type="bool"), ) mutually_exclusive = [ - ("global_ingress_replication_bgp", "global_mcast_group_L2") + ("global_ingress_replication_bgp", "global_mcast_group_L2"), ] module = AnsibleModule( @@ -461,9 +458,7 @@ def main(): args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) - proposed_args = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key != "interface": diff --git a/plugins/modules/nxos_vxlan_vtep_vni.py b/plugins/modules/nxos_vxlan_vtep_vni.py index 0dd65c6e7..8a455bc84 100644 --- a/plugins/modules/nxos_vxlan_vtep_vni.py +++ b/plugins/modules/nxos_vxlan_vtep_vni.py @@ -148,7 +148,8 @@ def get_value(arg, config, module): command = PARAM_TO_COMMAND_KEYMAP[arg] command_val_re = re.compile( - r"(?:{0}\s)(?P.*)$".format(command), re.M + r"(?:{0}\s)(?P.*)$".format(command), + re.M, ) if arg in BOOL_PARAMS: @@ -197,12 +198,9 @@ def get_existing(module, args): parents = ["interface {0}".format(interface_exist)] temp_config = netcfg.get_section(parents) - if ( - "member vni {0} associate-vrf".format(module.params["vni"]) - in temp_config - ): + if "member vni {0} associate-vrf".format(module.params["vni"]) in temp_config: parents.append( - "member vni {0} associate-vrf".format(module.params["vni"]) + "member vni {0} associate-vrf".format(module.params["vni"]), ) config = netcfg.get_section(parents) elif "member vni {0}".format(module.params["vni"]) in temp_config: @@ -252,17 +250,16 @@ def state_present(module, existing, proposed, candidate): if vni_command not in commands: commands.append("member vni {0}".format(module.params["vni"])) if value != PARAM_TO_DEFAULT_KEYMAP.get( - "multicast_group", "default" + "multicast_group", + "default", ): commands.append("{0} {1}".format(key, value)) - elif ( - key == "ingress-replication protocol" - and value != existing_commands.get(key) - ): + elif key == "ingress-replication protocol" and value != existing_commands.get(key): evalue = existing_commands.get(key) dvalue = PARAM_TO_DEFAULT_KEYMAP.get( - "ingress_replication", "default" + "ingress_replication", + "default", ) if value != dvalue: if evalue and evalue != dvalue: @@ -287,10 +284,7 @@ def state_present(module, existing, proposed, candidate): else: if key.replace(" ", "_").replace("-", "_") in BOOL_PARAMS: commands.append("no {0}".format(key.lower())) - elif ( - key == "multisite ingress-replication" - and value != existing_commands.get(key) - ): + elif key == "multisite ingress-replication" and value != existing_commands.get(key): vni_command = "member vni {0}".format(module.params["vni"]) if vni_command not in commands: commands.append("member vni {0}".format(module.params["vni"])) @@ -311,9 +305,7 @@ def state_present(module, existing, proposed, candidate): vni_command = "member vni {0}".format(module.params["vni"]) ingress_replications_command = "ingress-replication protocol static" ingress_replicationb_command = "ingress-replication protocol bgp" - ingress_replicationns_command = ( - "no ingress-replication protocol static" - ) + ingress_replicationns_command = "no ingress-replication protocol static" ingress_replicationnb_command = "no ingress-replication protocol bgp" interface_command = "interface {0}".format(module.params["interface"]) @@ -353,7 +345,7 @@ def state_present(module, existing, proposed, candidate): def state_absent(module, existing, proposed, candidate): if existing["assoc_vrf"]: commands = [ - "no member vni {0} associate-vrf".format(module.params["vni"]) + "no member vni {0} associate-vrf".format(module.params["vni"]), ] else: commands = ["no member vni {0}".format(module.params["vni"])] @@ -371,10 +363,14 @@ def main(): suppress_arp=dict(required=False, type="bool"), suppress_arp_disable=dict(required=False, type="bool"), ingress_replication=dict( - required=False, type="str", choices=["bgp", "static", "default"] + required=False, + type="str", + choices=["bgp", "static", "default"], ), state=dict( - choices=["present", "absent"], default="present", required=False + choices=["present", "absent"], + default="present", + required=False, ), multisite_ingress_replication=dict( required=False, @@ -405,8 +401,7 @@ def main(): and module.params["ingress_replication"] != "static" ): module.fail_json( - msg="ingress_replication=static is required " - "when using peer_list param", + msg="ingress_replication=static is required " "when using peer_list param", ) else: peer_list = module.params["peer_list"] @@ -437,7 +432,7 @@ def main(): ) elif interface_exist != module.params["interface"]: module.fail_json( - msg="Only 1 NVE interface is allowed on the switch." + msg="Only 1 NVE interface is allowed on the switch.", ) elif state == "absent": if interface_exist != module.params["interface"]: @@ -450,9 +445,7 @@ def main(): existing_vni=existing["vni"], ) - proposed_args = dict( - (k, v) for k, v in module.params.items() if v is not None and k in args - ) + proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): diff --git a/plugins/modules/nxos_zone_zoneset.py b/plugins/modules/nxos_zone_zoneset.py index b19b67fd7..ec99709e9 100644 --- a/plugins/modules/nxos_zone_zoneset.py +++ b/plugins/modules/nxos_zone_zoneset.py @@ -240,9 +240,7 @@ def __init__(self, module, vsan): self.parseCmdOutput() def execute_show_zoneset_active_cmd(self): - command = ( - "show zoneset active vsan " + str(self.vsan) + " | grep zoneset" - ) + command = "show zoneset active vsan " + str(self.vsan) + " | grep zoneset" output = execute_show_command(command, self.module)[0] return output @@ -464,7 +462,9 @@ def main(): zoneset_spec = dict( name=dict(type="str", required=True), members=dict( - type="list", elements="dict", options=zoneset_member_spec + type="list", + elements="dict", + options=zoneset_member_spec, ), remove=dict(type="bool", default=False), action=dict(type="str", choices=["activate", "deactivate"]), @@ -488,7 +488,8 @@ def main(): ) module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True + argument_spec=argument_spec, + supports_check_mode=True, ) warnings = list() @@ -519,9 +520,7 @@ def main(): if shZoneStatusObj.isVsanAbsent(): module.fail_json( - msg="Vsan " - + str(vsan) - + " is not present in the switch. Hence cannot procced.", + msg="Vsan " + str(vsan) + " is not present in the switch. Hence cannot procced.", ) if shZoneStatusObj.isLocked(): @@ -563,7 +562,7 @@ def main(): if op_mode != sw_mode: if op_mode == "enhanced": commands_executed.append( - "zone mode enhanced vsan " + str(vsan) + "zone mode enhanced vsan " + str(vsan), ) messages.append( "zone mode configuration changed from basic to enhanced for vsan " @@ -571,7 +570,7 @@ def main(): ) else: commands_executed.append( - "no zone mode enhanced vsan " + str(vsan) + "no zone mode enhanced vsan " + str(vsan), ) messages.append( "zone mode configuration changed from enhanced to basic for vsan " @@ -593,14 +592,14 @@ def main(): "zone smart-zoning enable vsan " + str(vsan), ) messages.append( - "smart-zoning enabled for vsan " + str(vsan) + "smart-zoning enabled for vsan " + str(vsan), ) else: commands_executed.append( "no zone smart-zoning enable vsan " + str(vsan), ) messages.append( - "smart-zoning disabled for vsan " + str(vsan) + "smart-zoning disabled for vsan " + str(vsan), ) else: messages.append( @@ -622,10 +621,7 @@ def main(): if removeflag: if shZoneObj.isZonePresent(zname): messages.append( - "zone '" - + zname - + "' is removed from vsan " - + str(vsan), + "zone '" + zname + "' is removed from vsan " + str(vsan), ) commands_executed.append( "no zone name " + zname + " vsan " + str(vsan), @@ -642,46 +638,35 @@ def main(): if zmembers is None: if shZoneObj.isZonePresent(zname): messages.append( - "zone '" - + zname - + "' is already present in vsan " - + str(vsan), + "zone '" + zname + "' is already present in vsan " + str(vsan), ) else: commands_executed.append( "zone name " + zname + " vsan " + str(vsan), ) messages.append( - "zone '" - + zname - + "' is created in vsan " - + str(vsan), + "zone '" + zname + "' is created in vsan " + str(vsan), ) else: cmdmemlist = [] for eachmem in zmembers: memtype = getMemType( - supported_choices, eachmem.keys() - ) - cmd = ( - memtype.replace("_", "-") - + " " - + eachmem[memtype] + supported_choices, + eachmem.keys(), ) + cmd = memtype.replace("_", "-") + " " + eachmem[memtype] if op_smart_zoning or sw_smart_zoning_bool: if eachmem["devtype"] is not None: cmd = cmd + " " + eachmem["devtype"] if eachmem["remove"]: if shZoneObj.isZonePresent(zname): if shZoneObj.isZoneMemberPresent( - zname, cmd + zname, + cmd, ): cmd = "no member " + cmd cmdmemlist.append(cmd) - if ( - op_smart_zoning - and eachmem["devtype"] is not None - ): + if op_smart_zoning and eachmem["devtype"] is not None: messages.append( "removing zone member '" + eachmem[memtype] @@ -702,10 +687,7 @@ def main(): + str(vsan), ) else: - if ( - op_smart_zoning - and eachmem["devtype"] is not None - ): + if op_smart_zoning and eachmem["devtype"] is not None: messages.append( "zone member '" + eachmem[memtype] @@ -738,10 +720,7 @@ def main(): else: if shZoneObj.isZoneMemberPresent(zname, cmd): - if ( - op_smart_zoning - and eachmem["devtype"] is not None - ): + if op_smart_zoning and eachmem["devtype"] is not None: messages.append( "zone member '" + eachmem[memtype] @@ -766,10 +745,7 @@ def main(): else: cmd = "member " + cmd cmdmemlist.append(cmd) - if ( - op_smart_zoning - and eachmem["devtype"] is not None - ): + if op_smart_zoning and eachmem["devtype"] is not None: messages.append( "adding zone member '" + eachmem[memtype] @@ -809,16 +785,10 @@ def main(): if removeflag: if shZonesetObj.isZonesetPresent(zsetname): messages.append( - "zoneset '" - + zsetname - + "' is removed from vsan " - + str(vsan), + "zoneset '" + zsetname + "' is removed from vsan " + str(vsan), ) commands_executed.append( - "no zoneset name " - + zsetname - + " vsan " - + str(vsan), + "no zoneset name " + zsetname + " vsan " + str(vsan), ) else: messages.append( @@ -886,10 +856,7 @@ def main(): ) if len(cmdmemlist) != 0: commands_executed.append( - "zoneset name " - + zsetname - + " vsan " - + str(vsan), + "zoneset name " + zsetname + " vsan " + str(vsan), ) commands_executed = commands_executed + cmdmemlist else: @@ -902,32 +869,20 @@ def main(): ) else: commands_executed.append( - "zoneset name " - + zsetname - + " vsan " - + str(vsan), + "zoneset name " + zsetname + " vsan " + str(vsan), ) messages.append( - "zoneset '" - + zsetname - + "' is created in vsan " - + str(vsan), + "zoneset '" + zsetname + "' is created in vsan " + str(vsan), ) # Process zoneset activate options if actionflag == "deactivate": if shZonesetActiveObj.isZonesetActive(zsetname): messages.append( - "deactivating zoneset '" - + zsetname - + "' in vsan " - + str(vsan), + "deactivating zoneset '" + zsetname + "' in vsan " + str(vsan), ) dactcmd.append( - "no zoneset activate name " - + zsetname - + " vsan " - + str(vsan), + "no zoneset activate name " + zsetname + " vsan " + str(vsan), ) else: messages.append( @@ -940,16 +895,10 @@ def main(): elif actionflag == "activate": if commands_executed: messages.append( - "activating zoneset '" - + zsetname - + "' in vsan " - + str(vsan), + "activating zoneset '" + zsetname + "' in vsan " + str(vsan), ) actcmd.append( - "zoneset activate name " - + zsetname - + " vsan " - + str(vsan), + "zoneset activate name " + zsetname + " vsan " + str(vsan), ) else: messages.append( @@ -969,11 +918,7 @@ def main(): commands_executed.append("zone commit vsan " + str(vsan)) if commands_executed: - commands_executed = ( - ["terminal dont-ask"] - + commands_executed - + ["no terminal dont-ask"] - ) + commands_executed = ["terminal dont-ask"] + commands_executed + ["no terminal dont-ask"] cmds = flatten_list(commands_executed) if cmds: diff --git a/plugins/netconf/nxos.py b/plugins/netconf/nxos.py index f6c46b7b0..fcbee7952 100644 --- a/plugins/netconf/nxos.py +++ b/plugins/netconf/nxos.py @@ -39,9 +39,7 @@ """ from ansible.plugins.netconf import NetconfBase -from ansible_collections.ansible.netcommon.plugins.plugin_utils.netconf_base import ( - NetconfBase, -) +from ansible_collections.ansible.netcommon.plugins.plugin_utils.netconf_base import NetconfBase class Netconf(NetconfBase): diff --git a/plugins/terminal/nxos.py b/plugins/terminal/nxos.py index e8be13977..c37a9701d 100644 --- a/plugins/terminal/nxos.py +++ b/plugins/terminal/nxos.py @@ -26,9 +26,7 @@ from ansible.errors import AnsibleConnectionFailure from ansible.module_utils._text import to_bytes, to_text -from ansible_collections.ansible.netcommon.plugins.plugin_utils.terminal_base import ( - TerminalBase, -) +from ansible_collections.ansible.netcommon.plugins.plugin_utils.terminal_base import TerminalBase class TerminalModule(TerminalBase): @@ -59,7 +57,8 @@ class TerminalModule(TerminalBase): re.I, ), re.compile( - rb"cannot apply non-existing acl policy to interface", re.I + rb"cannot apply non-existing acl policy to interface", + re.I, ), re.compile(rb"Duplicate sequence number", re.I), re.compile( @@ -92,20 +91,20 @@ def on_become(self, passwd=None): cmd = {"command": "enable"} if passwd: cmd["prompt"] = to_text( - r"(?i)[\r\n]?Password: $", errors="surrogate_or_strict" + r"(?i)[\r\n]?Password: $", + errors="surrogate_or_strict", ) cmd["answer"] = passwd cmd["prompt_retry_check"] = True try: self._exec_cli_command( - to_bytes(json.dumps(cmd), errors="surrogate_or_strict") + to_bytes(json.dumps(cmd), errors="surrogate_or_strict"), ) prompt = self._get_prompt() if prompt is None or not prompt.strip().endswith(b"enable#"): raise AnsibleConnectionFailure( - "failed to elevate privilege to enable mode still at prompt [%s]" - % prompt, + "failed to elevate privilege to enable mode still at prompt [%s]" % prompt, ) except AnsibleConnectionFailure as e: prompt = self._get_prompt() diff --git a/tests/unit/compat/mock.py b/tests/unit/compat/mock.py index 3b6fdcd61..3b9b0a840 100644 --- a/tests/unit/compat/mock.py +++ b/tests/unit/compat/mock.py @@ -105,7 +105,7 @@ def _readline_side_effect(): import _io file_spec = list( - set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))) + set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))), ) if mock is None: diff --git a/tests/unit/mock/path.py b/tests/unit/mock/path.py index 78733631d..78705889f 100644 --- a/tests/unit/mock/path.py +++ b/tests/unit/mock/path.py @@ -8,5 +8,6 @@ mock_unfrackpath_noop = MagicMock( - spec_set=unfrackpath, side_effect=lambda x, *args, **kwargs: x + spec_set=unfrackpath, + side_effect=lambda x, *args, **kwargs: x, ) diff --git a/tests/unit/mock/vault_helper.py b/tests/unit/mock/vault_helper.py index 7a39b007b..82d01f5c5 100644 --- a/tests/unit/mock/vault_helper.py +++ b/tests/unit/mock/vault_helper.py @@ -38,5 +38,7 @@ def __init__(self, text, encoding=None, errors=None, _bytes=None): def bytes(self): """The text encoded with encoding, unless we specifically set _bytes.""" return self._bytes or to_bytes( - self.text, encoding=self.encoding, errors=self.errors + self.text, + encoding=self.encoding, + errors=self.errors, ) diff --git a/tests/unit/mock/yaml_helper.py b/tests/unit/mock/yaml_helper.py index e973f2642..d7d759b52 100644 --- a/tests/unit/mock/yaml_helper.py +++ b/tests/unit/mock/yaml_helper.py @@ -48,7 +48,8 @@ def _dump_load_cycle(self, obj): # dump the gen 2 objects directory to strings string_from_object_dump_2 = self._dump_string( - obj_2, dumper=AnsibleDumper + obj_2, + dumper=AnsibleDumper, ) # The gen 1 and gen 2 yaml strings @@ -62,7 +63,8 @@ def _dump_load_cycle(self, obj): obj_3 = loader_3.get_data() string_from_object_dump_3 = self._dump_string( - obj_3, dumper=AnsibleDumper + obj_3, + dumper=AnsibleDumper, ) self.assertEqual(obj, obj_3) @@ -96,10 +98,14 @@ def _old_dump_load_cycle(self, obj): if PY3: yaml.dump( - obj_from_stream, stream_obj_from_stream, Dumper=AnsibleDumper + obj_from_stream, + stream_obj_from_stream, + Dumper=AnsibleDumper, ) yaml.dump( - obj_from_stream, stream_obj_from_string, Dumper=AnsibleDumper + obj_from_stream, + stream_obj_from_string, + Dumper=AnsibleDumper, ) else: yaml.dump( @@ -123,10 +129,12 @@ def _old_dump_load_cycle(self, obj): if PY3: yaml_string_obj_from_stream = yaml.dump( - obj_from_stream, Dumper=AnsibleDumper + obj_from_stream, + Dumper=AnsibleDumper, ) yaml_string_obj_from_string = yaml.dump( - obj_from_string, Dumper=AnsibleDumper + obj_from_string, + Dumper=AnsibleDumper, ) else: yaml_string_obj_from_stream = yaml.dump( @@ -141,11 +149,7 @@ def _old_dump_load_cycle(self, obj): ) assert yaml_string == yaml_string_obj_from_stream - assert ( - yaml_string - == yaml_string_obj_from_stream - == yaml_string_obj_from_string - ) + assert yaml_string == yaml_string_obj_from_stream == yaml_string_obj_from_string assert ( yaml_string == yaml_string_obj_from_stream diff --git a/tests/unit/modules/conftest.py b/tests/unit/modules/conftest.py index ee6bfa03a..349e71ada 100644 --- a/tests/unit/modules/conftest.py +++ b/tests/unit/modules/conftest.py @@ -22,20 +22,13 @@ def patch_ansible_module(request, mocker): if "ANSIBLE_MODULE_ARGS" not in request.param: request.param = {"ANSIBLE_MODULE_ARGS": request.param} if "_ansible_remote_tmp" not in request.param["ANSIBLE_MODULE_ARGS"]: - request.param["ANSIBLE_MODULE_ARGS"][ - "_ansible_remote_tmp" - ] = "/tmp" - if ( - "_ansible_keep_remote_files" - not in request.param["ANSIBLE_MODULE_ARGS"] - ): - request.param["ANSIBLE_MODULE_ARGS"][ - "_ansible_keep_remote_files" - ] = False + request.param["ANSIBLE_MODULE_ARGS"]["_ansible_remote_tmp"] = "/tmp" + if "_ansible_keep_remote_files" not in request.param["ANSIBLE_MODULE_ARGS"]: + request.param["ANSIBLE_MODULE_ARGS"]["_ansible_keep_remote_files"] = False args = json.dumps(request.param) else: raise Exception( - "Malformed data to the patch_ansible_module pytest fixture" + "Malformed data to the patch_ansible_module pytest fixture", ) mocker.patch("ansible.module_utils.basic._ANSIBLE_ARGS", to_bytes(args)) diff --git a/tests/unit/modules/network/nxos/nxos_module.py b/tests/unit/modules/network/nxos/nxos_module.py index a65988d62..02543ae9e 100644 --- a/tests/unit/modules/network/nxos/nxos_module.py +++ b/tests/unit/modules/network/nxos/nxos_module.py @@ -85,13 +85,22 @@ def execute_module_devices( retvals = {} for model in models: retvals[model] = self.execute_module( - failed, changed, commands, sort, device=model + failed, + changed, + commands, + sort, + device=model, ) return retvals def execute_module( - self, failed=False, changed=False, commands=None, sort=True, device="" + self, + failed=False, + changed=False, + commands=None, + sort=True, + device="", ): self.load_fixtures(commands, device=device) @@ -110,7 +119,9 @@ def execute_module( ) else: self.assertEqual( - commands, result["commands"], result["commands"] + commands, + result["commands"], + result["commands"], ) return result diff --git a/tests/unit/modules/network/nxos/test_nxos.py b/tests/unit/modules/network/nxos/test_nxos.py index 19450314b..d511281d6 100644 --- a/tests/unit/modules/network/nxos/test_nxos.py +++ b/tests/unit/modules/network/nxos/test_nxos.py @@ -113,7 +113,8 @@ def test_get_command_with_output_nxos(self): """Test _get_command_with_output for nxos""" self._prepare() cmd = self._cliconf._get_command_with_output( - command="show version", output="json" + command="show version", + output="json", ) self.assertEqual(cmd, "show version | json") @@ -122,7 +123,8 @@ def test_get_command_with_output_mds(self): """Test _get_command_with_output for mds""" self._prepare(platform="mds") cmd = self._cliconf._get_command_with_output( - command="show version", output="json" + command="show version", + output="json", ) self.assertEqual(cmd, "show version | json native") diff --git a/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py index 37b806800..593b28e7a 100644 --- a/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_acl_interfaces.py @@ -10,9 +10,7 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_acl_interfaces from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( - set_module_args, -) +from ansible_collections.cisco.nxos.tests.unit.modules.utils import set_module_args from .nxos_module import TestNxosModule @@ -36,16 +34,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acl_interfaces.acl_interfaces.Acl_interfaces.edit_config", @@ -264,7 +258,7 @@ def test_nxos_acl_interfaces_overridden_idempotent(self): def test_nxos_acl_interfaces_deletedname(self): set_module_args( - dict(config=[dict(name="Ethernet1/2")], state="deleted") + dict(config=[dict(name="Ethernet1/2")], state="deleted"), ) commands = ["interface Ethernet1/2", "no ip access-group ACL1v4 out"] self.execute_module(changed=True, commands=commands) @@ -273,7 +267,7 @@ def test_nxos_acl_interfaces_deletedafi(self): set_module_args( dict( config=[ - dict(name="Ethernet1/2", access_groups=[dict(afi="ipv4")]) + dict(name="Ethernet1/2", access_groups=[dict(afi="ipv4")]), ], state="deleted", ), @@ -341,7 +335,9 @@ def test_nxos_acl_interfaces_rendered(self): ] result = self.execute_module(changed=False) self.assertEqual( - sorted(result["rendered"]), sorted(commands), result["rendered"] + sorted(result["rendered"]), + sorted(commands), + result["rendered"], ) def test_nxos_acl_interfaces_parsed(self): @@ -367,7 +363,7 @@ def test_nxos_acl_interfaces_parsed(self): "access_groups": [ { "acls": [ - {"direction": "in", "name": "ACL2v6", "port": True} + {"direction": "in", "name": "ACL2v6", "port": True}, ], "afi": "ipv6", }, @@ -394,7 +390,7 @@ def test_nxos_acl_interfaces_gathered(self): "access_groups": [ { "acls": [ - {"direction": "in", "name": "ACL2v6", "port": True} + {"direction": "in", "name": "ACL2v6", "port": True}, ], "afi": "ipv6", }, diff --git a/tests/unit/modules/network/nxos/test_nxos_acls.py b/tests/unit/modules/network/nxos/test_nxos_acls.py index 5a331e728..36f762398 100644 --- a/tests/unit/modules/network/nxos/test_nxos_acls.py +++ b/tests/unit/modules/network/nxos/test_nxos_acls.py @@ -12,9 +12,7 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_acls from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( - set_module_args, -) +from ansible_collections.cisco.nxos.tests.unit.modules.utils import set_module_args from .nxos_module import TestNxosModule @@ -38,16 +36,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.acls.acls.Acls.edit_config", @@ -90,7 +84,7 @@ def test_nxos_acls_merged(self): sequence=20, protocol="tcp", protocol_options=dict( - tcp=dict(ack=True) + tcp=dict(ack=True), ), ), dict( @@ -110,7 +104,7 @@ def test_nxos_acls_merged(self): dict( grant="deny", destination=dict( - prefix="2002:2:2:2::/64" + prefix="2002:2:2:2::/64", ), source=dict(prefix="2002:1:1:1::/64"), sequence=30, @@ -207,7 +201,7 @@ def test_nxos_acls_replaced(self): protocol="icmp", protocol_options=dict( icmp=dict( - administratively_prohibited=True + administratively_prohibited=True, ), ), ), @@ -297,7 +291,7 @@ def test_nxos_acls_overridden(self): protocol="icmp", protocol_options=dict( icmp=dict( - administratively_prohibited=True + administratively_prohibited=True, ), ), ), @@ -554,7 +548,7 @@ def test_nxos_acls_gathered(self): "range": { "start": "1024", "end": "65500", - } + }, }, }, "destination": { @@ -746,7 +740,7 @@ def test_nxos_acls_parse_remark(self): "grant": "permit", "protocol": "ipv6", "source": { - "host": "2001:db8:85a3::8a2e:370:7334" + "host": "2001:db8:85a3::8a2e:370:7334", }, "destination": {"any": True}, }, @@ -802,7 +796,7 @@ def test_nxos_acls_parse_remark(self): "grant": "permit", "protocol": "tcp", "protocol_options": { - "tcp": {"established": True} + "tcp": {"established": True}, }, "source": { "host": "1.1.1.1", diff --git a/tests/unit/modules/network/nxos/test_nxos_bfd_global.py b/tests/unit/modules/network/nxos/test_nxos_bfd_global.py index 438d0ad76..478fdf146 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bfd_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_bfd_global.py @@ -209,7 +209,8 @@ def test_bfd_defaults_n7k(self): def test_bfd_existing_n9k(self): module_name = self.module.__name__.rsplit(".", 1)[1] self.execute_show_command.return_value = load_fixture( - module_name, "N9K.cfg" + module_name, + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -247,7 +248,8 @@ def test_bfd_existing_n9k(self): def test_bfd_idempotence_n9k(self): module_name = self.module.__name__.rsplit(".", 1)[1] self.execute_show_command.return_value = load_fixture( - module_name, "N9K.cfg" + module_name, + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -270,7 +272,8 @@ def test_bfd_idempotence_n9k(self): def test_bfd_existing_n7k(self): module_name = self.module.__name__.rsplit(".", 1)[1] self.execute_show_command.return_value = load_fixture( - module_name, "N7K.cfg" + module_name, + "N7K.cfg", ) self.get_platform_shortname.return_value = "N7K" set_module_args( @@ -312,7 +315,8 @@ def test_bfd_existing_n7k(self): def test_bfd_idempotence_n7k(self): module_name = self.module.__name__.rsplit(".", 1)[1] self.execute_show_command.return_value = load_fixture( - module_name, "N7K.cfg" + module_name, + "N7K.cfg", ) self.get_platform_shortname.return_value = "N7K" set_module_args( diff --git a/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py index 306faa991..84fc09813 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_bfd_interfaces.py @@ -47,16 +47,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.bfd_interfaces.bfd_interfaces.Bfd_interfaces.edit_config", @@ -104,7 +100,7 @@ def test_1(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -155,7 +151,7 @@ def test_2(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -222,7 +218,7 @@ def test_3(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict(config=[dict(name="Ethernet1/1")]) # Expected result commands for each 'state' @@ -265,10 +261,10 @@ def test_4(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( - config=[dict(name="Ethernet1/1.42", bfd="enable", echo="disable")] + config=[dict(name="Ethernet1/1.42", bfd="enable", echo="disable")], ) # Expected result commands for each 'state' merged = ["interface Ethernet1/1.42", "bfd", "no bfd echo"] @@ -310,7 +306,7 @@ def test_5(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py b/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py index cc562607a..7abef90cb 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_address_family.py @@ -24,9 +24,7 @@ from textwrap import dedent -from ansible_collections.cisco.nxos.plugins.modules import ( - nxos_bgp_address_family, -) +from ansible_collections.cisco.nxos.plugins.modules import nxos_bgp_address_family from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch from .nxos_module import TestNxosModule, set_module_args @@ -55,9 +53,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_address_family.bgp_address_family.Bgp_address_familyFacts.get_config", @@ -156,7 +152,7 @@ def test_nxos_bgp_additional_paths_replaced(self): afi="ipv4", safi="multicast", additional_paths=dict( - selection=dict(route_map="rmap1") + selection=dict(route_map="rmap1"), ), ), dict( @@ -237,7 +233,7 @@ def test_nxos_bgp_l2vpn_keys_replaced(self): config=dict( as_number="65563", address_family=[ - dict(afi="l2vpn", safi="evpn", advertise_pip=True) + dict(afi="l2vpn", safi="evpn", advertise_pip=True), ], ), state="replaced", @@ -360,7 +356,8 @@ def test_nxos_bgp_aggregate_address_merged(self): safi="multicast", aggregate_address=[ dict( - prefix="192.168.1.0/24", summary_only=True + prefix="192.168.1.0/24", + summary_only=True, ), dict( prefix="192.168.2.0/24", @@ -493,7 +490,9 @@ def test_nxos_bgp_dampen_igp_metric_merged(self): as_number="65563", address_family=[ dict( - afi="ipv4", safi="multicast", dampen_igp_metric=300 + afi="ipv4", + safi="multicast", + dampen_igp_metric=300, ), dict( vrf="site-1", @@ -843,7 +842,9 @@ def test_nxos_bgp_default_metric_merged(self): as_number="65563", address_family=[ dict( - afi="ipv4", safi="multicast", default_metric=7200 + afi="ipv4", + safi="multicast", + default_metric=7200, ), dict( vrf="site-1", @@ -927,7 +928,9 @@ def test_nxos_bgp_distance_merged(self): afi="ipv4", safi="multicast", distance=dict( - ebgp_routes=25, ibgp_routes=12, local_routes=4 + ebgp_routes=25, + ibgp_routes=12, + local_routes=4, ), ), dict( @@ -935,7 +938,9 @@ def test_nxos_bgp_distance_merged(self): afi="ipv4", safi="unicast", distance=dict( - ebgp_routes=20, ibgp_routes=18, local_routes=3 + ebgp_routes=20, + ibgp_routes=18, + local_routes=3, ), ), ], @@ -980,7 +985,9 @@ def test_nxos_bgp_distance_replaced(self): afi="ipv4", safi="unicast", distance=dict( - ebgp_routes=20, ibgp_routes=18, local_routes=2 + ebgp_routes=20, + ibgp_routes=18, + local_routes=2, ), ), ], @@ -1182,7 +1189,7 @@ def test_nxos_bgp_inject_map_replaced(self): afi="ipv4", safi="multicast", inject_map=[ - dict(route_map="rmap1", exist_map="rmap3") + dict(route_map="rmap1", exist_map="rmap3"), ], ), dict( @@ -1233,7 +1240,8 @@ def test_nxos_bgp_maximum_paths_merged(self): afi="ipv4", safi="multicast", maximum_paths=dict( - parallel_paths=15, ibgp=dict(parallel_paths=64) + parallel_paths=15, + ibgp=dict(parallel_paths=64), ), ), dict( @@ -1298,7 +1306,8 @@ def test_nxos_bgp_maximum_paths_replaced(self): afi="ipv4", safi="multicast", maximum_paths=dict( - parallel_paths=15, ibgp=dict(parallel_paths=64) + parallel_paths=15, + ibgp=dict(parallel_paths=64), ), ), dict( @@ -1345,11 +1354,13 @@ def test_nxos_bgp_network_merged(self): safi="multicast", networks=[ dict( - prefix="192.168.1.0/24", route_map="rmap2" + prefix="192.168.1.0/24", + route_map="rmap2", ), dict(prefix="192.168.2.0/24"), dict( - prefix="192.168.3.0/24", route_map="rmap3" + prefix="192.168.3.0/24", + route_map="rmap3", ), ], ), @@ -1408,8 +1419,9 @@ def test_nxos_bgp_network_replaced(self): safi="multicast", networks=[ dict( - prefix="192.168.3.0/24", route_map="rmap4" - ) + prefix="192.168.3.0/24", + route_map="rmap4", + ), ], ), dict( @@ -1417,7 +1429,7 @@ def test_nxos_bgp_network_replaced(self): afi="ipv4", safi="unicast", networks=[ - dict(prefix="11.0.0.0/8", route_map="rmap2") + dict(prefix="11.0.0.0/8", route_map="rmap2"), ], ), ], @@ -1461,7 +1473,8 @@ def test_nxos_bgp_nexthop_merged(self): nexthop=dict( route_map="rmap1", trigger_delay=dict( - critical_delay=120, non_critical_delay=180 + critical_delay=120, + non_critical_delay=180, ), ), ), @@ -1471,7 +1484,8 @@ def test_nxos_bgp_nexthop_merged(self): safi="unicast", nexthop=dict( trigger_delay=dict( - critical_delay=110, non_critical_delay=170 + critical_delay=110, + non_critical_delay=170, ), ), ), @@ -1523,7 +1537,8 @@ def test_nxos_bgp_nexthop_replaced(self): safi="unicast", nexthop=dict( trigger_delay=dict( - critical_delay=110, non_critical_delay=170 + critical_delay=110, + non_critical_delay=170, ), ), ), @@ -1939,7 +1954,8 @@ def test_nxos_bgp_timers_merged(self): safi="multicast", timers=dict( bestpath_defer=dict( - defer_time=120, maximum_defer_time=380 + defer_time=120, + maximum_defer_time=380, ), ), ), @@ -1949,7 +1965,8 @@ def test_nxos_bgp_timers_merged(self): safi="unicast", timers=dict( bestpath_defer=dict( - defer_time=110, maximum_defer_time=350 + defer_time=110, + maximum_defer_time=350, ), ), ), @@ -1992,7 +2009,8 @@ def test_nxos_bgp_timers_replaced(self): safi="multicast", timers=dict( bestpath_defer=dict( - defer_time=120, maximum_defer_time=380 + defer_time=120, + maximum_defer_time=380, ), ), ), @@ -2126,8 +2144,9 @@ def test_nxos_bgp_af_parsed(self): safi="unicast", timers=dict( bestpath_defer=dict( - defer_time=100, maximum_defer_time=350 - ) + defer_time=100, + maximum_defer_time=350, + ), ), ), ], @@ -2165,8 +2184,9 @@ def test_nxos_bgp_af_gathered(self): safi="unicast", timers=dict( bestpath_defer=dict( - defer_time=100, maximum_defer_time=350 - ) + defer_time=100, + maximum_defer_time=350, + ), ), ), ], diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_global.py b/tests/unit/modules/network/nxos/test_nxos_bgp_global.py index 02ae4d914..4b2df7f6c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_global.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_global.bgp_global.Bgp_globalFacts.get_config", @@ -90,7 +88,8 @@ def test_nxos_bgp_global_merged(self): neighbor_address="198.51.100.21", remote_as="65537", password=dict( - encryption=7, key="12090404011C03162E" + encryption=7, + key="12090404011C03162E", ), ), dict( @@ -363,7 +362,8 @@ def test_nxos_bgp_global_merged_idempotent(self): neighbor_address="198.51.100.21", remote_as="65537", password=dict( - encryption=7, key="12090404011C03162E" + encryption=7, + key="12090404011C03162E", ), ), dict( @@ -774,7 +774,8 @@ def test_nxos_bgp_global_replaced_failed_2(self): neighbor_address="198.51.100.21", remote_as="65537", password=dict( - encryption=7, key="12090404011C03162E" + encryption=7, + key="12090404011C03162E", ), ), ], @@ -845,7 +846,8 @@ def test_nxos_bgp_global_replaced_failed_3(self): neighbor_address="198.51.100.21", remote_as="65537", password=dict( - encryption=7, key="12090404011C03162E" + encryption=7, + key="12090404011C03162E", ), ), ], diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py b/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py index 8bec07416..37a2ef20e 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_neighbor_address_family.py @@ -24,9 +24,7 @@ from textwrap import dedent -from ansible_collections.cisco.nxos.plugins.modules import ( - nxos_bgp_neighbor_address_family, -) +from ansible_collections.cisco.nxos.plugins.modules import nxos_bgp_neighbor_address_family from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch from .nxos_module import TestNxosModule, set_module_args @@ -55,9 +53,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_neighbor_address_family." @@ -95,7 +91,8 @@ def test_nxos_bgp_nbr_af_advertise_map_merged(self): afi="ipv4", safi="multicast", advertise_map=dict( - route_map="rmap1", exist_map="rmap2" + route_map="rmap1", + exist_map="rmap2", ), ), ], @@ -175,7 +172,8 @@ def test_nxos_bgp_nbr_af_advertise_map_replaced(self): afi="ipv4", safi="multicast", advertise_map=dict( - route_map="rmap1", exist_map="rmap3" + route_map="rmap1", + exist_map="rmap3", ), ), ], @@ -593,7 +591,7 @@ def test_nxos_bgp_nbr_af_as_override_replaced(self): dict( neighbor_address="10.0.0.2", address_family=[ - dict(afi="ipv4", safi="multicast") + dict(afi="ipv4", safi="multicast"), ], ), ], @@ -661,7 +659,8 @@ def test_nxos_bgp_nbr_af_capability_merged(self): safi="multicast", capability=dict( additional_paths=dict( - receive="enable", send="enable" + receive="enable", + send="enable", ), ), ), @@ -754,7 +753,7 @@ def test_nxos_bgp_nbr_af_capability_replaced(self): afi="ipv4", safi="multicast", capability=dict( - additional_paths=dict(send="enable") + additional_paths=dict(send="enable"), ), ), ], @@ -855,7 +854,7 @@ def test_nxos_bgp_nbr_af_originate_peer_as_merged(self): afi="ipv4", safi="multicast", default_originate=dict( - route_map="rmap2" + route_map="rmap2", ), ), ], @@ -988,10 +987,12 @@ def test_nxos_bgp_nbr_af_filter_list_inherit_merged(self): afi="ipv4", safi="multicast", filter_list=dict( - inbound="rmap3", outbound="rmap4" + inbound="rmap3", + outbound="rmap4", ), inherit=dict( - template="template-2", sequence=200 + template="template-2", + sequence=200, ), ), ], @@ -1086,7 +1087,8 @@ def test_nxos_bgp_nbr_af_filter_list_inherit_replaced(self): safi="multicast", filter_list=dict(inbound="rmap3"), inherit=dict( - template="template-2", sequence=200 + template="template-2", + sequence=200, ), ), ], @@ -1207,7 +1209,7 @@ def test_nxos_bgp_nbr_af_maximum_prefix_merged(self): afi="ipv4", safi="multicast", maximum_prefix=dict( - max_prefix_limit=28 + max_prefix_limit=28, ), ), dict( @@ -1315,7 +1317,7 @@ def test_nxos_bgp_nbr_af_maximum_prefix_replaced(self): afi="ipv4", safi="multicast", maximum_prefix=dict( - max_prefix_limit=28 + max_prefix_limit=28, ), ), dict( @@ -1409,14 +1411,14 @@ def test_nxos_bgp_nbr_af_next_hop_merged(self): afi="ipv4", safi="multicast", next_hop_self=dict( - all_routes=True + all_routes=True, ), ), dict( afi="ipv6", safi="multicast", next_hop_self=dict( - all_routes=True + all_routes=True, ), ), ], @@ -1498,7 +1500,7 @@ def test_nxos_bgp_nbr_af_next_hop_replaced(self): afi="ipv4", safi="multicast", next_hop_self=dict( - all_routes=True + all_routes=True, ), ), ], @@ -1551,7 +1553,8 @@ def test_nxos_bgp_nbr_af_prefix_list_merged(self): afi="ipv4", safi="multicast", prefix_list=dict( - inbound="rmap3", outbound="rmap4" + inbound="rmap3", + outbound="rmap4", ), ), ], @@ -1704,7 +1707,8 @@ def test_nxos_bgp_nbr_af_rewrite_evpn_route_map_merged(self): afi="ipv4", safi="multicast", route_map=dict( - inbound="rmap3", outbound="rmap4" + inbound="rmap3", + outbound="rmap4", ), rewrite_evpn_rt_asn=True, ), @@ -2006,7 +2010,7 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_merged(self): afi="ipv4", safi="multicast", soft_reconfiguration_inbound=dict( - set=True + set=True, ), soo="73:43", ), @@ -2024,7 +2028,7 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_merged(self): afi="ipv4", safi="unicast", soft_reconfiguration_inbound=dict( - always=True + always=True, ), soo="65:28", ), @@ -2032,7 +2036,7 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_merged(self): afi="ipv4", safi="multicast", soft_reconfiguration_inbound=dict( - always=True + always=True, ), ), ], @@ -2089,7 +2093,7 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_replaced(self): afi="ipv4", safi="multicast", soft_reconfiguration_inbound=dict( - set=True + set=True, ), ), ], @@ -2106,7 +2110,7 @@ def test_nxos_bgp_nbr_af_soft_reconfiguration_soo_replaced(self): afi="ipv4", safi="unicast", soft_reconfiguration_inbound=dict( - always=True + always=True, ), soo="65:28", ), @@ -2244,7 +2248,7 @@ def test_nxos_bgp_nbr_af_suppress_inactive_unsuppress_replaced(self): dict( neighbor_address="10.0.0.2", address_family=[ - dict(afi="ipv4", safi="multicast") + dict(afi="ipv4", safi="multicast"), ], ), ], @@ -2430,7 +2434,7 @@ def test_nxos_bgp_nbr_af_overridden(self): dict( neighbor_address="192.168.1.1", address_family=[ - dict(afi="ipv4", safi="multicast") + dict(afi="ipv4", safi="multicast"), ], ), ], @@ -2490,7 +2494,7 @@ def test_nxos_bgp_nbr_af_gathered(self): dict( neighbor_address="192.168.1.1", address_family=[ - dict(afi="ipv4", safi="multicast") + dict(afi="ipv4", safi="multicast"), ], ), ], @@ -2537,7 +2541,7 @@ def test_nxos_bgp_nbr_af_parsed(self): dict( neighbor_address="192.168.1.1", address_family=[ - dict(afi="ipv4", safi="multicast") + dict(afi="ipv4", safi="multicast"), ], ), ], @@ -2657,7 +2661,7 @@ def test_nxos_bgp_nbr_af_no_cmd(self): dict( neighbor_address="10.0.0.2", address_family=[ - dict(afi="ipv4", safi="multicast") + dict(afi="ipv4", safi="multicast"), ], ), ], diff --git a/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py b/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py index fe9d92440..4eaa47205 100644 --- a/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py +++ b/tests/unit/modules/network/nxos/test_nxos_bgp_templates.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.bgp_templates.bgp_templates.Bgp_templatesFacts.get_config", @@ -343,7 +341,8 @@ def test_nxos_bgp_templates_deleted_single(self): set_module_args( dict( config=dict( - as_number="65536", neighbor=[dict(name="tmplt_1")] + as_number="65536", + neighbor=[dict(name="tmplt_1")], ), state="deleted", ), diff --git a/tests/unit/modules/network/nxos/test_nxos_command.py b/tests/unit/modules/network/nxos/test_nxos_command.py index 84bf5b133..f6a57e18f 100644 --- a/tests/unit/modules/network/nxos/test_nxos_command.py +++ b/tests/unit/modules/network/nxos/test_nxos_command.py @@ -88,7 +88,7 @@ def test_nxos_command_wait_for_fails(self): def test_nxos_command_retries(self): wait_for = 'result[0] contains "test string"' set_module_args( - dict(commands=["show version"], wait_for=wait_for, retries=2) + dict(commands=["show version"], wait_for=wait_for, retries=2), ) self.execute_module(failed=True) self.assertEqual(self.run_commands.call_count, 3) @@ -104,7 +104,7 @@ def test_nxos_command_match_any(self): 'result[0] contains "test string"', ] set_module_args( - dict(commands=["show version"], wait_for=wait_for, match="any") + dict(commands=["show version"], wait_for=wait_for, match="any"), ) self.execute_module() @@ -114,7 +114,7 @@ def test_nxos_command_match_all(self): 'result[0] contains "image file"', ] set_module_args( - dict(commands=["show version"], wait_for=wait_for, match="all") + dict(commands=["show version"], wait_for=wait_for, match="all"), ) self.execute_module() @@ -125,6 +125,6 @@ def test_nxos_command_match_all_failure(self): ] commands = ["show version", "show version"] set_module_args( - dict(commands=commands, wait_for=wait_for, match="all") + dict(commands=commands, wait_for=wait_for, match="all"), ) self.execute_module(failed=True) diff --git a/tests/unit/modules/network/nxos/test_nxos_config.py b/tests/unit/modules/network/nxos/test_nxos_config.py index a1f79899a..3befca3f7 100644 --- a/tests/unit/modules/network/nxos/test_nxos_config.py +++ b/tests/unit/modules/network/nxos/test_nxos_config.py @@ -24,10 +24,7 @@ from ansible_collections.cisco.nxos.plugins.cliconf.nxos import Cliconf from ansible_collections.cisco.nxos.plugins.modules import nxos_config -from ansible_collections.cisco.nxos.tests.unit.compat.mock import ( - MagicMock, - patch, -) +from ansible_collections.cisco.nxos.tests.unit.compat.mock import MagicMock, patch from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -78,7 +75,8 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "nxos_config", "config.cfg" + "nxos_config", + "config.cfg", ) self.load_config.return_value = None @@ -87,7 +85,8 @@ def test_nxos_config_no_change(self): args = dict(lines=lines) self.conn.get_diff = MagicMock( return_value=self.cliconf_obj.get_diff( - "\n".join(lines), self.running_config + "\n".join(lines), + self.running_config, ), ) set_module_args(args) @@ -111,7 +110,9 @@ def test_nxos_config_src(self): ] self.assertEqual( - sorted(config), sorted(result["commands"]), result["commands"] + sorted(config), + sorted(result["commands"]), + result["commands"], ) def test_nxos_config_replace_src(self): @@ -125,7 +126,8 @@ def test_nxos_config_replace_src(self): ) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["config replace bootflash:config"] + result["commands"], + ["config replace bootflash:config"], ) def test_nxos_config_lines(self): @@ -133,7 +135,8 @@ def test_nxos_config_lines(self): args = dict(lines=lines) self.conn.get_diff = MagicMock( return_value=self.cliconf_obj.get_diff( - "\n".join(lines), self.running_config + "\n".join(lines), + self.running_config, ), ) set_module_args(args) @@ -142,7 +145,9 @@ def test_nxos_config_lines(self): config = ["hostname switch01"] self.assertEqual( - sorted(config), sorted(result["commands"]), result["commands"] + sorted(config), + sorted(result["commands"]), + result["commands"], ) def test_nxos_config_before(self): @@ -150,7 +155,8 @@ def test_nxos_config_before(self): args = dict(lines=lines, before=["before command"]) self.conn.get_diff = MagicMock( return_value=self.cliconf_obj.get_diff( - "\n".join(lines), self.running_config + "\n".join(lines), + self.running_config, ), ) set_module_args(args) @@ -159,7 +165,9 @@ def test_nxos_config_before(self): config = ["before command", "hostname switch01"] self.assertEqual( - sorted(config), sorted(result["commands"]), result["commands"] + sorted(config), + sorted(result["commands"]), + result["commands"], ) self.assertEqual("before command", result["commands"][0]) @@ -169,7 +177,8 @@ def test_nxos_config_after(self): self.conn.get_diff = MagicMock( return_value=self.cliconf_obj.get_diff( - "\n".join(lines), self.running_config + "\n".join(lines), + self.running_config, ), ) set_module_args(args) @@ -178,7 +187,9 @@ def test_nxos_config_after(self): config = ["after command", "hostname switch01"] self.assertEqual( - sorted(config), sorted(result["commands"]), result["commands"] + sorted(config), + sorted(result["commands"]), + result["commands"], ) self.assertEqual("after command", result["commands"][-1]) @@ -222,7 +233,9 @@ def test_nxos_replace_block_src(self): ] self.assertEqual( - sorted(config), sorted(result["commands"]), result["commands"] + sorted(config), + sorted(result["commands"]), + result["commands"], ) def test_nxos_replace_block_lines(self): @@ -328,7 +341,7 @@ def test_nxos_config_defaults_true(self): def test_nxos_config_defaults_false_backup_true(self): set_module_args( - dict(lines=["hostname localhost"], defaults=False, backup=True) + dict(lines=["hostname localhost"], defaults=False, backup=True), ) result = self.execute_module(changed=True) self.assertEqual(self.get_config.call_count, 1) @@ -336,7 +349,7 @@ def test_nxos_config_defaults_false_backup_true(self): def test_nxos_config_defaults_true_backup_true(self): set_module_args( - dict(lines=["hostname localhost"], defaults=True, backup=True) + dict(lines=["hostname localhost"], defaults=True, backup=True), ) result = self.execute_module(changed=True) self.assertEqual(self.get_config.call_count, 1) diff --git a/tests/unit/modules/network/nxos/test_nxos_devicealias.py b/tests/unit/modules/network/nxos/test_nxos_devicealias.py index ebd754ff9..94ffa6c50 100644 --- a/tests/unit/modules/network/nxos/test_nxos_devicealias.py +++ b/tests/unit/modules/network/nxos/test_nxos_devicealias.py @@ -11,9 +11,7 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_devicealias from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( - AnsibleFailJson, -) +from ansible_collections.cisco.nxos.tests.unit.modules.utils import AnsibleFailJson from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -23,15 +21,13 @@ class TestNxosDeviceAliasModule(TestNxosModule): def setUp(self): super(TestNxosDeviceAliasModule, self).setUp() - module_path = ( - "ansible_collections.cisco.nxos.plugins.modules.nxos_devicealias." - ) + module_path = "ansible_collections.cisco.nxos.plugins.modules.nxos_devicealias." self.mock_run_commands = patch(module_path + "run_commands") self.run_commands = self.mock_run_commands.start() self.mock_execute_show_cmd = patch( - module_path + "showDeviceAliasStatus.execute_show_cmd" + module_path + "showDeviceAliasStatus.execute_show_cmd", ) self.execute_show_cmd = self.mock_execute_show_cmd.start() @@ -58,7 +54,8 @@ def test_da_mode_1(self): # Switch has mode as enahnced set_module_args(dict(mode="basic"), True) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -76,7 +73,8 @@ def test_da_mode_2(self): # Switch has mode as enahnced set_module_args(dict(mode="enhanced"), True) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -86,7 +84,8 @@ def test_da_distribute_1(self): # Switch has mode as enahnced, distrbute = True set_module_args(dict(distribute=True, mode="enhanced"), True) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -96,7 +95,8 @@ def test_da_distribute_2(self): # Switch has mode as enhanced, distrbute = True set_module_args(dict(distribute=False, mode="enhanced"), True) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) result = self.execute_module(changed=True) self.assertEqual(result["commands"], ["no device-alias distribute"]) @@ -106,7 +106,8 @@ def test_da_distribute_3(self): # Switch has mode as enahnced, distrbute = True set_module_args(dict(distribute=False, mode="basic"), True) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -129,10 +130,12 @@ def test_da_add_1(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -159,10 +162,12 @@ def test_da_add_2(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -179,10 +184,12 @@ def test_da_add_3(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False, failed=True) @@ -198,10 +205,12 @@ def test_da_add_4(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False, failed=True) @@ -223,10 +232,12 @@ def test_da_remove_1(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -258,10 +269,12 @@ def test_da_remove_2(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -283,7 +296,8 @@ def test_da_lock(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatuslock.cfg" + "nxos_devicealias", + "shdastatuslock.cfg", ) self.execute_module(failed=True) @@ -305,10 +319,12 @@ def test_da_paramete_not_supported(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() @@ -327,10 +343,12 @@ def test_da_name_parameter_missing(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() @@ -350,10 +368,12 @@ def test_da_rename_1(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -380,10 +400,12 @@ def test_da_rename_2(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False, failed=True) self.assertEqual(result["commands"], []) @@ -395,7 +417,8 @@ def test_da_mansi(self): "shdastatus_mansi.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -421,10 +444,12 @@ def test_da_add_bad(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False, failed=True) @@ -442,10 +467,12 @@ def test_da_add_bad_1(self): True, ) self.execute_show_cmd.return_value = load_fixture( - "nxos_devicealias", "shdastatus.cfg" + "nxos_devicealias", + "shdastatus.cfg", ) self.execute_show_cmd_1.return_value = load_fixture( - "nxos_devicealias", "shdadatabse.cfg" + "nxos_devicealias", + "shdadatabse.cfg", ) result = self.execute_module(changed=False, failed=True) diff --git a/tests/unit/modules/network/nxos/test_nxos_evpn_global.py b/tests/unit/modules/network/nxos/test_nxos_evpn_global.py index 77303e4bc..625a3a15a 100644 --- a/tests/unit/modules/network/nxos/test_nxos_evpn_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_evpn_global.py @@ -61,13 +61,15 @@ def load_fixtures(self, commands=None, device=""): def start_configured(self, *args, **kwargs): self.get_config.return_value = load_fixture( - "nxos_evpn_global", "configured.cfg" + "nxos_evpn_global", + "configured.cfg", ) return self.execute_module(*args, **kwargs) def start_unconfigured(self, *args, **kwargs): self.get_config.return_value = load_fixture( - "nxos_evpn_global", "unconfigured.cfg" + "nxos_evpn_global", + "unconfigured.cfg", ) return self.execute_module(*args, **kwargs) diff --git a/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py b/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py index f648edcf4..3f858b543 100644 --- a/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py +++ b/tests/unit/modules/network/nxos/test_nxos_evpn_vni.py @@ -51,13 +51,14 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "", "nxos_evpn_vni_config.cfg" + "", + "nxos_evpn_vni_config.cfg", ) self.load_config.return_value = None def test_nxos_evpn_vni_present(self): set_module_args( - dict(vni="6000", route_target_import="5000:10", state="present") + dict(vni="6000", route_target_import="5000:10", state="present"), ) result = self.execute_module(changed=True) self.assertEqual( diff --git a/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py index a2e26478d..ccd23c696 100644 --- a/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_fc_interfaces.py @@ -644,9 +644,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.fc_interfaces.fc_interfaces.Fc_interfacesFacts.get_interfaces_data", @@ -708,7 +706,8 @@ def test_gathered(self): def test_parsed(self): # test parsed for config set_module_args( - dict(state="parsed", running_config=sh_run), ignore_provider_arg + dict(state="parsed", running_config=sh_run), + ignore_provider_arg, ) result = self.execute_module(changed=False) self.assertEqual(result["parsed"], gath_val) @@ -924,7 +923,8 @@ def test_analytics_scsi_to_all(self): set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["interface fc18/11", "analytics type fc-all"] + result["commands"], + ["interface fc18/11", "analytics type fc-all"], ) def test_analytics_scsi_to_all_replaced(self): @@ -1065,7 +1065,8 @@ def test_analytics_none_to_scsi(self): set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["interface fc1/1", "analytics type fc-scsi"] + result["commands"], + ["interface fc1/1", "analytics type fc-scsi"], ) def test_analytics_none_to_scsi_replaced(self): @@ -1106,7 +1107,8 @@ def test_analytics_none_to_nvme(self): set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["interface fc1/1", "analytics type fc-nvme"] + result["commands"], + ["interface fc1/1", "analytics type fc-nvme"], ) def test_analytics_none_to_nvme_replaced(self): @@ -1254,7 +1256,8 @@ def test_analytics_none_to_all(self): set_module_args(args, ignore_provider_arg) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["interface fc1/1", "analytics type fc-all"] + result["commands"], + ["interface fc1/1", "analytics type fc-all"], ) def test_analytics_none_to_all_replaced(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_feature.py b/tests/unit/modules/network/nxos/test_nxos_feature.py index f37fa7c14..be0696dfa 100644 --- a/tests/unit/modules/network/nxos/test_nxos_feature.py +++ b/tests/unit/modules/network/nxos/test_nxos_feature.py @@ -86,14 +86,16 @@ def test_nxos_feature_enable(self): set_module_args(dict(feature="nve", state="enabled")) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["terminal dont-ask", "feature nv overlay"] + result["commands"], + ["terminal dont-ask", "feature nv overlay"], ) def test_nxos_feature_disable(self): set_module_args(dict(feature="ospf", state="disabled")) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["terminal dont-ask", "no feature ospf"] + result["commands"], + ["terminal dont-ask", "no feature ospf"], ) @@ -159,14 +161,16 @@ def test_nxos_feature_enable(self): set_module_args(dict(feature="fcrxbbcredit", state="enabled")) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["terminal dont-ask", "feature fcrxbbcredit"] + result["commands"], + ["terminal dont-ask", "feature fcrxbbcredit"], ) def test_nxos_feature_disable(self): set_module_args(dict(feature="port-track", state="disabled")) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["terminal dont-ask", "no feature port-track"] + result["commands"], + ["terminal dont-ask", "no feature port-track"], ) def test_nxos_feature_enable_already_enabled(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_hostname.py b/tests/unit/modules/network/nxos/test_nxos_hostname.py index 20c071ad5..3b568300c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_hostname.py +++ b/tests/unit/modules/network/nxos/test_nxos_hostname.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.hostname.hostname.HostnameFacts.get_config", @@ -157,7 +155,8 @@ def test_nxos_hostname_parsed(self): """, ) set_module_args( - dict(running_config=cfg, state="parsed"), ignore_provider_arg + dict(running_config=cfg, state="parsed"), + ignore_provider_arg, ) parsed = {"hostname": "NXOSv-9k"} result = self.execute_module(changed=False) diff --git a/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py index 0dc6baeb2..bf9405853 100644 --- a/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_hsrp_interfaces.py @@ -47,16 +47,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.hsrp_interfaces.hsrp_interfaces.Hsrp_interfaces.edit_config", @@ -102,7 +98,7 @@ def test_1(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -145,7 +141,7 @@ def test_2(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -207,10 +203,10 @@ def test_3(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( - config=[dict(name="Ethernet1/1"), dict(name="Ethernet1/2")] + config=[dict(name="Ethernet1/1"), dict(name="Ethernet1/2")], ) # Expected result commands for each 'state' merged = [] @@ -262,7 +258,7 @@ def test_4(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict(config=[dict(name="Ethernet1/1.42", bfd="enable")]) # Expected result commands for each 'state' @@ -304,7 +300,7 @@ def test_5(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_interfaces.py index c58dd8123..be3e0431c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_interfaces.py @@ -47,16 +47,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.interfaces.interfaces.Interfaces.edit_config", @@ -128,7 +124,7 @@ def test_1(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -288,7 +284,7 @@ def test_2(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -432,7 +428,7 @@ def test_3(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -497,7 +493,9 @@ def test_3(self): "interface Ethernet1/4.101", ] self.execute_module( - changed=True, commands=merged_legacy, device="legacy" + changed=True, + commands=merged_legacy, + device="legacy", ) deleted = [ @@ -610,7 +608,7 @@ def test_4(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -646,7 +644,7 @@ def test_5(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -688,7 +686,7 @@ def test_6_gathered(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -731,7 +729,7 @@ def test_7_purged(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -772,7 +770,7 @@ def test_vlan_enabled(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs @@ -813,7 +811,7 @@ def test_mode_mtu(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_RUN_INTF: intf + self.SHOW_RUN_INTF: intf, } self.get_system_defaults.return_value = sysdefs diff --git a/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py index d96b82772..dda34abe0 100644 --- a/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_l3_interfaces.py @@ -28,10 +28,7 @@ L3_interfaces, ) from ansible_collections.cisco.nxos.plugins.modules import nxos_l3_interfaces -from ansible_collections.cisco.nxos.tests.unit.compat.mock import ( - PropertyMock, - patch, -) +from ansible_collections.cisco.nxos.tests.unit.compat.mock import PropertyMock, patch from .nxos_module import TestNxosModule, set_module_args @@ -53,16 +50,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.l3_interfaces.l3_interfaces.L3_interfaces.edit_config", @@ -117,7 +110,7 @@ def test_2(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -215,7 +208,7 @@ def test_3(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -322,7 +315,7 @@ def test_4(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -464,7 +457,7 @@ def test_5(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -551,7 +544,7 @@ def test_6(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -563,7 +556,9 @@ def test_6(self): ), dict(name="Ethernet1/2"), dict( - name="Ethernet1/3", redirects=True, unreachables=False + name="Ethernet1/3", + redirects=True, + unreachables=False, ), # defaults dict(name="Ethernet1/4", redirects=False, unreachables=True), ], @@ -637,7 +632,7 @@ def test_7(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -687,7 +682,7 @@ def test_7(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook["state"] = "deleted" set_module_args(playbook, ignore_provider_arg) @@ -702,7 +697,7 @@ def test_8(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict() @@ -730,10 +725,10 @@ def test_9(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( - config=[dict(name="Ethernet1/3"), dict(name="Ethernet1/5")] + config=[dict(name="Ethernet1/3"), dict(name="Ethernet1/5")], ) # Expected result commands for each 'state' deleted = [ @@ -792,7 +787,7 @@ def test_10(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -874,7 +869,7 @@ def test_11(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ @@ -1019,14 +1014,14 @@ def test_12(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ dict( name="Vlan99", ipv4=[ - {"address": "192.168.1.1/24", "tag": 500} + {"address": "192.168.1.1/24", "tag": 500}, ], # adding a tag ), ], @@ -1052,7 +1047,7 @@ def test_12_gathered(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict(state="gathered") gathered_facts = [ @@ -1073,7 +1068,7 @@ def test_replaced_tag(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py index b3b9bf1c6..12d34e7ba 100644 --- a/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_lacp_interfaces.py @@ -47,16 +47,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.l3_interfaces.l3_interfaces.L3_interfaces.edit_config", @@ -89,7 +85,7 @@ def test_lacp_mode_parse(self): """, ) self.get_resource_connection_facts.return_value = { - self.SHOW_CMD: existing + self.SHOW_CMD: existing, } playbook = dict( config=[ diff --git a/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py index b2f8b222d..2b7e82067 100644 --- a/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_lldp_interfaces.py @@ -10,9 +10,7 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_lldp_interfaces from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( - set_module_args, -) +from ansible_collections.cisco.nxos.tests.unit.modules.utils import set_module_args from .nxos_module import TestNxosModule @@ -36,16 +34,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.lldp_interfaces.lldp_interfaces.Lldp_interfaces.edit_config", @@ -157,7 +151,7 @@ def test_nxos_lldp_interfaces_overridden(self): set_module_args( dict( config=[ - dict(name="Ethernet1/4", receive=True, transmit=False) + dict(name="Ethernet1/4", receive=True, transmit=False), ], state="overridden", ), @@ -193,7 +187,7 @@ def test_nxos_lldp_interfaces_overridden_idempotent(self): def test_nxos_lldp_interfaces_deleted_intf(self): set_module_args( - dict(config=[dict(name="Ethernet1/2")], state="deleted") + dict(config=[dict(name="Ethernet1/2")], state="deleted"), ) commands = [ "interface Ethernet1/2", @@ -238,7 +232,9 @@ def test_nxos_lldp_interfaces_rendered(self): ] result = self.execute_module(changed=False) self.assertEqual( - sorted(result["rendered"]), sorted(commands), result["rendered"] + sorted(result["rendered"]), + sorted(commands), + result["rendered"], ) def test_nxos_lldp_interfaces_parsed(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_logging_global.py b/tests/unit/modules/network/nxos/test_nxos_logging_global.py index a6d1cd1bf..e4b9e45c9 100644 --- a/tests/unit/modules/network/nxos/test_nxos_logging_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_logging_global.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.logging_global.logging_global.Logging_globalFacts.get_config", @@ -239,7 +237,9 @@ def test_nxos_logging_global_linear_merged_3(self): ip=dict( access_list=dict( cache=dict( - entries=16384, interval=200, threshold=80 + entries=16384, + interval=200, + threshold=80, ), detailed=True, include=dict(sgt=True), @@ -286,7 +286,9 @@ def test_nxos_logging_global_linear_merged_3_idempotent(self): ip=dict( access_list=dict( cache=dict( - entries=16384, interval=200, threshold=80 + entries=16384, + interval=200, + threshold=80, ), detailed=True, include=dict(sgt=True), @@ -322,8 +324,8 @@ def test_nxos_logging_global_linear_replaced_3(self): origin_id=dict(ip="192.168.1.1"), ip=dict( access_list=dict( - cache=dict(entries=16384, interval=210) - ) + cache=dict(entries=16384, interval=210), + ), ), source_interface="Ethernet1/120", ), @@ -531,7 +533,8 @@ def test_nxos_logging_global_event_replaced(self): def test_nxos_logging_global_gathered_empty(self): set_module_args( - dict(running_config="", state="gathered"), ignore_provider_arg + dict(running_config="", state="gathered"), + ignore_provider_arg, ) result = self.execute_module(changed=False) self.assertEqual(result["gathered"], {}) @@ -561,7 +564,7 @@ def test_nxos_logging_global_gathered(self): "rfc_strict": True, "origin_id": {"string": "nodeA"}, "facilities": [ - {"facility": "vlan_mgr", "severity": "notification"} + {"facility": "vlan_mgr", "severity": "notification"}, ], } result = self.execute_module(changed=False) @@ -582,7 +585,8 @@ def test_nxos_logging_global_parsed(self): """, ) set_module_args( - dict(running_config=cfg, state="parsed"), ignore_provider_arg + dict(running_config=cfg, state="parsed"), + ignore_provider_arg, ) parsed = { "console": {"severity": "alert"}, @@ -613,7 +617,7 @@ def test_nxos_logging_global_hosts_merged(self): port=5891, use_vrf="default", secure=dict( - trustpoint=dict(client_identity="test") + trustpoint=dict(client_identity="test"), ), ), dict(host="192.168.1.2"), @@ -652,7 +656,7 @@ def test_nxos_logging_global_hosts_replaced(self): port=5891, use_vrf="default", secure=dict( - trustpoint=dict(client_identity="test") + trustpoint=dict(client_identity="test"), ), ), dict( @@ -740,7 +744,7 @@ def test_nxos_logging_global_event_replaced_2(self): set_module_args( dict( config=dict( - event=dict(trunk_status=dict(enable=False, default=True)) + event=dict(trunk_status=dict(enable=False, default=True)), ), state="replaced", ), diff --git a/tests/unit/modules/network/nxos/test_nxos_ntp_global.py b/tests/unit/modules/network/nxos/test_nxos_ntp_global.py index dd05f62e8..3b81598d1 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ntp_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_ntp_global.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ntp_global.ntp_global.Ntp_globalFacts.get_config", @@ -329,7 +327,9 @@ def test_nxos_ntp_global_complex_2_merged(self): ), dict(peer="192.168.1.2", key_id=3, use_vrf="siteB"), dict( - peer="192.168.1.3", maxpoll=10, use_vrf="default" + peer="192.168.1.3", + maxpoll=10, + use_vrf="default", ), ], servers=[ @@ -343,7 +343,9 @@ def test_nxos_ntp_global_complex_2_merged(self): ), dict(server="203.0.113.2", key_id=3, use_vrf="siteB"), dict( - server="203.0.113.3", maxpoll=10, use_vrf="default" + server="203.0.113.3", + maxpoll=10, + use_vrf="default", ), ], ), @@ -567,7 +569,8 @@ def test_nxos_ntp_global_complex_3_replaced(self): def test_nxos_ntp_global_gathered_empty(self): set_module_args( - dict(running_config="", state="gathered"), ignore_provider_arg + dict(running_config="", state="gathered"), + ignore_provider_arg, ) result = self.execute_module(changed=False) self.assertEqual(result["gathered"], {}) @@ -603,7 +606,8 @@ def test_nxos_ntp_global_parsed(self): """, ) set_module_args( - dict(running_config=cfg, state="parsed"), ignore_provider_arg + dict(running_config=cfg, state="parsed"), + ignore_provider_arg, ) parsed = { "trusted_keys": [ diff --git a/tests/unit/modules/network/nxos/test_nxos_nxapi.py b/tests/unit/modules/network/nxos/test_nxos_nxapi.py index e9f8e8b6c..cbdadeef9 100644 --- a/tests/unit/modules/network/nxos/test_nxos_nxapi.py +++ b/tests/unit/modules/network/nxos/test_nxos_nxapi.py @@ -91,7 +91,8 @@ def test_nxos_nxapi_no_change(self): def test_nxos_nxapi_disable(self): set_module_args(dict(state="absent")) self.execute_module_devices( - changed=True, commands=["no feature nxapi"] + changed=True, + commands=["no feature nxapi"], ) def test_nxos_nxapi_no_http(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py b/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py index c89edc747..e3b053f5c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py +++ b/tests/unit/modules/network/nxos/test_nxos_ospf_interfaces.py @@ -50,9 +50,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ospf_interfaces.ospf_interfaces.Ospf_interfacesFacts.get_config", @@ -400,17 +398,19 @@ def test_nxos_ospf_interfaces_af_multiareas_merged(self): name="Ethernet1/1", address_family=[ dict( - afi="ipv4", multi_areas=["1.1.1.1", "1.1.1.3"] + afi="ipv4", + multi_areas=["1.1.1.1", "1.1.1.3"], ), dict( - afi="ipv6", multi_areas=["3.3.3.3", "4.4.4.4"] + afi="ipv6", + multi_areas=["3.3.3.3", "4.4.4.4"], ), ], ), dict( name="Ethernet1/2", address_family=[ - dict(afi="ipv6", multi_areas=["5.5.5.6"]) + dict(afi="ipv6", multi_areas=["5.5.5.6"]), ], ), ], @@ -455,10 +455,12 @@ def test_nxos_ospf_interfaces_af_multiareas_replaced(self): name="Ethernet1/1", address_family=[ dict( - afi="ipv4", multi_areas=["1.1.1.1", "1.1.1.3"] + afi="ipv4", + multi_areas=["1.1.1.1", "1.1.1.3"], ), dict( - afi="ipv6", multi_areas=["3.3.3.3", "4.4.4.4"] + afi="ipv6", + multi_areas=["3.3.3.3", "4.4.4.4"], ), ], ), @@ -508,7 +510,8 @@ def test_nxos_ospf_interfaces_authentication_merged(self): dict( afi="ipv4", authentication=dict( - key_chain="test-1", message_digest=True + key_chain="test-1", + message_digest=True, ), ), ], @@ -517,20 +520,21 @@ def test_nxos_ospf_interfaces_authentication_merged(self): name="Ethernet1/2", address_family=[ dict( - afi="ipv4", authentication=dict(null_auth=True) - ) + afi="ipv4", + authentication=dict(null_auth=True), + ), ], ), dict( name="Ethernet1/3", address_family=[ - dict(afi="ipv4", authentication=dict(enable=True)) + dict(afi="ipv4", authentication=dict(enable=True)), ], ), dict( name="Ethernet1/4", address_family=[ - dict(afi="ipv4", authentication=dict(enable=False)) + dict(afi="ipv4", authentication=dict(enable=False)), ], ), ], @@ -577,14 +581,15 @@ def test_nxos_ospf_interfaces_authentication_replaced(self): name="Ethernet1/2", address_family=[ dict( - afi="ipv4", authentication=dict(null_auth=True) - ) + afi="ipv4", + authentication=dict(null_auth=True), + ), ], ), dict( name="Ethernet1/3", address_family=[ - dict(afi="ipv4", authentication=dict(enable=True)) + dict(afi="ipv4", authentication=dict(enable=True)), ], ), ], @@ -629,7 +634,8 @@ def test_nxos_ospf_interfaces_authentication_key_merged(self): dict( afi="ipv4", authentication_key=dict( - encryption=3, key="77840f9d4d882176" + encryption=3, + key="77840f9d4d882176", ), ), ], @@ -640,7 +646,8 @@ def test_nxos_ospf_interfaces_authentication_key_merged(self): dict( afi="ipv4", authentication_key=dict( - encryption=0, key="password" + encryption=0, + key="password", ), ), ], @@ -651,7 +658,8 @@ def test_nxos_ospf_interfaces_authentication_key_merged(self): dict( afi="ipv4", authentication_key=dict( - encryption=7, key="712090404011C031628" + encryption=7, + key="712090404011C031628", ), ), ], @@ -699,7 +707,8 @@ def test_nxos_ospf_interfaces_authentication_key_replaced(self): dict( afi="ipv4", authentication_key=dict( - encryption=0, key="password" + encryption=0, + key="password", ), ), ], @@ -756,7 +765,9 @@ def test_nxos_ospf_interfaces_message_digest_key_merged(self): dict( afi="ipv4", message_digest_key=dict( - key_id=1, encryption=0, key="password" + key_id=1, + encryption=0, + key="password", ), ), ], @@ -817,7 +828,9 @@ def test_nxos_ospf_interfaces_message_digest_key_replaced(self): dict( afi="ipv4", message_digest_key=dict( - key_id=1, encryption=0, key="password1" + key_id=1, + encryption=0, + key="password1", ), ), ], @@ -932,13 +945,13 @@ def test_nxos_ospf_interfaces_linear_args_1_replaced(self): dict( name="Ethernet1/1", address_family=[ - dict(afi="ipv4", cost=200, hello_interval=9000) + dict(afi="ipv4", cost=200, hello_interval=9000), ], ), dict( name="Ethernet1/2", address_family=[ - dict(afi="ipv6", cost=180, dead_interval=3000) + dict(afi="ipv6", cost=180, dead_interval=3000), ], ), ], @@ -1225,7 +1238,9 @@ def test_nxos_ospf_interfaces_linear_args_4_merged(self): name="Ethernet1/1", address_family=[ dict( - afi="ipv4", shutdown=False, transmit_delay=210 + afi="ipv4", + shutdown=False, + transmit_delay=210, ), dict(afi="ipv6", shutdown=True), ], @@ -1241,10 +1256,14 @@ def test_nxos_ospf_interfaces_linear_args_4_merged(self): name="Ethernet1/3", address_family=[ dict( - afi="ipv4", shutdown=True, transmit_delay=430 + afi="ipv4", + shutdown=True, + transmit_delay=430, ), dict( - afi="ipv6", shutdown=True, transmit_delay=120 + afi="ipv6", + shutdown=True, + transmit_delay=120, ), ], ), @@ -1371,7 +1390,7 @@ def test_nxos_ospf_interfaces_parsed(self): { "afi": "ipv6", "processes": [ - {"process_id": "210", "multi_areas": ["3.3.3.3"]} + {"process_id": "210", "multi_areas": ["3.3.3.3"]}, ], }, ], @@ -1433,7 +1452,7 @@ def test_nxos_ospf_interfaces_gathered(self): { "afi": "ipv6", "processes": [ - {"process_id": "210", "multi_areas": ["3.3.3.3"]} + {"process_id": "210", "multi_areas": ["3.3.3.3"]}, ], }, ], @@ -1481,7 +1500,9 @@ def test_nxos_ospf_interfaces_overridden(self): name="Ethernet1/1", address_family=[ dict( - afi="ipv4", shutdown=False, transmit_delay=300 + afi="ipv4", + shutdown=False, + transmit_delay=300, ), dict(afi="ipv6", shutdown=True), ], @@ -1599,19 +1620,19 @@ def test_nxos_ospf_interfaces_passive_intf(self): dict( name="Ethernet1/2", address_family=[ - dict(afi="ipv4", default_passive_interface=True) + dict(afi="ipv4", default_passive_interface=True), ], ), dict( name="Ethernet1/3", address_family=[ - dict(afi="ipv6", default_passive_interface=True) + dict(afi="ipv6", default_passive_interface=True), ], ), dict( name="Ethernet1/4", address_family=[ - dict(afi="ipv4", default_passive_interface=True) + dict(afi="ipv4", default_passive_interface=True), ], ), ], diff --git a/tests/unit/modules/network/nxos/test_nxos_ospfv2.py b/tests/unit/modules/network/nxos/test_nxos_ospfv2.py index db3ca64d7..aa38c9eb1 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ospfv2.py +++ b/tests/unit/modules/network/nxos/test_nxos_ospfv2.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ospfv2.ospfv2.Ospfv2Facts.get_config", @@ -85,10 +83,12 @@ def test_nxos_ospfv2_merged(self): area_id="0.0.0.100", filter_list=[ dict( - route_map="rmap_1", direction="in" + route_map="rmap_1", + direction="in", ), dict( - route_map="rmap_2", direction="out" + route_map="rmap_2", + direction="out", ), ], ranges=[ @@ -168,10 +168,12 @@ def test_nxos_ospfv2_merged_idempotent(self): area_id="0.0.0.100", filter_list=[ dict( - route_map="rmap_1", direction="in" + route_map="rmap_1", + direction="in", ), dict( - route_map="rmap_2", direction="out" + route_map="rmap_2", + direction="out", ), ], ranges=[ @@ -335,10 +337,12 @@ def test_nxos_ospfv2_replaced_idempotent(self): area_id="0.0.0.100", filter_list=[ dict( - route_map="rmap_1", direction="in" + route_map="rmap_1", + direction="in", ), dict( - route_map="rmap_2", direction="out" + route_map="rmap_2", + direction="out", ), ], ranges=[ @@ -381,8 +385,8 @@ def test_nxos_ospfv2_overridden(self): dict( config=dict( processes=[ - dict(process_id="300", router_id="203.0.113.20") - ] + dict(process_id="300", router_id="203.0.113.20"), + ], ), state="overridden", ), @@ -440,10 +444,12 @@ def test_nxos_ospfv2_overridden_idempotent(self): area_id="0.0.0.100", filter_list=[ dict( - route_map="rmap_1", direction="in" + route_map="rmap_1", + direction="in", ), dict( - route_map="rmap_2", direction="out" + route_map="rmap_2", + direction="out", ), ], ranges=[ @@ -487,7 +493,7 @@ def test_nxos_ospfv2_deleted(self): set_module_args( dict( config=dict( - processes=[dict(process_id="100"), dict(process_id="300")] + processes=[dict(process_id="100"), dict(process_id="300")], ), state="deleted", ), @@ -519,7 +525,7 @@ def test_nxos_ospfv2_deleted_idempotent(self): set_module_args( dict( config=dict( - processes=[dict(process_id="400"), dict(process_id="500")] + processes=[dict(process_id="400"), dict(process_id="500")], ), state="deleted", ), diff --git a/tests/unit/modules/network/nxos/test_nxos_ospfv3.py b/tests/unit/modules/network/nxos/test_nxos_ospfv3.py index 8f90dd9a6..3b6511784 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ospfv3.py +++ b/tests/unit/modules/network/nxos/test_nxos_ospfv3.py @@ -53,9 +53,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.ospfv3.ospfv3.Ospfv3Facts.get_config", @@ -234,7 +232,8 @@ def test_nxos_ospfv3_af_areas_ranges_merged(self): area_id="1.1.1.2", ranges=[ dict( - prefix="2001:db4::/32", cost=11 + prefix="2001:db4::/32", + cost=11, ), dict( prefix="2001:db5::/32", @@ -291,7 +290,8 @@ def test_nxos_ospfv3_af_areas_ranges_replaced(self): area_id="1.1.1.2", ranges=[ dict( - prefix="2001:db4::/32", cost=11 + prefix="2001:db4::/32", + cost=11, ), dict( prefix="2001:db5::/32", @@ -383,7 +383,7 @@ def test_nxos_ospfv3_af_areas_default_cost_replaced(self): afi="ipv6", safi="unicast", areas=[ - dict(area_id="1.1.1.2", default_cost=200) + dict(area_id="1.1.1.2", default_cost=200), ], ), ), @@ -422,7 +422,8 @@ def test_nxos_ospfv3_af_default_information_merged(self): safi="unicast", default_information=dict( originate=dict( - always=True, route_map="test-2" + always=True, + route_map="test-2", ), ), ), @@ -460,7 +461,7 @@ def test_nxos_ospfv3_af_default_information_merged_2(self): afi="ipv6", safi="unicast", default_information=dict( - originate=dict(set=False) + originate=dict(set=False), ), ), ), @@ -497,7 +498,7 @@ def test_nxos_ospfv3_af_default_information_replaced(self): afi="ipv6", safi="unicast", default_information=dict( - originate=dict(set=True) + originate=dict(set=True), ), ), ), @@ -531,7 +532,9 @@ def test_nxos_ospfv3_af_distance_merged(self): dict( process_id="100", address_family=dict( - afi="ipv6", safi="unicast", distance=35 + afi="ipv6", + safi="unicast", + distance=35, ), ), ], @@ -597,7 +600,9 @@ def test_nxos_ospfv3_af_maximum_paths_merged(self): dict( process_id="100", address_family=dict( - afi="ipv6", safi="unicast", maximum_paths=27 + afi="ipv6", + safi="unicast", + maximum_paths=27, ), ), ], @@ -682,7 +687,8 @@ def test_nxos_ospfv3_af_redistribute_merged(self): route_map="test-3", ), dict( - protocol="static", route_map="test-4" + protocol="static", + route_map="test-4", ), ], ), @@ -734,7 +740,8 @@ def test_nxos_ospfv3_af_redistribute_replaced(self): route_map="test-3", ), dict( - protocol="static", route_map="test-4" + protocol="static", + route_map="test-4", ), ], ), @@ -1013,8 +1020,9 @@ def test_nxos_ospfv3_areas_nssa_merged(self): route_map="test-1", translate=dict( type7=dict( - always=True, supress_fa=True - ) + always=True, + supress_fa=True, + ), ), ), ), @@ -1051,7 +1059,7 @@ def test_nxos_ospfv3_areas_nssa_merged_2(self): dict( process_id="100", areas=[ - dict(area_id="1.1.1.1", nssa=dict(set=False)) + dict(area_id="1.1.1.1", nssa=dict(set=False)), ], ), ], @@ -1185,8 +1193,8 @@ def test_nxos_ospfv3_areas_stub_replaced(self): dict( config=dict( processes=[ - dict(process_id="100", areas=[dict(area_id="1.1.1.3")]) - ] + dict(process_id="100", areas=[dict(area_id="1.1.1.3")]), + ], ), state="replaced", ), @@ -1211,7 +1219,8 @@ def test_nxos_ospfv3_autocost_flush_route_isolate_merged(self): dict( process_id="100", auto_cost=dict( - reference_bandwidth=100, unit="Gbps" + reference_bandwidth=100, + unit="Gbps", ), flush_routes=True, isolate=True, @@ -1446,7 +1455,8 @@ def test_nxos_ospfv3_graceful_restart_merged(self): dict( process_id="100", graceful_restart=dict( - grace_period=50, helper_disable=True + grace_period=50, + helper_disable=True, ), ), dict( @@ -1534,8 +1544,8 @@ def test_nxos_ospfv3_max_metric_merged(self): max_metric=dict( router_lsa=dict( inter_area_prefix_lsa=dict( - max_metric_value=1800 - ) + max_metric_value=1800, + ), ), ), ), @@ -1782,7 +1792,7 @@ def test_nxos_ospfv3_vrf_merged(self): wait_for_bgp_asn=65563, ), inter_area_prefix_lsa=dict( - set=True + set=True, ), ), ), @@ -2163,7 +2173,7 @@ def test_nxos_ospfv3_parsed(self): { "vrf": "red", "areas": [ - {"area_id": "1.1.1.1", "nssa": {"set": True}} + {"area_id": "1.1.1.1", "nssa": {"set": True}}, ], }, ], @@ -2216,7 +2226,7 @@ def test_nxos_ospfv3_gathered(self): { "vrf": "red", "areas": [ - {"area_id": "1.1.1.1", "nssa": {"set": True}} + {"area_id": "1.1.1.1", "nssa": {"set": True}}, ], }, ], diff --git a/tests/unit/modules/network/nxos/test_nxos_overlay_global.py b/tests/unit/modules/network/nxos/test_nxos_overlay_global.py index f464094bc..4b29ba34b 100644 --- a/tests/unit/modules/network/nxos/test_nxos_overlay_global.py +++ b/tests/unit/modules/network/nxos/test_nxos_overlay_global.py @@ -50,7 +50,8 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "", "nxos_overlay_global_config.cfg" + "", + "nxos_overlay_global_config.cfg", ) self.load_config.return_value = None diff --git a/tests/unit/modules/network/nxos/test_nxos_pim.py b/tests/unit/modules/network/nxos/test_nxos_pim.py index 8ef0a7360..871cba316 100644 --- a/tests/unit/modules/network/nxos/test_nxos_pim.py +++ b/tests/unit/modules/network/nxos/test_nxos_pim.py @@ -57,7 +57,8 @@ def test_nxos_pim_1(self): self.get_config.return_value = load_fixture("nxos_pim", "config.cfg") set_module_args(dict(ssm_range="233.0.0.0/8")) self.execute_module( - changed=True, commands=["ip pim ssm range 233.0.0.0/8"] + changed=True, + commands=["ip pim ssm range 233.0.0.0/8"], ) def test_nxos_pim_2(self): @@ -65,7 +66,8 @@ def test_nxos_pim_2(self): self.get_config.return_value = load_fixture("nxos_pim", "config.cfg") set_module_args(dict(bfd="disable", ssm_range="none")) self.execute_module( - changed=True, commands=["no ip pim bfd", "ip pim ssm range none"] + changed=True, + commands=["no ip pim bfd", "ip pim ssm range none"], ) def test_nxos_pim_3(self): @@ -93,7 +95,8 @@ def test_nxos_pim_5(self): self.get_config.return_value = load_fixture("nxos_pim", "config.cfg") set_module_args(dict(ssm_range="default")) self.execute_module( - changed=True, commands=["no ip pim ssm range none"] + changed=True, + commands=["no ip pim ssm range none"], ) # SSM 'default' idempotence diff --git a/tests/unit/modules/network/nxos/test_nxos_pim_interface.py b/tests/unit/modules/network/nxos/test_nxos_pim_interface.py index 54dcac3ce..b70548281 100644 --- a/tests/unit/modules/network/nxos/test_nxos_pim_interface.py +++ b/tests/unit/modules/network/nxos/test_nxos_pim_interface.py @@ -65,12 +65,7 @@ def load_from_file(*args, **kwargs): for command in commands: if isinstance(command, dict): command = command["command"] - filename = ( - str(command) - .split(" | ", 1)[0] - .replace(" ", "_") - .replace("/", "_") - ) + filename = str(command).split(" | ", 1)[0].replace(" ", "_").replace("/", "_") output.append(load_fixture(module_name, filename)) return output @@ -167,7 +162,8 @@ def test_bfd_1(self): self.get_config.return_value = None set_module_args(dict(interface="eth2/1", bfd="enable")) self.execute_module( - changed=True, commands=["interface eth2/1", "ip pim bfd-instance"] + changed=True, + commands=["interface eth2/1", "ip pim bfd-instance"], ) # default (None) -> disable diff --git a/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py b/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py index 2e30bf402..fc936319a 100644 --- a/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py +++ b/tests/unit/modules/network/nxos/test_nxos_pim_rp_address.py @@ -51,14 +51,16 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "nxos_pim_rp_address", "config.cfg" + "nxos_pim_rp_address", + "config.cfg", ) self.load_config.return_value = None def test_nxos_pim_rp_address(self): set_module_args(dict(rp_address="5.6.7.8")) self.execute_module( - changed=True, commands=["ip pim rp-address 5.6.7.8"] + changed=True, + commands=["ip pim rp-address 5.6.7.8"], ) def test_nxos_pim_rp_address_no_change(self): @@ -68,7 +70,8 @@ def test_nxos_pim_rp_address_no_change(self): def test_nxos_pim_rp_address_absent(self): set_module_args(dict(rp_address="1.2.3.4", state="absent")) self.execute_module( - changed=True, commands=["no ip pim rp-address 1.2.3.4"] + changed=True, + commands=["no ip pim rp-address 1.2.3.4"], ) def test_nxos_pim_rp_address_absent_no_change(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_ping.py b/tests/unit/modules/network/nxos/test_nxos_ping.py index 49eaf7051..8fe894a4f 100644 --- a/tests/unit/modules/network/nxos/test_nxos_ping.py +++ b/tests/unit/modules/network/nxos/test_nxos_ping.py @@ -65,7 +65,8 @@ def test_nxos_ping_expected_success(self): set_module_args(dict(dest="172.28.128.7", vrf="management")) result = self.execute_module() self.assertEqual( - result["commands"], ["ping 172.28.128.7 count 5 vrf management"] + result["commands"], + ["ping 172.28.128.7 count 5 vrf management"], ) self.assertEqual(result["packet_loss"], "0.00%") self.assertEqual(result["packets_rx"], 5) @@ -89,7 +90,7 @@ def test_nxos_ping_expected_failure(self): """, ] set_module_args( - dict(dest="172.28.128.8", vrf="management", state="absent") + dict(dest="172.28.128.8", vrf="management", state="absent"), ) self.execute_module(failed=False) @@ -127,7 +128,7 @@ def test_nxos_ping_expected_failure_but_succeeded(self): """, ] set_module_args( - dict(dest="172.28.128.7", vrf="management", state="absent") + dict(dest="172.28.128.7", vrf="management", state="absent"), ) result = self.execute_module(failed=True) self.assertEqual(result["msg"], "Ping succeeded unexpectedly") @@ -178,7 +179,8 @@ def test_nxos_ping_expected_success_df_bit(self): set_module_args(dict(dest="172.28.128.7", df_bit=True)) result = self.execute_module() self.assertEqual( - result["commands"], ["ping 172.28.128.7 count 5 df-bit"] + result["commands"], + ["ping 172.28.128.7 count 5 df-bit"], ) def test_nxos_ping_expected_success_size(self): @@ -199,7 +201,8 @@ def test_nxos_ping_expected_success_size(self): set_module_args(dict(dest="172.28.128.7", size=65468)) result = self.execute_module() self.assertEqual( - result["commands"], ["ping 172.28.128.7 count 5 packet-size 65468"] + result["commands"], + ["ping 172.28.128.7 count 5 packet-size 65468"], ) def test_nxos_ping_expected_success_all(self): @@ -270,5 +273,6 @@ def test_nxos_ping_failed_error(self): set_module_args(dict(dest="172.28.128.7", count=10, vrf="site-1")) result = self.execute_module(failed=True) self.assertEqual( - result["msg"], "An unexpected error occurred. Check all params." + result["msg"], + "An unexpected error occurred. Check all params.", ) diff --git a/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py b/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py index 6414e048f..d63a67005 100644 --- a/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py +++ b/tests/unit/modules/network/nxos/test_nxos_prefix_lists.py @@ -53,9 +53,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.prefix_lists.prefix_lists.Prefix_listsFacts.get_config", @@ -560,19 +558,20 @@ def test_nxos_prefix_lists_parsed(self): """, ) set_module_args( - dict(running_config=cfg, state="parsed"), ignore_provider_arg + dict(running_config=cfg, state="parsed"), + ignore_provider_arg, ) parsed = [ { "afi": "ipv4", "prefix_lists": [ - {"name": "plist1", "description": "Test plist1"} + {"name": "plist1", "description": "Test plist1"}, ], }, { "afi": "ipv6", "prefix_lists": [ - {"name": "plist3", "description": "Test plist3"} + {"name": "plist3", "description": "Test plist3"}, ], }, ] diff --git a/tests/unit/modules/network/nxos/test_nxos_route_maps.py b/tests/unit/modules/network/nxos/test_nxos_route_maps.py index 8441d06bc..1b018455f 100644 --- a/tests/unit/modules/network/nxos/test_nxos_route_maps.py +++ b/tests/unit/modules/network/nxos/test_nxos_route_maps.py @@ -53,9 +53,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.route_maps.route_maps.Route_mapsFacts.get_config", @@ -91,7 +89,8 @@ def test_nxos_route_maps_linear_merged(self): description="rmap1-deny-40", set=dict( as_path=dict( - prepend=dict(last_as=10), tag=True + prepend=dict(last_as=10), + tag=True, ), comm_list="comm1", dampening=dict( @@ -116,13 +115,13 @@ def test_nxos_route_maps_linear_merged(self): null_interface="null0", ip=dict( address=dict( - prefix_list="prefixlist1" + prefix_list="prefixlist1", ), precedence="critical", ), ipv6=dict( address=dict( - prefix_list="prefixlist2" + prefix_list="prefixlist2", ), precedence="immediate", ), @@ -235,7 +234,8 @@ def test_nxos_route_maps_linear_merged_idempotent(self): description="rmap1-deny-40", set=dict( as_path=dict( - prepend=dict(last_as=10), tag=True + prepend=dict(last_as=10), + tag=True, ), comm_list="comm1", dampening=dict( @@ -260,13 +260,13 @@ def test_nxos_route_maps_linear_merged_idempotent(self): null_interface="null0", ip=dict( address=dict( - prefix_list="prefixlist1" + prefix_list="prefixlist1", ), precedence="critical", ), ipv6=dict( address=dict( - prefix_list="prefixlist2" + prefix_list="prefixlist2", ), precedence="immediate", ), @@ -366,7 +366,7 @@ def test_nxos_route_maps_linear_replaced(self): set=dict( ip=dict( address=dict( - prefix_list="prefixlist1" + prefix_list="prefixlist1", ), precedence="critical", ), @@ -439,7 +439,7 @@ def test_nxos_route_maps_parsed(self): sequence=40, description="rmap1-deny-40", set=dict( - as_path=dict(prepend=dict(last_as=10), tag=True) + as_path=dict(prepend=dict(last_as=10), tag=True), ), ), ], @@ -507,7 +507,7 @@ def test_nxos_route_maps_gathered(self): sequence=40, description="rmap1-deny-40", set=dict( - as_path=dict(prepend=dict(last_as=10), tag=True) + as_path=dict(prepend=dict(last_as=10), tag=True), ), ), ], @@ -572,7 +572,7 @@ def test_nxos_route_maps_rendered(self): set=dict( ip=dict( address=dict( - prefix_list="prefixlist1" + prefix_list="prefixlist1", ), precedence="critical", ), @@ -641,7 +641,7 @@ def test_nxos_route_maps_overridden(self): set=dict( ipv6=dict( address=dict( - prefix_list="prefixlist2" + prefix_list="prefixlist2", ), precedence="immediate", ), @@ -767,7 +767,7 @@ def test_nxos_route_maps_complex_merged(self): ), as_path=["65565", "65578", "65590"], community=dict( - community_list=["comm1", "comm2"] + community_list=["comm1", "comm2"], ), evpn=dict(route_types=["1", "2-mac-ip"]), extcommunity=dict( @@ -791,10 +791,10 @@ def test_nxos_route_maps_complex_merged(self): source="192.168.1.0/24", ), next_hop=dict( - prefix_lists=["pl1", "pl2"] + prefix_lists=["pl1", "pl2"], ), route_source=dict( - prefix_lists=["pl3", "pl4"] + prefix_lists=["pl3", "pl4"], ), ), mac_list=["mac1", "mac2"], @@ -823,10 +823,10 @@ def test_nxos_route_maps_complex_merged(self): source="192.168.1.0/24", ), next_hop=dict( - prefix_lists=["pl1", "pl2"] + prefix_lists=["pl1", "pl2"], ), route_source=dict( - prefix_lists=["pl3", "pl4"] + prefix_lists=["pl3", "pl4"], ), ), ), @@ -837,8 +837,8 @@ def test_nxos_route_maps_complex_merged(self): set=dict( as_path=dict( prepend=dict( - as_number=["65546", "78878"] - ) + as_number=["65546", "78878"], + ), ), distance=dict( igp_ebgp_routes=10, @@ -846,7 +846,7 @@ def test_nxos_route_maps_complex_merged(self): local_routes=90, ), evpn=dict( - gateway_ip=dict(ip="192.168.1.1") + gateway_ip=dict(ip="192.168.1.1"), ), ), ), @@ -855,7 +855,7 @@ def test_nxos_route_maps_complex_merged(self): action="permit", set=dict( evpn=dict( - gateway_ip=dict(use_nexthop=True) + gateway_ip=dict(use_nexthop=True), ), community=dict( internet=True, diff --git a/tests/unit/modules/network/nxos/test_nxos_snmp_server.py b/tests/unit/modules/network/nxos/test_nxos_snmp_server.py index 0d49757f2..be0fdfafd 100644 --- a/tests/unit/modules/network/nxos/test_nxos_snmp_server.py +++ b/tests/unit/modules/network/nxos/test_nxos_snmp_server.py @@ -42,9 +42,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_get_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.snmp_server.snmp_server.Snmp_serverFacts.get_config", @@ -71,7 +69,7 @@ def test_nxos_snmp_server_linear_merged(self): counter=dict(cache=dict(timeout=1800)), drop=dict(unknown_engine_id=True, unknown_user=True), engine_id=dict( - local="'00:00:00:63:00:01:00:10:20:15:10:03'" + local="'00:00:00:63:00:01:00:10:20:15:10:03'", ), communities=[ dict(name="private", group="network-admin"), @@ -81,13 +79,15 @@ def test_nxos_snmp_server_linear_merged(self): location="lab", mib=dict( community_map=dict( - community="public", context="public1" - ) + community="public", + context="public1", + ), ), packetsize=484, protocol=dict(enable=True), source_interface=dict( - informs="Ethernet1/1", traps="Ethernet1/2" + informs="Ethernet1/1", + traps="Ethernet1/2", ), system_shutdown=True, tcp_session=dict(auth=True), @@ -150,19 +150,21 @@ def test_nxos_snmp_server_linear_merged_idempotent(self): counter=dict(cache=dict(timeout=1800)), drop=dict(unknown_engine_id=True, unknown_user=True), engine_id=dict( - local="00:00:00:63:00:01:00:10:20:15:10:03" + local="00:00:00:63:00:01:00:10:20:15:10:03", ), global_enforce_priv=True, location="lab", mib=dict( community_map=dict( - community="public", context="public1" - ) + community="public", + context="public1", + ), ), packetsize=484, protocol=dict(enable=True), source_interface=dict( - informs="Ethernet1/1", traps="Ethernet1/2" + informs="Ethernet1/1", + traps="Ethernet1/2", ), system_shutdown=True, tcp_session=dict(auth=True), @@ -204,19 +206,21 @@ def test_nxos_snmp_server_linear_replaced(self): context=dict(name="public", vrf="siteA"), counter=dict(cache=dict(timeout=1860)), engine_id=dict( - local="00:00:00:63:00:01:00:10:20:15:10:03" + local="00:00:00:63:00:01:00:10:20:15:10:03", ), global_enforce_priv=True, location="lab", mib=dict( community_map=dict( - community="public", context="public1" - ) + community="public", + context="public1", + ), ), packetsize=484, protocol=dict(enable=True), source_interface=dict( - informs="Ethernet1/3", traps="Ethernet1/2" + informs="Ethernet1/3", + traps="Ethernet1/2", ), tcp_session=dict(auth=True), ), @@ -265,19 +269,21 @@ def test_nxos_snmp_server_linear_overridden(self): context=dict(name="public", vrf="siteA"), counter=dict(cache=dict(timeout=1860)), engine_id=dict( - local="00:00:00:63:00:01:00:10:20:15:10:03" + local="00:00:00:63:00:01:00:10:20:15:10:03", ), global_enforce_priv=True, location="lab", mib=dict( community_map=dict( - community="public", context="public1" - ) + community="public", + context="public1", + ), ), packetsize=484, protocol=dict(enable=True), source_interface=dict( - informs="Ethernet1/3", traps="Ethernet1/2" + informs="Ethernet1/3", + traps="Ethernet1/2", ), tcp_session=dict(auth=True), ), @@ -474,7 +480,8 @@ def test_nxos_snmp_server_hosts_merged(self): traps=True, ), dict( - host="192.168.1.1", source_interface="Ethernet1/1" + host="192.168.1.1", + source_interface="Ethernet1/1", ), dict( host="192.168.2.1", @@ -541,7 +548,8 @@ def test_nxos_snmp_server_hosts_merged(self): traps=True, ), dict( - host="192.168.1.1", source_interface="Ethernet1/1" + host="192.168.1.1", + source_interface="Ethernet1/1", ), dict( host="192.168.2.1", @@ -600,7 +608,8 @@ def test_nxos_snmp_server_hosts_replaced(self): traps=True, ), dict( - host="192.168.1.1", source_interface="Ethernet1/1" + host="192.168.1.1", + source_interface="Ethernet1/1", ), dict( host="192.168.2.1", @@ -746,7 +755,7 @@ def test_nxos_snmp_server_users_merged(self): password="0x5632724fb8ac3699296af262", engine_id="2:2:2:2:2", priv=dict( - privacy_password="0x5632724fb8ac3699296af262" + privacy_password="0x5632724fb8ac3699296af262", ), localizedv2_key=True, ), @@ -926,7 +935,9 @@ def test_nxos_snmp_server_parsed(self): communities=[ dict(name="private", group="network-admin"), dict( - name="public", use_ipv4acl="myacl", use_ipv6acl="myaclv6" + name="public", + use_ipv4acl="myacl", + use_ipv6acl="myaclv6", ), ], context=dict(name="public", vrf="siteA"), @@ -936,7 +947,7 @@ def test_nxos_snmp_server_parsed(self): global_enforce_priv=True, location="lab", mib=dict( - community_map=dict(community="public", context="public1") + community_map=dict(community="public", context="public1"), ), packetsize=484, protocol=dict(enable=True), @@ -953,7 +964,7 @@ def test_nxos_snmp_server_parsed(self): password="0x7d425fbf09417c44bca69e1d9e9ce889", localized_key=True, priv=dict( - privacy_password="0x7d425fbf09417c44bca69e1d9e9ce889" + privacy_password="0x7d425fbf09417c44bca69e1d9e9ce889", ), ), ), @@ -991,19 +1002,21 @@ def test_nxos_snmp_server_rendered(self): ], drop=dict(unknown_engine_id=True, unknown_user=True), engine_id=dict( - local="'00:00:00:63:00:01:00:10:20:15:10:03'" + local="'00:00:00:63:00:01:00:10:20:15:10:03'", ), global_enforce_priv=True, location="lab", mib=dict( community_map=dict( - community="public", context="public1" - ) + community="public", + context="public1", + ), ), packetsize=484, protocol=dict(enable=True), source_interface=dict( - informs="Ethernet1/1", traps="Ethernet1/2" + informs="Ethernet1/1", + traps="Ethernet1/2", ), system_shutdown=True, tcp_session=dict(auth=True), @@ -1069,7 +1082,7 @@ def test_nxos_snmp_server_gathered(self): global_enforce_priv=True, location="lab", mib=dict( - community_map=dict(community="public", context="public1") + community_map=dict(community="public", context="public1"), ), packetsize=484, protocol=dict(enable=True), diff --git a/tests/unit/modules/network/nxos/test_nxos_static_routes.py b/tests/unit/modules/network/nxos/test_nxos_static_routes.py index 0c9505b6b..4d210a1ac 100644 --- a/tests/unit/modules/network/nxos/test_nxos_static_routes.py +++ b/tests/unit/modules/network/nxos/test_nxos_static_routes.py @@ -28,9 +28,7 @@ def setUp(self): self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) - self.get_resource_connection = ( - self.mock_get_resource_connection.start() - ) + self.get_resource_connection = self.mock_get_resource_connection.start() self.mock_execute_show_command = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.facts.static_routes.static_routes.Static_routesFacts.get_static_routes_data", @@ -96,7 +94,7 @@ def test_nxos_static_routes_all_idempotent(self): { "forward_router_address": "192.0.2.26", "tag": 12, - } + }, ], "dest": "192.0.2.80/28", }, @@ -132,7 +130,7 @@ def test_nxos_static_routes_all_idempotent(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.168.255.1"} + {"forward_router_address": "192.168.255.1"}, ], "dest": "0.0.0.0/0", }, @@ -300,7 +298,7 @@ def test_nxos_static_routes_merged(self): { "next_hops": [ { - "forward_router_address": "192.0.2.13" + "forward_router_address": "192.0.2.13", }, { "forward_router_address": "192.0.2.14", @@ -322,8 +320,8 @@ def test_nxos_static_routes_merged(self): { "next_hops": [ { - "forward_router_address": "192.168.255.1" - } + "forward_router_address": "192.168.255.1", + }, ], "dest": "0.0.0.0/0", }, @@ -781,8 +779,9 @@ def test_nxos_static_routes_deleteddest(self): vrf="Test", address_families=[ dict( - afi="ipv4", routes=[dict(dest="192.0.2.48/28")] - ) + afi="ipv4", + routes=[dict(dest="192.0.2.48/28")], + ), ], ), ], @@ -869,7 +868,7 @@ def test_nxos_static_routes_deletedroute(self): { "next_hops": [ { - "forward_router_address": "192.0.2.13" + "forward_router_address": "192.0.2.13", }, { "forward_router_address": "192.0.2.14", @@ -991,7 +990,7 @@ def test_nxos_static_routes_parsed(self): { "forward_router_address": "192.0.2.26", "tag": 12, - } + }, ], "dest": "192.0.2.80/28", }, @@ -1027,7 +1026,7 @@ def test_nxos_static_routes_parsed(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.168.255.1"} + {"forward_router_address": "192.168.255.1"}, ], "dest": "0.0.0.0/0", }, @@ -1194,7 +1193,7 @@ def test_nxos_static_routes_gathered(self): { "forward_router_address": "192.0.2.26", "tag": 12, - } + }, ], "dest": "192.0.2.79/28", }, @@ -1230,7 +1229,7 @@ def test_nxos_static_routes_gathered(self): "routes": [ { "next_hops": [ - {"forward_router_address": "192.168.255.1"} + {"forward_router_address": "192.168.255.1"}, ], "dest": "0.0.0.0/0", }, diff --git a/tests/unit/modules/network/nxos/test_nxos_system.py b/tests/unit/modules/network/nxos/test_nxos_system.py index a6fb286bd..7118b2d25 100644 --- a/tests/unit/modules/network/nxos/test_nxos_system.py +++ b/tests/unit/modules/network/nxos/test_nxos_system.py @@ -52,7 +52,9 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "nxos_system", "config.cfg", device=device + "nxos_system", + "config.cfg", + device=device, ) self.load_config.return_value = None @@ -93,7 +95,9 @@ def test_nxos_system_domain_name_vrf_only(self): ) commands = [] self.execute_module( - changed=False, commands=commands, device="vrf_only" + changed=False, + commands=commands, + device="vrf_only", ) def test_nxos_system_domain_name_complex(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_telemetry.py b/tests/unit/modules/network/nxos/test_nxos_telemetry.py index 63300899e..9fa5ee647 100644 --- a/tests/unit/modules/network/nxos/test_nxos_telemetry.py +++ b/tests/unit/modules/network/nxos/test_nxos_telemetry.py @@ -33,9 +33,7 @@ ) from ansible_collections.cisco.nxos.plugins.modules import nxos_telemetry from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( - AnsibleFailJson, -) +from ansible_collections.cisco.nxos.tests.unit.modules.utils import AnsibleFailJson from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -59,16 +57,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.telemetry.telemetry.Telemetry.edit_config", @@ -190,7 +184,8 @@ def test_tms_global_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS global config is present. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -214,7 +209,8 @@ def test_tms_global_change_cert_n9k(self): # TMS global config is present # Change certificate self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -244,7 +240,8 @@ def test_tms_global_change_interface_n9k(self): # TMS global config is present # Change interface self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -275,7 +272,8 @@ def test_tms_global_change_several_n9k(self): # TMS global config is present # Change source_interface, vrf and cert self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -329,7 +327,7 @@ def test_tms_destgroup_input_validation_1(self): self.execute_module() testdata = errinfo.value.args[0] assert "Parameter under is required" in str( - testdata["msg"] + testdata["msg"], ) assert testdata["failed"] @@ -338,17 +336,15 @@ def test_tms_destgroup_input_validation_2(self): self.execute_show_command.return_value = None self.get_platform_shortname.return_value = "N9K" args = build_args( - [{"id": "88", "destination": "192.168.1.1"}], "destination_groups" + [{"id": "88", "destination": "192.168.1.1"}], + "destination_groups", ) set_module_args(args, ignore_provider_arg) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert ( - "Parameter under must be a dict" - in str( - testdata["msg"], - ) + assert "Parameter under must be a dict" in str( + testdata["msg"], ) assert testdata["failed"] @@ -365,7 +361,7 @@ def test_tms_destgroup_input_validation_3(self): self.execute_module() testdata = errinfo.value.args[0] assert "Playbook entry contains unrecongnized parameters" in str( - testdata["msg"] + testdata["msg"], ) assert testdata["failed"] @@ -484,7 +480,8 @@ def test_tms_destgroup_idempotent_n9k(self): # TMS destgroup config is not present. # Configure only identifier self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -509,7 +506,8 @@ def test_tms_destgroup_idempotent2_n9k(self): # TMS destgroup config is not present. # Configure only identifier self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args([{"id": "2"}], "destination_groups") @@ -520,7 +518,8 @@ def test_tms_destgroup_merged_aggregate_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS destgroup config is present. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -553,7 +552,8 @@ def test_tms_destgroup_change_n9k(self): # TMS destgroup config is not present. # Change protocol and encoding for dest group 2 self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -594,7 +594,8 @@ def test_tms_destgroup_add_n9k(self): # Add destinations to destgroup 10 # Add new destgroup 55 and 56 self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -652,12 +653,8 @@ def test_tms_sensorgroup_merged_n9k(self): # TMS sensorgroup config is not present. self.execute_show_command.return_value = None self.get_platform_shortname.return_value = "N9K" - td55_name = ( - "sys/bgp/inst/dom-default/peer-[10.10.10.11]/ent-[10.10.10.11]" - ) - td55_fc = ( - 'or(eq(ethpmPhysIf.operSt,"down"),eq(ethpmPhysIf.operSt,"up"))' - ) + td55_name = "sys/bgp/inst/dom-default/peer-[10.10.10.11]/ent-[10.10.10.11]" + td55_fc = 'or(eq(ethpmPhysIf.operSt,"down"),eq(ethpmPhysIf.operSt,"up"))' args = build_args( [ { @@ -743,7 +740,7 @@ def test_tms_sensorgroup_input_validation_1(self): self.execute_module() testdata = errinfo.value.args[0] assert "Parameter under is required" in str( - testdata["msg"] + testdata["msg"], ) assert testdata["failed"] @@ -769,10 +766,7 @@ def test_tms_sensorgroup_input_validation_2(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert ( - "Parameter under requires key" - in str(testdata["msg"]) - ) + assert "Parameter under requires key" in str(testdata["msg"]) assert testdata["failed"] def test_tms_sensorgroup_resource_key_n9k(self): @@ -900,7 +894,8 @@ def test_tms_sensorgroup_merged_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS sensorgroup config is not present. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -925,7 +920,8 @@ def test_tms_sensorgroup_quotes_merged_idempotent_n9k(self): # Assumes feature telemetry is enabled # TMS sensorgroup config is present with quotes in NX-API path. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K_SGs.cfg" + "nxos_telemetry", + "N9K_SGs.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -953,7 +949,8 @@ def test_tms_sensorgroup_quotes_merged_idempotent_n9k(self): def test_tms_sensorgroup_vxlan_idempotent_n9k(self): # TMS sensorgroup config present. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -966,7 +963,8 @@ def test_tms_sensorgroup_vxlan_idempotent_n9k(self): def test_tms_sensorgroup_idempotent_variable1_n9k(self): # TMS sensorgroup config is present with path key name. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -987,7 +985,8 @@ def test_tms_sensorgroup_idempotent_variable1_n9k(self): def test_tms_sensorgroup_idempotent_variable2_n9k(self): # TMS sensorgroup config is present with path key name and depth. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -1006,7 +1005,8 @@ def test_tms_sensorgroup_idempotent_variable2_n9k(self): def test_tms_sensorgroup_idempotent_resource_key_n9k(self): # TMS sensorgroup config is present resource key only. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args([{"id": "55"}], "sensor_groups") @@ -1135,7 +1135,8 @@ def test_tms_subscription_merged_n9k(self): def test_tms_subscription_merged_idempotent_n9k(self): # TMS subscription config is not present. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -1161,7 +1162,8 @@ def test_tms_subscription_merged_change1_n9k(self): # TMS subscription config present. # Change sample interval for sensor group 2 self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -1194,7 +1196,8 @@ def test_tms_subscription_add_n9k(self): # TMS subscription config present. # Add new destination_group and sensor_group to subscription 5 self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" args = build_args( @@ -1383,7 +1386,8 @@ def test_telemetry_full_n9k(self): def test_telemetry_deleted_input_validation_n9k(self): # State is 'deleted' and 'config' key present. self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -1404,10 +1408,7 @@ def test_telemetry_deleted_input_validation_n9k(self): with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() testdata = errinfo.value.args[0] - assert ( - "Remove config key from playbook when state is " - in str(testdata["msg"]) - ) + assert "Remove config key from playbook when state is " in str(testdata["msg"]) assert testdata["failed"] def test_telemetry_deleted_n9k(self): @@ -1415,7 +1416,8 @@ def test_telemetry_deleted_n9k(self): # TMS global config is present. # Make absent with all playbook keys provided self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args(dict(state="deleted"), ignore_provider_arg) @@ -1434,7 +1436,8 @@ def test_tms_replaced1_n9k(self): # Assumes feature telemetry is enabled # Modify global config and remove everything else self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -1479,7 +1482,8 @@ def test_tms_replaced2_n9k(self): # Modify sensor-group 55, 56 # remove all subscriptions self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -1597,7 +1601,8 @@ def test_tms_replaced3_n9k(self): # Modify sensor-group 55 and delete all others # Modify subscription 7, add 10 and delete all others self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( @@ -1690,7 +1695,8 @@ def test_tms_replaced_idempotent_n9k(self): # Modify sensor-group 55 and delete all others # Modify subscription 7, add 10 and delete all others self.execute_show_command.return_value = load_fixture( - "nxos_telemetry", "N9K.cfg" + "nxos_telemetry", + "N9K.cfg", ) self.get_platform_shortname.return_value = "N9K" set_module_args( diff --git a/tests/unit/modules/network/nxos/test_nxos_user.py b/tests/unit/modules/network/nxos/test_nxos_user.py index 98070c114..edcb25b31 100644 --- a/tests/unit/modules/network/nxos/test_nxos_user.py +++ b/tests/unit/modules/network/nxos/test_nxos_user.py @@ -74,7 +74,7 @@ def test_mds(self): "usr_name": "admin", "expire_date": "this user account has no expiry date", "TABLE_role": { - "ROW_role": {"role": "network-admin"} + "ROW_role": {"role": "network-admin"}, }, }, { @@ -95,7 +95,7 @@ def test_mds(self): "network_os_platform": "DS-C9710", } set_module_args( - dict(name="ansible-test-2", configured_password="ansible") + dict(name="ansible-test-2", configured_password="ansible"), ) self.execute_module( changed=True, diff --git a/tests/unit/modules/network/nxos/test_nxos_vlans.py b/tests/unit/modules/network/nxos/test_nxos_vlans.py index 945cbc738..ba742a62c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vlans.py +++ b/tests/unit/modules/network/nxos/test_nxos_vlans.py @@ -45,16 +45,12 @@ def setUp(self): self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) - self.get_resource_connection_config = ( - self.mock_get_resource_connection_config.start() - ) + self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) - self.get_resource_connection_facts = ( - self.mock_get_resource_connection_facts.start() - ) + self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_edit_config = patch( "ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.config.vlans.vlans.Vlans.edit_config", @@ -124,7 +120,10 @@ def test_1(self): dict(vlan_id=4), dict(vlan_id=5, mapped_vni=555, mode="ce"), dict( - vlan_id=7, mapped_vni=777, name="test-vlan7", enabled=False + vlan_id=7, + mapped_vni=777, + name="test-vlan7", + enabled=False, ), dict(vlan_id="8", state="active", name="test-changeme-not"), # vlan 3 is not present in playbook. diff --git a/tests/unit/modules/network/nxos/test_nxos_vpc.py b/tests/unit/modules/network/nxos/test_nxos_vpc.py index 72d6e9968..e464db81e 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vpc.py +++ b/tests/unit/modules/network/nxos/test_nxos_vpc.py @@ -70,9 +70,7 @@ def vrf_load_from_file(*args, **kwargs): module, commands = args output = list() for command in commands: - filename = "vrf_test_" + str(command).split(" | ", 1)[ - 0 - ].replace(" ", "_") + filename = "vrf_test_" + str(command).split(" | ", 1)[0].replace(" ", "_") output.append(load_fixture("nxos_vpc", filename)) return output @@ -129,7 +127,8 @@ def test_nxos_vpc_vrf_2(self): # vrf 'my_vrf'-> vrf 'test-vrf' # All pkl commands should be present self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args( dict( @@ -152,7 +151,8 @@ def test_nxos_vpc_vrf_3(self): # vrf 'my_vrf' -> vrf 'obviously-different-vrf' # Existing pkl_src should be retained even though playbook does not specify it self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args( dict( @@ -174,10 +174,11 @@ def test_nxos_vpc_vrf_4(self): # vrf 'my_vrf'-> vrf 'management' # 'management' is the default value for vrf, it will not nvgen self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args( - dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="management") + dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="management"), ) self.execute_module( changed=True, @@ -191,7 +192,8 @@ def test_nxos_vpc_vrf_4(self): def test_nxos_vpc_vrf_5(self): # vrf 'my_vrf' -> vrf 'my_vrf' (idempotence) self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args( dict( @@ -206,7 +208,8 @@ def test_nxos_vpc_vrf_5(self): def test_nxos_vpc_vrf_6(self): # vrf 'my_vrf' -> absent tests self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args(dict(domain=100, state="absent")) self.execute_module( @@ -219,7 +222,8 @@ def test_nxos_vpc_vrf_7(self): # dest 192.168.1.1 source 10.1.1.1 vrf my_vrf -> (dest only) (idempotence) # pkl_src/pkl_vrf not in playbook but exists on device. self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args(dict(domain=100, pkl_dest="192.168.1.1")) self.execute_module(changed=False, device="_vrf_test") @@ -228,9 +232,10 @@ def test_nxos_vpc_vrf_8(self): # dest 192.168.1.1 source 10.1.1.1 vrf my_vrf -> (optional vrf) (idempotence) # pkl_src not in playbook but exists on device. self.get_config.return_value = load_fixture( - "nxos_vpc", "vrf_test_vpc_config" + "nxos_vpc", + "vrf_test_vpc_config", ) set_module_args( - dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="my_vrf") + dict(domain=100, pkl_dest="192.168.1.1", pkl_vrf="my_vrf"), ) self.execute_module(changed=False, device="_vrf_test") diff --git a/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py b/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py index 2eeaaccc9..3d23d6c52 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py +++ b/tests/unit/modules/network/nxos/test_nxos_vpc_interface.py @@ -71,12 +71,14 @@ def test_nxos_vpc_interface_absent(self): set_module_args(dict(portchannel=10, vpc=100, state="absent")) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["interface port-channel10", "no vpc"] + result["commands"], + ["interface port-channel10", "no vpc"], ) def test_nxos_vpc_interface_present(self): set_module_args(dict(portchannel=20, vpc=200, state="present")) result = self.execute_module(changed=True) self.assertEqual( - result["commands"], ["interface port-channel20", "vpc 200"] + result["commands"], + ["interface port-channel20", "vpc 200"], ) diff --git a/tests/unit/modules/network/nxos/test_nxos_vrf.py b/tests/unit/modules/network/nxos/test_nxos_vrf.py index 1502e4629..459fa60a9 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vrf.py +++ b/tests/unit/modules/network/nxos/test_nxos_vrf.py @@ -67,19 +67,21 @@ def load_from_file(*args, **kwargs): def test_nxos_vrf_present(self): set_module_args(dict(vrf="ntc", state="present", admin_state="up")) self.execute_module( - changed=True, commands=["vrf context ntc", "no shutdown", "exit"] + changed=True, + commands=["vrf context ntc", "no shutdown", "exit"], ) def test_nxos_vrf_present_no_change(self): set_module_args( - dict(vrf="management", state="present", admin_state="up") + dict(vrf="management", state="present", admin_state="up"), ) self.execute_module(changed=False, commands=[]) def test_nxos_vrf_absent(self): set_module_args(dict(vrf="management", state="absent")) self.execute_module( - changed=True, commands=["no vrf context management"] + changed=True, + commands=["no vrf context management"], ) def test_nxos_vrf_absent_no_change(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_vrf_af.py b/tests/unit/modules/network/nxos/test_nxos_vrf_af.py index 0e14eec9c..085ebb255 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vrf_af.py +++ b/tests/unit/modules/network/nxos/test_nxos_vrf_af.py @@ -49,7 +49,7 @@ def setUp(self): ) self.get_capabilities = self.mock_get_capabilities.start() self.get_capabilities.return_value = { - "device_info": {"network_os_platform": "N7K-C7018"} + "device_info": {"network_os_platform": "N7K-C7018"}, } def tearDown(self): @@ -60,7 +60,8 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "nxos_vrf_af", "config.cfg" + "nxos_vrf_af", + "config.cfg", ) self.load_config.return_value = None @@ -92,7 +93,7 @@ def test_nxos_vrf_af_absent_current_existing(self): def test_nxos_vrf_af_auto_evpn_route_target_present_current_existing(self): set_module_args( - dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=True) + dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=True), ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -101,7 +102,7 @@ def test_nxos_vrf_af_auto_evpn_route_target_present_current_non_existing( self, ): set_module_args( - dict(vrf="vrf10", afi="ipv4", route_target_both_auto_evpn=True) + dict(vrf="vrf10", afi="ipv4", route_target_both_auto_evpn=True), ) result = self.execute_module(changed=True) self.assertEqual( @@ -115,7 +116,7 @@ def test_nxos_vrf_af_auto_evpn_route_target_present_current_non_existing( def test_nxos_vrf_af_auto_evpn_route_target_absent_current_existing(self): set_module_args( - dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=False) + dict(vrf="vrf11", afi="ipv4", route_target_both_auto_evpn=False), ) result = self.execute_module(changed=True) self.assertEqual( @@ -131,7 +132,7 @@ def test_nxos_vrf_af_auto_evpn_route_target_absent_current_non_existing( self, ): set_module_args( - dict(vrf="vrf1", afi="ipv4", route_target_both_auto_evpn=False) + dict(vrf="vrf1", afi="ipv4", route_target_both_auto_evpn=False), ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) @@ -1101,14 +1102,14 @@ def test_nxos_vrf_af_auto_evpn_route_target_and_manual_route_targets_with_absent def test_nxos_vrf_af_both_auto_N9K(self): self.get_capabilities.return_value = { - "device_info": {"network_os_platform": "N9K-C9300v"} + "device_info": {"network_os_platform": "N9K-C9300v"}, } set_module_args( dict( vrf="v2000", afi="ipv4", route_targets=[ - {"rt": "auto", "direction": "both", "state": "present"} + {"rt": "auto", "direction": "both", "state": "present"}, ], ), ) diff --git a/tests/unit/modules/network/nxos/test_nxos_vsan.py b/tests/unit/modules/network/nxos/test_nxos_vsan.py index 4a0d91e65..b841d5fc2 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vsan.py +++ b/tests/unit/modules/network/nxos/test_nxos_vsan.py @@ -11,9 +11,7 @@ from ansible_collections.cisco.nxos.plugins.modules import nxos_vsan from ansible_collections.cisco.nxos.tests.unit.compat.mock import patch -from ansible_collections.cisco.nxos.tests.unit.modules.utils import ( - AnsibleFailJson, -) +from ansible_collections.cisco.nxos.tests.unit.modules.utils import AnsibleFailJson from .nxos_module import TestNxosModule, load_fixture, set_module_args @@ -23,9 +21,7 @@ class TestNxosVsanModule(TestNxosModule): def setUp(self): super(TestNxosVsanModule, self).setUp() - module_path = ( - "ansible_collections.cisco.nxos.plugins.modules.nxos_vsan." - ) + module_path = "ansible_collections.cisco.nxos.plugins.modules.nxos_vsan." self.mock_run_commands = patch(module_path + "run_commands") self.run_commands = self.mock_run_commands.start() @@ -38,9 +34,7 @@ def setUp(self): self.mock_execute_show_vsanmemcmd = patch( module_path + "GetVsanInfoFromSwitch.execute_show_vsan_mem_cmd", ) - self.execute_show_vsanmem_cmd = ( - self.mock_execute_show_vsanmemcmd.start() - ) + self.execute_show_vsanmem_cmd = self.mock_execute_show_vsanmemcmd.start() self.mock_load_config = patch(module_path + "load_config") self.load_config = self.mock_load_config.start() @@ -77,24 +71,28 @@ def test_vsan_add_remove_but_present_in_switch(self): } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) def test_vsan_remove(self): margs = { - "vsan": [{"id": 922, "remove": True}, {"id": 923, "remove": True}] + "vsan": [{"id": 922, "remove": True}, {"id": 923, "remove": True}], } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -122,10 +120,12 @@ def test_vsan_add(self): } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -163,10 +163,12 @@ def test_vsan_suspend(self): } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -186,14 +188,16 @@ def test_vsan_suspend(self): def test_vsan_invalid_vsan(self): margs = { - "vsan": [{"id": 4096, "name": "vsan-SAN-925", "suspend": True}] + "vsan": [{"id": 4096, "name": "vsan-SAN-925", "suspend": True}], } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) with pytest.raises(AnsibleFailJson) as errinfo: self.execute_module() @@ -203,14 +207,16 @@ def test_vsan_invalid_vsan(self): def test_vsan_change_reserved_vsan(self): margs = { - "vsan": [{"id": 4094, "name": "vsan-SAN-925", "suspend": True}] + "vsan": [{"id": 4094, "name": "vsan-SAN-925", "suspend": True}], } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=False) assert "reserved vsan" in str(result["messages"]) @@ -227,10 +233,12 @@ def test_vsan_add_int_existing_vsan(self): } set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=True) self.assertEqual( @@ -248,10 +256,12 @@ def test_vsan_remove_non_existing_vsan(self): margs = {"vsan": [{"id": 1111, "remove": True}]} set_module_args(margs, True) self.execute_show_vsan_cmd.return_value = load_fixture( - "nxos_vsan", "shvsan.cfg" + "nxos_vsan", + "shvsan.cfg", ) self.execute_show_vsanmem_cmd.return_value = load_fixture( - "nxos_vsan", "shvsanmem.cfg" + "nxos_vsan", + "shvsanmem.cfg", ) result = self.execute_module(changed=False) self.assertEqual(result["commands"], []) diff --git a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py index beae9a09b..d0b7f1245 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py +++ b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep.py @@ -51,13 +51,14 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "nxos_vxlan_vtep", "config.cfg" + "nxos_vxlan_vtep", + "config.cfg", ) self.load_config.return_value = None def test_nxos_vxlan_vtep(self): set_module_args( - dict(interface="nve1", description="simple description") + dict(interface="nve1", description="simple description"), ) self.execute_module( changed=True, diff --git a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py index 597857989..612dcc6f1 100644 --- a/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py +++ b/tests/unit/modules/network/nxos/test_nxos_vxlan_vtep_vni.py @@ -51,7 +51,8 @@ def tearDown(self): def load_fixtures(self, commands=None, device=""): self.get_config.return_value = load_fixture( - "nxos_vxlan_vtep_vni", "config.cfg" + "nxos_vxlan_vtep_vni", + "config.cfg", ) self.load_config.return_value = None @@ -62,13 +63,15 @@ def test_nxos_vxlan_vtep_vni_present_no_change(self): def test_nxos_vxlan_vtep_vni(self): set_module_args(dict(interface="nve1", vni=5000)) self.execute_module( - changed=True, commands=["interface nve1", "member vni 5000"] + changed=True, + commands=["interface nve1", "member vni 5000"], ) def test_nxos_vxlan_vtep_vni_absent(self): set_module_args(dict(interface="nve1", vni=6000, state="absent")) self.execute_module( - changed=True, commands=["interface nve1", "no member vni 6000"] + changed=True, + commands=["interface nve1", "no member vni 6000"], ) def test_nxos_vxlan_vtep_vni_absent_no_change(self): diff --git a/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py b/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py index 9af738342..6f4b8de4c 100644 --- a/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py +++ b/tests/unit/modules/network/nxos/test_nxos_zone_zoneset.py @@ -19,9 +19,7 @@ class TestNxosZoneZonesetModule(TestNxosModule): def setUp(self): super(TestNxosZoneZonesetModule, self).setUp() - module_path = ( - "ansible_collections.cisco.nxos.plugins.modules.nxos_zone_zoneset." - ) + module_path = "ansible_collections.cisco.nxos.plugins.modules.nxos_zone_zoneset." self.mock_run_commands = patch(module_path + "run_commands") self.run_commands = self.mock_run_commands.start() @@ -29,16 +27,12 @@ def setUp(self): self.mock_execute_show_cmd_zoneset_active = patch( module_path + "ShowZonesetActive.execute_show_zoneset_active_cmd", ) - self.execute_show_cmd_zoneset_active = ( - self.mock_execute_show_cmd_zoneset_active.start() - ) + self.execute_show_cmd_zoneset_active = self.mock_execute_show_cmd_zoneset_active.start() self.mock_execute_show_cmd_zoneset = patch( module_path + "ShowZoneset.execute_show_zoneset_cmd", ) - self.execute_show_cmd_zoneset = ( - self.mock_execute_show_cmd_zoneset.start() - ) + self.execute_show_cmd_zoneset = self.mock_execute_show_cmd_zoneset.start() self.mock_execute_show_cmd_zone = patch( module_path + "ShowZone.execute_show_zone_vsan_cmd", @@ -48,9 +42,7 @@ def setUp(self): self.mock_execute_show_cmd_zone_status = patch( module_path + "ShowZoneStatus.execute_show_zone_status_cmd", ) - self.execute_show_cmd_zone_status = ( - self.mock_execute_show_cmd_zone_status.start() - ) + self.execute_show_cmd_zone_status = self.mock_execute_show_cmd_zone_status.start() self.mock_load_config = patch(module_path + "load_config") self.load_config = self.mock_load_config.start() @@ -270,7 +262,7 @@ def test_zone_add_rem_1(self): def test_zone_add_rem_2(self): a = dict( - zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneBNew")])] + zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneBNew")])], ) set_module_args(a, True) self.execute_show_cmd_zone_status.return_value = load_fixture( @@ -294,7 +286,7 @@ def test_zone_add_rem_2(self): def test_zone_add_rem_3(self): a = dict( - zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneB")])] + zone_zoneset_details=[dict(vsan=923, zone=[dict(name="zoneB")])], ) set_module_args(a, True) self.execute_show_cmd_zone_status.return_value = load_fixture( @@ -351,7 +343,8 @@ def test_zonemem_add_rem_1(self): a = dict( zone_zoneset_details=[ dict( - vsan=923, zone=[dict(name="zoneA", members=[mem1, mem2])] + vsan=923, + zone=[dict(name="zoneA", members=[mem1, mem2])], ), ], ) @@ -384,7 +377,8 @@ def test_zonemem_add_rem_2(self): a = dict( zone_zoneset_details=[ dict( - vsan=923, zone=[dict(name="zoneA1", members=[mem1, mem2])] + vsan=923, + zone=[dict(name="zoneA1", members=[mem1, mem2])], ), ], ) @@ -495,7 +489,7 @@ def test_zoneset_add_rem(self): def test_zoneset_add_rem_1(self): a = dict( zone_zoneset_details=[ - dict(vsan=922, zoneset=[dict(name="zsetname21New")]) + dict(vsan=922, zoneset=[dict(name="zsetname21New")]), ], ) set_module_args(a, True) @@ -520,7 +514,7 @@ def test_zoneset_add_rem_1(self): def test_zoneset_add_rem_2(self): a = dict( zone_zoneset_details=[ - dict(vsan=922, zoneset=[dict(name="zsetname21")]) + dict(vsan=922, zoneset=[dict(name="zsetname21")]), ], ) set_module_args(a, True) @@ -541,7 +535,8 @@ def test_zoneset_add_rem_3(self): a = dict( zone_zoneset_details=[ dict( - vsan=922, zoneset=[dict(name="zsetname21New", remove=True)] + vsan=922, + zoneset=[dict(name="zsetname21New", remove=True)], ), ], ) @@ -566,7 +561,8 @@ def test_zoneset_mem_add_rem(self): a = dict( zone_zoneset_details=[ dict( - vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])] + vsan=922, + zoneset=[dict(name="zsetname21", members=[mem1])], ), ], ) @@ -597,7 +593,8 @@ def test_zoneset_mem_add_rem_1(self): a = dict( zone_zoneset_details=[ dict( - vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])] + vsan=922, + zoneset=[dict(name="zsetname21", members=[mem1])], ), ], ) @@ -628,7 +625,8 @@ def test_zoneset_mem_add_rem_2(self): a = dict( zone_zoneset_details=[ dict( - vsan=922, zoneset=[dict(name="zsetname21", members=[mem1])] + vsan=922, + zoneset=[dict(name="zsetname21", members=[mem1])], ), ], ) @@ -651,7 +649,8 @@ def test_zoneset_activate_deactivate(self): a = dict( zone_zoneset_details=[ dict( - vsan=221, zoneset=[dict(name="zsv221", action="activate")] + vsan=221, + zoneset=[dict(name="zsv221", action="activate")], ), ], ) @@ -744,7 +743,8 @@ def test_bug_zone_remove(self): a = dict( zone_zoneset_details=[ dict( - vsan=221, zone=[dict(name="zv221", members=[mem1, mem2])] + vsan=221, + zone=[dict(name="zv221", members=[mem1, mem2])], ), ], ) From c2383582cae3834b041067612a2b8cd6128c83f6 Mon Sep 17 00:00:00 2001 From: Ashwini Mhatre Date: Thu, 7 Mar 2024 17:55:45 +0530 Subject: [PATCH 19/19] Update test-requirements.txt --- test-requirements.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test-requirements.txt b/test-requirements.txt index a42e5fcf7..f0860548b 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -2,5 +2,7 @@ black==23.3.0 flake8 yamllint -coverage==4.5.4 virl2-client==2.6.1 +pytest-ansible +pytest-xdist +pytest-cov