summaryrefslogtreecommitdiffstats
path: root/ansible_collections/cisco/meraki/plugins/modules/meraki_snmp.py
blob: 52d4dbbbbad6b8f7ab078c447ee21087de430bc8 (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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2018, Kevin Breit (@kbreit) <kevin.breit@kevinbreit.net>
# 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

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    "status": ['deprecated'],
    'supported_by': 'community'
}

DOCUMENTATION = r'''
---
module: meraki_snmp
short_description: Manage organizations in the Meraki cloud
description:
- Allows for management of SNMP settings for Meraki.
deprecated:
  removed_in: '3.0.0'
  why: Updated modules released with increased functionality
  alternative: cisco.meraki.networks_snmp
options:
    state:
        description:
        - Specifies whether SNMP information should be queried or modified.
        choices: ['query', 'present']
        default: present
        type: str
    v2c_enabled:
        description:
        - Specifies whether SNMPv2c is enabled.
        type: bool
    v3_enabled:
        description:
        - Specifies whether SNMPv3 is enabled.
        type: bool
    v3_auth_mode:
        description:
        - Sets authentication mode for SNMPv3.
        choices: ['MD5', 'SHA']
        type: str
    v3_auth_pass:
        description:
        - Authentication password for SNMPv3.
        - Must be at least 8 characters long.
        type: str
    v3_priv_mode:
        description:
        - Specifies privacy mode for SNMPv3.
        choices: ['DES', 'AES128']
        type: str
    v3_priv_pass:
        description:
        - Privacy password for SNMPv3.
        - Must be at least 8 characters long.
        type: str
    peer_ips:
        description:
        - List of IP addresses which can perform SNMP queries.
        type: list
        elements: str
    net_name:
        description:
        - Name of network.
        type: str
    net_id:
        description:
        - ID of network.
        type: str
    access:
        description:
        - Type of SNMP access.
        choices: [community, none, users]
        type: str
    community_string:
        description:
        - SNMP community string.
        - Only relevant if C(access) is set to C(community).
        type: str
    users:
        description:
        - Information about users with access to SNMP.
        - Only relevant if C(access) is set to C(users).
        type: list
        elements: dict
        suboptions:
            username:
                description: Username of user with access.
                type: str
            passphrase:
                description: Passphrase for user SNMP access.
                type: str
author:
- Kevin Breit (@kbreit)
extends_documentation_fragment: cisco.meraki.meraki
'''

EXAMPLES = r'''
- name: Query SNMP values
  meraki_snmp:
    auth_key: abc12345
    org_name: YourOrg
    state: query
  delegate_to: localhost

- name: Enable SNMPv2
  meraki_snmp:
    auth_key: abc12345
    org_name: YourOrg
    state: present
    v2c_enabled: yes
  delegate_to: localhost

- name: Disable SNMPv2
  meraki_snmp:
    auth_key: abc12345
    org_name: YourOrg
    state: present
    v2c_enabled: no
  delegate_to: localhost

- name: Enable SNMPv3
  meraki_snmp:
    auth_key: abc12345
    org_name: YourOrg
    state: present
    v3_enabled: true
    v3_auth_mode: SHA
    v3_auth_pass: ansiblepass
    v3_priv_mode: AES128
    v3_priv_pass: ansiblepass
    peer_ips: 192.0.1.1;192.0.1.2
  delegate_to: localhost

- name: Set network access type to community string
  meraki_snmp:
    auth_key: abc1235
    org_name: YourOrg
    net_name: YourNet
    state: present
    access: community
    community_string: abc123
  delegate_to: localhost

- name: Set network access type to username
  meraki_snmp:
    auth_key: abc1235
    org_name: YourOrg
    net_name: YourNet
    state: present
    access: users
    users:
      - username: ansibleuser
        passphrase: ansiblepass
  delegate_to: localhost
'''

