summaryrefslogtreecommitdiffstats
path: root/ansible_collections/cisco/nxos/plugins/modules/nxos_snmp_traps.py
blob: fce1a8a20674ab95f0d5ce01a05ffc84506bbffc (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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import absolute_import, division, print_function


__metaclass__ = type


DOCUMENTATION = """
module: nxos_snmp_traps
extends_documentation_fragment:
- cisco.nxos.nxos
short_description: (deprecated, removed after 2024-01-01) Manages SNMP traps.
description:
- Manages SNMP traps configurations.
version_added: 1.0.0
deprecated:
  alternative: nxos_snmp_server
  why: Updated modules released with more functionality
  removed_at_date: '2024-01-01'
author:
- Jason Edelman (@jedelman8)
notes:
- Tested against NXOSv 7.3.(0)D1(1) on VIRL
- Limited Support for Cisco MDS
- This module works at the group level for traps.  If you need to only enable/disable
  1 specific trap within a group, use the M(cisco.nxos.nxos_command) module.
- Be aware that you can set a trap only for an enabled feature.
options:
  group:
    description:
    - Case sensitive group.
    required: true
    choices:
    - aaa
    - bfd
    - bgp
    - bridge
    - callhome
    - cfs
    - config
    - eigrp
    - entity
    - feature-control
    - generic
    - hsrp
    - license
    - link
    - lldp
    - mmode
    - ospf
    - pim
    - rf
    - rmon
    - snmp
    - storm-control
    - stpx
    - switchfabric
    - syslog
    - sysmgr
    - system
    - upgrade
    - vtp
    - all
    type: str
  state:
    description:
    - Manage the state of the resource.
    required: false
    default: enabled
    choices:
    - enabled
    - disabled
    type: str
"""

EXAMPLES = """
# ensure lldp trap configured
- cisco.nxos.nxos_snmp_traps:
    group: lldp
    state: enabled

# ensure lldp trap is not configured
- cisco.nxos.nxos_snmp_traps:
    group: lldp
    state: disabled
"""

RETURN = """
commands:
    description: command sent to the device
    returned: always
    type: list
    sample: "snmp-server enable traps lldp ;"
"""


from ansible.module_utils.basic import AnsibleModule

from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
    get_capabilities,
    load_config,
    run_commands,
)


def get_platform_id(module):
    info = get_capabilities(module).get("device_info", {})
    return info.get("network_os_platform", "")


def execute_show_command(command, module):
    command = {"command": command, "output": "text"}

    return run_commands(module, command)


def flatten_list(command_lists):
    flat_command_list = []
    for command in command_lists:
        if isinstance(command, list):
            flat_command_list.extend(command)
        else:
            flat_command_list.append(command)
    return flat_command_list


def get_snmp_traps(group, module):
    body = execute_show_command("show run snmp all", module)[0].split("\n")

    resource = {}
    feature_list = [
        "aaa",
        "bfd",
        "bgp",
        "bridge",
        "callhome",
        "cfs",
        "config",
        "eigrp",
        "entity",
        "feature-control",
        "generic",
        "hsrp",
        "license",
        "link",
        "lldp",
        "mmode",
        "ospf",
        "pim",
        "rf",
        "rmon",
        "snmp",
        "storm-control",
        "stpx",
        "switchfabric",
        "syslog",
        "sysmgr",
        "system",
        "upgrade",
        "vtp",
    ]

    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")
        feature_list.remove("bfd")

    for each in feature_list:
        for line in body:
            if each == "ospf":
                # ospf behaves differently when routers are present
                if "snmp-server enable traps ospf" == line:
                    resource[each] = True
                    break
            else:
                if "enable traps {0}".format(each) in line:
                    if "no " in line:
                        resource[each] = False
                        break
                    else:
                        resource[each] = True

    for each in feature_list:
        if resource.get(each) is None:
            # on some platforms, the 'no' cmd does not
            # show up and so check if the feature is enabled
            body = execute_show_command("show run | inc feature", module)[0]
            if "feature {0}".format(each) in body:
                resource[each] = False

    find = resource.get(group, None)

    if group == "all".lower():
        return resource
    elif find is not None:
        trap_resource = {group: find}
        return trap_resource
    else:
        # if 'find' is None, it means that 'group' is a
        # currently disabled feature.
        return {}


def get_trap_commands(group, state, existing, module):
    commands = []
    enabled = False
    disabled = False

    if group == "all":
        if state == "disabled":
            for feature in existing:
                if existing[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)
                    commands.append(trap_command)

    else:
        if group in existing:
            if existing[group]:
                enabled = True
            else:
                disabled = True

            if state == "disabled" and enabled:
                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))

    return commands


def main():
    argument_spec = dict(
        state=dict(choices=["enabled", "disabled"], default="enabled"),
        group=dict(
            choices=[
                "aaa",
                "bfd",
                "bgp",
                "bridge",
                "callhome",
                "cfs",
                "config",
                "eigrp",
                "entity",
                "feature-control",
                "generic",
                "hsrp",
                "license",
                "link",
                "lldp",
                "mmode",
                "ospf",
                "pim",
                "rf",
                "rmon",
                "snmp",
                "storm-control",
                "stpx",
                "switchfabric",
                "syslog",
                "sysmgr",
                "system",
                "upgrade",
                "vtp",
                "all",
            ],
            required=True,
        ),
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    warnings = list()
    results = {"changed": False, "commands": [], "warnings": warnings}

    group = module.params["group"].lower()
    state = module.params["state"]

    existing = get_snmp_traps(group, module)

    commands = get_trap_commands(group, state, existing, module)
    cmds = flatten_list(commands)
    if cmds:
        results["changed"] = True
        if not module.check_mode:
            load_config(module, cmds)

        if "configure" in cmds:
            cmds.pop(0)
        results["commands"] = cmds

    module.exit_json(**results)


if __name__ == "__main__":
    main()