summaryrefslogtreecommitdiff
path: root/plugins/modules/vyos_lldp_global.py
blob: 9ebbac09f15abccd6e66cd98d2a5a59157279c4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+
from __future__ import absolute_import, division, print_function


__metaclass__ = type

DOCUMENTATION = r"""
---
module: vyos_lldp_global
short_description: Manage LLDP global configuration on VyOS via REST API.
description:
  - Manage LLDP global configuration on VyOS via REST API.
  - Uses C(ansible_connection=ansible.netcommon.httpapi).
version_added: "1.0.0"
author: VyOS Community (@vyos)
options:
  config:
    description: LLDP global configuration.
    type: dict
    suboptions:
      enable:
        description: Enable LLDP service.
        type: bool
      addresses:
        description: List of management addresses to advertise.
        type: list
        elements: str
      snmp:
        description:
          - C(enable) to enable LLDP SNMP subagent.
          - C(disable) to disable it.
          - Requires SNMP service to be configured on the device.
        type: str
      legacy_protocols:
        description: Legacy protocols to support.
        type: list
        elements: str
        choices: [cdp, edp, fdp, sonmp]
  state:
    description:
      - C(merged) - merge config with existing.
      - C(replaced) - replace existing config with provided.
      - C(deleted) - delete LLDP configuration.
      - C(gathered) - return current config without changes.
    type: str
    default: merged
    choices: [merged, replaced, deleted, gathered]
"""

EXAMPLES = r"""
- name: Enable LLDP with management address and legacy protocols
  vyos.rest.vyos_lldp_global:
    config:
      enable: true
      addresses:
        - 192.0.2.17
      legacy_protocols:
        - cdp
        - fdp
    state: merged

- name: Replace LLDP configuration
  vyos.rest.vyos_lldp_global:
    config:
      enable: true
      addresses:
        - 192.0.2.99
    state: replaced

- name: Delete all LLDP configuration
  vyos.rest.vyos_lldp_global:
    state: deleted

- name: Gather current LLDP configuration
  vyos.rest.vyos_lldp_global:
    state: gathered
  register: result
"""

RETURN = r"""
before:
  description: LLDP configuration before the module ran.
  returned: always
  type: dict
after:
  description: LLDP configuration after the module ran.
  returned: when changed
  type: dict
commands:
  description: List of commands sent to the device.
  returned: always
  type: list
gathered:
  description: Current LLDP configuration from the device.
  returned: when state is gathered
  type: dict
"""

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.vyos.rest.plugins.module_utils.vyos import VyOSModule


_BASE = ["service", "lldp"]


def _get(vyos):
    raw = vyos.get_config(_BASE)
    if not raw:
        return {}
    result = {}
    if isinstance(raw, dict):
        result["enable"] = True
        if "management-address" in raw:
            v = raw["management-address"]
            result["addresses"] = (
                sorted(list(v.keys()))
                if isinstance(v, dict)
                else ([v] if isinstance(v, str) else sorted(list(v)))
            )
        if "snmp" in raw:
            result["snmp"] = "enable"
        if "legacy-protocols" in raw:
            v = raw["legacy-protocols"]
            result["legacy_protocols"] = (
                sorted(list(v.keys()))
                if isinstance(v, dict)
                else ([v] if isinstance(v, str) else sorted(list(v)))
            )
    return result


def _build(want, have, state):
    cmds = []

    if state == "deleted":
        if have:
            cmds.append(("delete", _BASE))
        return cmds

    if state == "replaced":
        # only wipe and rebuild if have differs from want
        want_addrs = sorted(want.get("addresses") or [])
        have_addrs = sorted(have.get("addresses") or [])
        want_protos = sorted(want.get("legacy_protocols") or [])
        have_protos = sorted(have.get("legacy_protocols") or [])
        want_snmp = want.get("snmp")
        have_snmp = have.get("snmp")
        want_enable = bool(want.get("enable"))
        have_enable = bool(have.get("enable"))

        if (
            want_addrs != have_addrs
            or want_protos != have_protos
            or want_snmp != have_snmp
            or want_enable != have_enable
        ):
            if have:
                cmds.append(("delete", _BASE))
            # fall through to set everything from want
        else:
            return cmds  # already matches — idempotent

    # enable
    if want.get("enable") and not have.get("enable"):
        cmds.append(("set", _BASE))

    # addresses
    have_addrs_set = set(have.get("addresses") or []) if state != "replaced" else set()
    for addr in want.get("addresses") or []:
        if addr not in have_addrs_set:
            cmds.append(("set", _BASE + ["management-address", addr]))

    # snmp
    if want.get("snmp"):
        if want["snmp"] == "disable" and have.get("snmp"):
            cmds.append(("delete", _BASE + ["snmp"]))
        elif want["snmp"] != "disable" and not have.get("snmp"):
            cmds.append(("set", _BASE + ["snmp"]))

    # legacy_protocols
    have_protos_set = set(have.get("legacy_protocols") or []) if state != "replaced" else set()
    for p in want.get("legacy_protocols") or []:
        if p not in have_protos_set:
            cmds.append(("set", _BASE + ["legacy-protocols", p]))

    return cmds


def main():
    module = AnsibleModule(
        argument_spec=dict(
            config=dict(
                type="dict",
                options=dict(
                    enable=dict(type="bool"),
                    addresses=dict(type="list", elements="str"),
                    snmp=dict(type="str"),
                    legacy_protocols=dict(
                        type="list",
                        elements="str",
                        choices=["cdp", "edp", "fdp", "sonmp"],
                    ),
                ),
            ),
            state=dict(
                default="merged",
                choices=["merged", "replaced", "deleted", "gathered"],
            ),
        ),
        supports_check_mode=True,
    )

    vyos = VyOSModule(module)
    state = module.params["state"]
    config = module.params.get("config") or {}
    have = _get(vyos)

    if state == "gathered":
        module.exit_json(changed=False, gathered=have)

    commands = _build(config, have, state)

    if module.check_mode:
        module.exit_json(changed=bool(commands), commands=commands, before=have)

    if commands:
        response = vyos.apply_commands(commands)
        saved = vyos.save_config()
        module.exit_json(
            changed=True,
            before=have,
            after=_get(vyos),
            commands=commands,
            saved=saved,
            response=response,
        )

    module.exit_json(changed=False, before=have, after=have, commands=[])


if __name__ == "__main__":
    main()