RETURN = r'''
data:
    description: Information about SNMP settings.
    type: complex
    returned: always
    contains:
        hostname:
            description: Hostname of SNMP server.
            returned: success and no network specified.
            type: str
            sample: n1.meraki.com
        peer_ips:
            description: Semi-colon delimited list of IPs which can poll SNMP information.
            returned: success and no network specified.
            type: str
            sample: 192.0.1.1
        port:
            description: Port number of SNMP.
            returned: success and no network specified.
            type: str
            sample: 16100
        v2c_enabled:
            description: Shows enabled state of SNMPv2c
            returned: success and no network specified.
            type: bool
            sample: true
        v3_enabled:
            description: Shows enabled state of SNMPv3
            returned: success and no network specified.
            type: bool
            sample: true
        v3_auth_mode:
            description: The SNMP version 3 authentication mode either MD5 or SHA.
            returned: success and no network specified.
            type: str
            sample: SHA
        v3_priv_mode:
            description: The SNMP version 3 privacy mode DES or AES128.
            returned: success and no network specified.
            type: str
            sample: AES128
        v2_community_string:
            description: Automatically generated community string for SNMPv2c.
            returned: When SNMPv2c is enabled and no network specified.
            type: str
            sample: o/8zd-JaSb
        v3_user:
            description: Automatically generated username for SNMPv3.
            returned: When SNMPv3c is enabled and no network specified.
            type: str
            sample: o/8zd-JaSb
        access:
            description: Type of SNMP access.
            type: str
            returned: success, when network specified
        community_string:
            description: SNMP community string. Only relevant if C(access) is set to C(community).
            type: str
            returned: success, when network specified
        users:
            description: Information about users with access to SNMP. Only relevant if C(access) is set to C(users).
            type: complex
            contains:
                username:
                    description: Username of user with access.
                    type: str
                    returned: success, when network specified
                passphrase:
                    description: Passphrase for user SNMP access.
                    type: str
                    returned: success, when network specified
'''

from ansible.module_utils.basic import AnsibleModule, json
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec


def get_snmp(meraki, org_id):
    path = meraki.construct_path('get_all', org_id=org_id)
    r = meraki.request(path,
                       method='GET',
                       )
    if meraki.status == 200:
        return r


def set_snmp(meraki, org_id):
    payload = dict()
    if meraki.params['v2c_enabled'] is not None:
        payload = {'v2cEnabled': meraki.params['v2c_enabled'],
                   }
    if meraki.params['v3_enabled'] is True:
        if len(meraki.params['v3_auth_pass']) < 8 or len(meraki.params['v3_priv_pass']) < 8:
            meraki.fail_json(msg='v3_auth_pass and v3_priv_pass must both be at least 8 characters long.')
        if meraki.params['v3_auth_mode'] is None or \
           meraki.params['v3_auth_pass'] is None or \
           meraki.params['v3_priv_mode'] is None or \
           meraki.params['v3_priv_pass'] is None:
            meraki.fail_json(msg='v3_auth_mode, v3_auth_pass, v3_priv_mode, and v3_auth_pass are required')
        payload = {'v3Enabled': meraki.params['v3_enabled'],
                   'v3AuthMode': meraki.params['v3_auth_mode'].upper(),
                   'v3AuthPass': meraki.params['v3_auth_pass'],
                   'v3PrivMode': meraki.params['v3_priv_mode'].upper(),
                   'v3PrivPass': meraki.params['v3_priv_pass'],
                   }
        if meraki.params['peer_ips'] is not None:
            payload['peerIps'] = meraki.params['peer_ips']
    elif meraki.params['v3_enabled'] is False:
        payload = {'v3Enabled': False}
    full_compare = snake_dict_to_camel_dict(payload)
    path = meraki.construct_path('create', org_id=org_id)
    snmp = get_snmp(meraki, org_id)
    ignored_parameters = ['v3AuthPass', 'v3PrivPass', 'hostname', 'port', 'v2CommunityString', 'v3User']
    if meraki.is_update_required(snmp, full_compare, optional_ignore=ignored_parameters):
        if meraki.module.check_mode is True:
            meraki.generate_diff(snmp, full_compare)
            snmp.update(payload)
            meraki.result['data'] = snmp
            meraki.result['changed'] = True
            meraki.exit_json(**meraki.result)
        r = meraki.request(path,
                           method='PUT',
                           payload=json.dumps(payload))
        if meraki.status == 200:
            meraki.generate_diff(snmp, r)
            meraki.result['changed'] = True
            return r
    else:
        return snmp


