summaryrefslogtreecommitdiff
path: root/plugins/module_utils
diff options
context:
space:
mode:
authorYVarshitha <63169351+YVarshitha@users.noreply.github.com>2021-10-02 13:28:30 -0400
committerGitHub <noreply@github.com>2021-10-02 17:28:30 +0000
commit85ea49f10a6167dea4c08e71a1e8e5a62cb57395 (patch)
tree0bfd9aa0bc06c1d342944fef3bc18f7c3d7ec047 /plugins/module_utils
parent88689227265b7f6b272b695a275f4a47735ddcc2 (diff)
downloadvyos.vyos-85ea49f10a6167dea4c08e71a1e8e5a62cb57395.tar.gz
vyos.vyos-85ea49f10a6167dea4c08e71a1e8e5a62cb57395.zip
Add vyos_ntp resource module (#175)
Add vyos_ntp resource module SUMMARY Resource module vyos_ntp ISSUE TYPE New Module Pull Request COMPONENT NAME vyos_ntp ADDITIONAL INFORMATION Reviewed-by: GomathiselviS <None> Reviewed-by: Nilashish Chakraborty <nilashishchakraborty8@gmail.com> Reviewed-by: None <None>
Diffstat (limited to 'plugins/module_utils')
-rw-r--r--plugins/module_utils/network/vyos/argspec/ntp_global/__init__.py0
-rw-r--r--plugins/module_utils/network/vyos/argspec/ntp_global/ntp_global.py72
-rw-r--r--plugins/module_utils/network/vyos/config/ntp_global/__init__.py0
-rw-r--r--plugins/module_utils/network/vyos/config/ntp_global/ntp_global.py197
-rw-r--r--plugins/module_utils/network/vyos/facts/facts.py4
-rw-r--r--plugins/module_utils/network/vyos/facts/ntp_global/__init__.py0
-rw-r--r--plugins/module_utils/network/vyos/facts/ntp_global/ntp_global.py99
-rw-r--r--plugins/module_utils/network/vyos/rm_templates/ntp_global.py129
8 files changed, 501 insertions, 0 deletions
diff --git a/plugins/module_utils/network/vyos/argspec/ntp_global/__init__.py b/plugins/module_utils/network/vyos/argspec/ntp_global/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/plugins/module_utils/network/vyos/argspec/ntp_global/__init__.py
diff --git a/plugins/module_utils/network/vyos/argspec/ntp_global/ntp_global.py b/plugins/module_utils/network/vyos/argspec/ntp_global/ntp_global.py
new file mode 100644
index 00000000..63262154
--- /dev/null
+++ b/plugins/module_utils/network/vyos/argspec/ntp_global/ntp_global.py
@@ -0,0 +1,72 @@
+# -*- coding: utf-8 -*-
+# Copyright 2021 Red Hat
+# GNU General Public License v3.0+
+# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import absolute_import, division, print_function
+
+__metaclass__ = type
+
+#############################################
+# WARNING #
+#############################################
+#
+# This file is auto generated by the
+# cli_rm_builder.
+#
+# Manually editing this file is not advised.
+#
+# To update the argspec make the desired changes
+# in the module docstring and re-run
+# cli_rm_builder.
+#
+#############################################
+
+"""
+The arg spec for the vyos_ntp module
+"""
+
+
+class Ntp_globalArgs(object): # pylint: disable=R0903
+ """The arg spec for the vyos_ntp module"""
+
+ argument_spec = {
+ "config": {
+ "type": "dict",
+ "options": {
+ "allow_clients": {"type": "list", "elements": "str"},
+ "listen_addresses": {"type": "list", "elements": "str"},
+ "servers": {
+ "type": "list",
+ "elements": "dict",
+ "options": {
+ "server": {"type": "str"},
+ "options": {
+ "type": "list",
+ "elements": "str",
+ "choices": [
+ "noselect",
+ "dynamic",
+ "preempt",
+ "prefer",
+ ],
+ },
+ },
+ },
+ },
+ },
+ "running_config": {"type": "str"},
+ "state": {
+ "type": "str",
+ "choices": [
+ "deleted",
+ "merged",
+ "overridden",
+ "replaced",
+ "gathered",
+ "rendered",
+ "parsed",
+ ],
+ "default": "merged",
+ },
+ } # pylint: disable=C0301
diff --git a/plugins/module_utils/network/vyos/config/ntp_global/__init__.py b/plugins/module_utils/network/vyos/config/ntp_global/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/plugins/module_utils/network/vyos/config/ntp_global/__init__.py
diff --git a/plugins/module_utils/network/vyos/config/ntp_global/ntp_global.py b/plugins/module_utils/network/vyos/config/ntp_global/ntp_global.py
new file mode 100644
index 00000000..0a0e389f
--- /dev/null
+++ b/plugins/module_utils/network/vyos/config/ntp_global/ntp_global.py
@@ -0,0 +1,197 @@
+#
+# -*- coding: utf-8 -*-
+# Copyright 2021 Red Hat
+# GNU General Public License v3.0+
+# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+#
+
+from __future__ import absolute_import, division, print_function
+
+__metaclass__ = type
+
+"""
+The vyos_ntp config file.
+It is in this file where the current configuration (as dict)
+is compared to the provided configuration (as dict) and the command set
+necessary to bring the current configuration to its desired end-state is
+created.
+"""
+
+from ansible.module_utils.six import iteritems
+from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
+ dict_merge,
+)
+from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module import (
+ ResourceModule,
+)
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import (
+ Facts,
+)
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.ntp_global import (
+ NtpTemplate,
+)
+
+
+class Ntp_global(ResourceModule):
+ """
+ The vyos_ntp config class
+ """
+
+ def __init__(self, module):
+ super(Ntp_global, self).__init__(
+ empty_fact_val={},
+ facts_module=Facts(module),
+ module=module,
+ resource="ntp_global",
+ tmplt=NtpTemplate(),
+ )
+ self.parsers = [
+ "allow_clients",
+ "listen_addresses",
+ "server",
+ "options",
+ "allow_clients_delete",
+ "listen_addresses_delete",
+ ]
+
+ def execute_module(self):
+ """Execute the module
+
+ :rtype: A dictionary
+ :returns: The result from module execution
+ """
+ if self.state not in ["parsed", "gathered"]:
+ self.generate_commands()
+ self.run_commands()
+ return self.result
+
+ def generate_commands(self):
+ """Generate configuration commands to send based on
+ want, have and desired state.
+ """
+
+ wantd = self._ntp_list_to_dict(self.want)
+ haved = self._ntp_list_to_dict(self.have)
+
+ # if state is merged, merge want onto have and then compare
+ if self.state == "merged":
+ wantd = dict_merge(haved, wantd)
+
+ # 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
+ }
+ wantd = {}
+
+ commandlist = self._commandlist(haved)
+ servernames = self._servernames(haved)
+ # removing the servername and commandlist from the list after deleting it from haved
+ for k, have in iteritems(haved):
+ if k not in wantd:
+ for hk, hval in iteritems(have):
+ if hk == "allow_clients" and hk in commandlist:
+ self.commands.append(
+ self._tmplt.render(
+ {"": hk}, "allow_clients_delete", True
+ )
+ )
+ commandlist.remove(hk)
+ elif hk == "listen_addresses" and hk in commandlist:
+ self.commands.append(
+ self._tmplt.render(
+ {"": hk}, "listen_addresses_delete", True
+ )
+ )
+ commandlist.remove(hk)
+ elif hk == "server" and have["server"] in servernames:
+ self._compareoverride(want={}, have=have)
+ servernames.remove(have["server"])
+
+ # remove existing config for overridden,replaced and deleted
+ # Getting the list of the server names from haved
+ # to avoid the duplication of overridding/replacing the servers
+ if self.state in ["overridden", "replaced"]:
+
+ commandlist = self._commandlist(haved)
+ servernames = self._servernames(haved)
+
+ for k, have in iteritems(haved):
+ if k not in wantd and "server" not in have:
+ self._compareoverride(want={}, have=have)
+ # removing the servername from the list after deleting it from haved
+ elif k not in wantd and have["server"] in servernames:
+ self._compareoverride(want={}, have=have)
+ servernames.remove(have["server"])
+
+ for k, want in iteritems(wantd):
+ self._compare(want=want, have=haved.pop(k, {}))
+
+ def _compare(self, want, have):
+ """Leverages the base class `compare()` method and
+ populates the list of commands to be run by comparing
+ the `want` and `have` data with the `parsers` defined
+ for the Ntp network resource.
+ """
+ if "options" in want:
+ self.compare(parsers="options", want=want, have=have)
+ else:
+ self.compare(parsers=self.parsers, want=want, have=have)
+
+ def _compareoverride(self, want, have):
+ # do not delete configuration with options level
+ for i, val in iteritems(have):
+ if i == "options":
+ pass
+ else:
+ self.compare(parsers=i, want={}, have=have)
+
+ def _ntp_list_to_dict(self, entry):
+ servers_dict = {}
+ for k, data in iteritems(entry):
+ if k == "servers":
+ for value in data:
+ if "options" in value:
+ result = self._serveroptions_list_to_dict(value)
+ for res, resvalue in iteritems(result):
+ servers_dict.update({res: resvalue})
+ else:
+ servers_dict.update({value["server"]: value})
+ else:
+ for value in data:
+ servers_dict.update({"ip_" + value: {k: value}})
+ return servers_dict
+
+ def _serveroptions_list_to_dict(self, entry):
+ serveroptions_dict = {}
+ for Opk, Op in iteritems(entry):
+ if Opk == "options":
+ for val in Op:
+ dict = {}
+ dict.update({"server": entry["server"]})
+ dict.update({Opk: val})
+ serveroptions_dict.update(
+ {entry["server"] + "_" + val: dict}
+ )
+ return serveroptions_dict
+
+ def _commandlist(self, haved):
+ commandlist = []
+ for k, have in iteritems(haved):
+ for ck, cval in iteritems(have):
+ if ck != "options" and ck not in commandlist:
+ commandlist.append(ck)
+ return commandlist
+
+ def _servernames(self, haved):
+ servernames = []
+ for k, have in iteritems(haved):
+ for sk, sval in iteritems(have):
+ if sk == "server" and sval not in [
+ "0.pool.ntp.org",
+ "1.pool.ntp.org",
+ "2.pool.ntp.org",
+ ]:
+ if sval not in servernames:
+ servernames.append(sval)
+ return servernames
diff --git a/plugins/module_utils/network/vyos/facts/facts.py b/plugins/module_utils/network/vyos/facts/facts.py
index ab074b00..e560a48a 100644
--- a/plugins/module_utils/network/vyos/facts/facts.py
+++ b/plugins/module_utils/network/vyos/facts/facts.py
@@ -64,6 +64,9 @@ from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.prefi
from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.logging_global.logging_global import (
Logging_globalFacts,
)
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.ntp_global.ntp_global import (
+ Ntp_globalFacts,
+)
from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.legacy.base import (
Default,
Neighbors,
@@ -90,6 +93,7 @@ FACT_RESOURCE_SUBSETS = dict(
route_maps=Route_mapsFacts,
prefix_lists=Prefix_listsFacts,
logging_global=Logging_globalFacts,
+ ntp_global=Ntp_globalFacts,
)
diff --git a/plugins/module_utils/network/vyos/facts/ntp_global/__init__.py b/plugins/module_utils/network/vyos/facts/ntp_global/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/plugins/module_utils/network/vyos/facts/ntp_global/__init__.py
diff --git a/plugins/module_utils/network/vyos/facts/ntp_global/ntp_global.py b/plugins/module_utils/network/vyos/facts/ntp_global/ntp_global.py
new file mode 100644
index 00000000..bb20e2d6
--- /dev/null
+++ b/plugins/module_utils/network/vyos/facts/ntp_global/ntp_global.py
@@ -0,0 +1,99 @@
+# -*- coding: utf-8 -*-
+# Copyright 2021 Red Hat
+# GNU General Public License v3.0+
+# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import absolute_import, division, print_function
+
+
+__metaclass__ = type
+
+"""
+The vyos ntp fact class
+It is in this file the configuration is collected from the device
+for a given resource, parsed, and the facts tree is populated
+based on the configuration.
+"""
+
+import re
+
+from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import (
+ utils,
+)
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.ntp_global import (
+ NtpTemplate,
+)
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.ntp_global.ntp_global import (
+ Ntp_globalArgs,
+)
+
+
+class Ntp_globalFacts(object):
+ """The vyos ntp facts class"""
+
+ def __init__(self, module, subspec="config", options="options"):
+ self._module = module
+ self.argument_spec = Ntp_globalArgs.argument_spec
+
+ def get_config(self, connection):
+ return connection.get("show configuration commands | grep ntp")
+
+ def populate_facts(self, connection, ansible_facts, data=None):
+ """Populate the facts for Ntp network resource
+
+ :param connection: the device connection
+ :param ansible_facts: Facts dictionary
+ :param data: previously collected conf
+
+ :rtype: dictionary
+ :returns: facts
+ """
+ facts = {}
+ objs = []
+ config_lines = []
+
+ if not data:
+ data = self.get_config(connection)
+
+ for resource in data.splitlines():
+ config_lines.append(re.sub("'", "", resource))
+ # parse native config using the Ntp template
+ ntp_parser = NtpTemplate(lines=config_lines, module=self._module)
+
+ objs = ntp_parser.parse()
+
+ if objs:
+ if "allow_clients" in objs:
+ objs["allow_clients"] = sorted(list(objs["allow_clients"]))
+
+ if "listen_addresses" in objs:
+ objs["listen_addresses"] = sorted(
+ list(objs["listen_addresses"])
+ )
+
+ """ if "options" in objs["servers"].values():
+ val = objs["servers"].values()
+ val["options"] = sorted(val["options"]) """
+
+ if "servers" in objs:
+ objs["servers"] = list(objs["servers"].values())
+ objs["servers"] = sorted(
+ objs["servers"], key=lambda k: k["server"]
+ )
+ for i in objs["servers"]:
+ if "options" in i:
+ i["options"] = sorted(list(i["options"]))
+
+ ansible_facts["ansible_network_resources"].pop("ntp_global", None)
+
+ params = utils.remove_empties(
+ ntp_parser.validate_config(
+ self.argument_spec, {"config": objs}, redact=True
+ )
+ )
+
+ if params.get("config"):
+ facts["ntp_global"] = params["config"]
+ ansible_facts["ansible_network_resources"].update(facts)
+
+ return ansible_facts
diff --git a/plugins/module_utils/network/vyos/rm_templates/ntp_global.py b/plugins/module_utils/network/vyos/rm_templates/ntp_global.py
new file mode 100644
index 00000000..ac0bcbbf
--- /dev/null
+++ b/plugins/module_utils/network/vyos/rm_templates/ntp_global.py
@@ -0,0 +1,129 @@
+# -*- coding: utf-8 -*-
+# Copyright 2021 Red Hat
+# GNU General Public License v3.0+
+# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import absolute_import, division, print_function
+
+__metaclass__ = type
+
+"""
+The Ntp parser templates file. This contains
+a list of parser definitions and associated functions that
+facilitates both facts gathering and native command generation for
+the given network resource.
+"""
+
+import re
+from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.network_template import (
+ NetworkTemplate,
+)
+
+
+class NtpTemplate(NetworkTemplate):
+ def __init__(self, lines=None, module=None):
+ prefix = {"set": "set", "remove": "delete"}
+ super(NtpTemplate, self).__init__(
+ lines=lines, tmplt=self, prefix=prefix, module=module
+ )
+
+ # fmt: off
+ PARSERS = [
+
+ # set system ntp allow_clients address <address>
+ {
+ "name": "allow_clients",
+ "getval": re.compile(
+ r"""
+ ^set\ssystem\sntp\sallow-clients\saddress (\s(?P<ipaddress>\S+))?
+ $""",
+ re.VERBOSE),
+ "setval": "system ntp allow-clients address {{allow_clients}}",
+ "result": {
+ "allow_clients": ["{{ipaddress}}"]
+ }
+ },
+
+ # set system ntp allow_clients
+ {
+ "name": "allow_clients_delete",
+ "getval": re.compile(
+ r"""
+ ^set\ssystem\sntp\sallow-clients
+ $""",
+ re.VERBOSE),
+ "setval": "system ntp allow-clients",
+ "result": {
+
+ }
+
+ },
+
+ # set system ntp listen_address <address>
+ {
+ "name": "listen_addresses",
+ "getval": re.compile(
+ r"""
+ ^set\ssystem\sntp\slisten-address (\s(?P<ip_address>\S+))?
+ $""",
+ re.VERBOSE),
+ "setval": "system ntp listen-address {{listen_addresses}}",
+ "result": {
+ "listen_addresses": ["{{ip_address}}"]
+ }
+ },
+
+ # set system ntp listen_address
+ {
+ "name": "listen_addresses_delete",
+ "getval": re.compile(
+ r"""
+ ^set\ssystem\sntp\slisten-address
+ $""",
+ re.VERBOSE),
+ "setval": "system ntp listen-address",
+ "result": {
+ }
+ },
+
+ # set system ntp server <name>
+ {
+ "name": "server",
+ "getval": re.compile(
+ r"""
+ ^set\ssystem\sntp\sserver (\s(?P<name>\S+))?
+ $""",
+ re.VERBOSE),
+ "setval": "system ntp server {{server}}",
+ "result": {
+ "servers": {
+ "{{name}}": {
+ "server": "{{name}}"
+ }
+ }
+
+ }
+ },
+
+ # set system ntp server <name> <options>
+ {
+ "name": "options",
+ "getval": re.compile(
+ r"""
+ ^set\ssystem\sntp\sserver
+ \s(?P<name>\S+)
+ \s(?P<options>noselect|dynamic|preempt|prefer)?
+ $""",
+ re.VERBOSE),
+ "setval": "system ntp server {{server}} {{options}}",
+ "result": {
+ "servers": {
+ "{{name}}": {
+ "server": "{{name}}",
+ "options": ["{{options}}"]
+ }
+ }
+ }
+ }
+ ]
+ # fmt: on