def main():

    # define the available arguments/parameters that a user can pass to
    # the module
    user_arg_spec = dict(username=dict(type='str'),
                         passphrase=dict(type='str', no_log=True),
                         )

    argument_spec = meraki_argument_spec()
    argument_spec.update(state=dict(type='str', choices=['present', 'query'], default='present'),
                         v2c_enabled=dict(type='bool'),
                         v3_enabled=dict(type='bool'),
                         v3_auth_mode=dict(type='str', choices=['SHA', 'MD5']),
                         v3_auth_pass=dict(type='str', no_log=True),
                         v3_priv_mode=dict(type='str', choices=['DES', 'AES128']),
                         v3_priv_pass=dict(type='str', no_log=True),
                         peer_ips=dict(type='list', default=None, elements='str'),
                         access=dict(type='str', choices=['none', 'community', 'users']),
                         community_string=dict(type='str', no_log=True),
                         users=dict(type='list', default=None, elements='dict', options=user_arg_spec),
                         net_name=dict(type='str'),
                         net_id=dict(type='str'),
                         )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           )
    meraki = MerakiModule(module, function='snmp')
    meraki.params['follow_redirects'] = 'all'

    query_urls = {'snmp': '/organizations/{org_id}/snmp'}
    query_net_urls = {'snmp': '/networks/{net_id}/snmp'}
    update_urls = {'snmp': '/organizations/{org_id}/snmp'}
    update_net_urls = {'snmp': '/networks/{net_id}/snmp'}

    meraki.url_catalog['get_all'].update(query_urls)
    meraki.url_catalog['query_net_all'] = query_net_urls
    meraki.url_catalog['create'] = update_urls
    meraki.url_catalog['create_net'] = update_net_urls

    payload = None

    if not meraki.params['org_name'] and not meraki.params['org_id']:
        meraki.fail_json(msg='org_name or org_id is required')

    org_id = meraki.params['org_id']
    if org_id is None:
        org_id = meraki.get_org_id(meraki.params['org_name'])
    net_id = meraki.params['net_id']
    if net_id is None and meraki.params['net_name']:
        nets = meraki.get_nets(org_id=org_id)
        net_id = meraki.get_net_id(org_id, meraki.params['net_name'], data=nets)

    if meraki.params['state'] == 'present':
        if net_id is not None:
            payload = {'access': meraki.params['access']}
            if meraki.params['community_string'] is not None:
                payload['communityString'] = meraki.params['community_string']
            elif meraki.params['users'] is not None:
                payload['users'] = meraki.params['users']

    if meraki.params['state'] == 'query':
        if net_id is None:
            meraki.result['data'] = get_snmp(meraki, org_id)
        else:
            path = meraki.construct_path('query_net_all', net_id=net_id)
            response = meraki.request(path, method='GET')
            if meraki.status == 200:
                meraki.result['data'] = response
    elif meraki.params['state'] == 'present':
        if net_id is None:
            meraki.result['data'] = set_snmp(meraki, org_id)
        else:
            path = meraki.construct_path('query_net_all', net_id=net_id)
            original = meraki.request(path, method='GET')
            if meraki.is_update_required(original, payload):
                path = meraki.construct_path('create_net', net_id=net_id)
                response = meraki.request(path, method='PUT', payload=json.dumps(payload))
                if meraki.status == 200:
                    if response['access'] == 'none':
                        meraki.result['data'] = {}
                    else:
                        meraki.result['data'] = response
                    meraki.result['changed'] = True
            else:
                meraki.result['data'] = original

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    meraki.exit_json(**meraki.result)


if __name__ == '__main__':
    main()