Debian Codegraph @

ansible_collections/cisco/intersight/plugins/modules/intersight_snmp_policy.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 ANSIBLE_METADATA = {'metadata_version': '1.1',
10 'status': ['preview'],
11 'supported_by': 'community'}
12
13 DOCUMENTATION = r'''
14 ---
15 module: intersight_snmp_policy
16 short_description: SNMP Policy configuration for Cisco Intersight
17 description:
18 - Manages SNMP Policy configuration on Cisco Intersight.
19 - A policy to configure SNMP settings for Cisco Intersight managed servers.
20 - Supports both SNMPv2c and SNMPv3 configurations with users, traps, and community strings.
21 - For more information see L(Cisco Intersight,https://intersight.com/apidocs/snmp/Policy/get/).
22 extends_documentation_fragment: intersight
23 options:
24 state:
25 description:
26 - If C(present), will verify the resource is present and will create if needed.
27 - If C(absent), will verify the resource is absent and will delete if needed.
28 type: str
29 choices: [present, absent]
30 default: present
31 organization:
32 description:
33 - The name of the Organization this resource is assigned to.
34 - Profiles, Policies, and Pools that are created within a Custom Organization are applicable only to devices in the same Organization.
35 type: str
36 default: default
37 name:
38 description:
39 - The name assigned to the SNMP Policy.
40 - The name must be between 1 and 62 alphanumeric characters, allowing special characters :-_.
41 type: str
42 required: true
43 description:
44 description:
45 - The user-defined description for the SNMP Policy.
46 - Description can contain letters(a-z, A-Z), numbers(0-9), hyphen(-), period(.), colon(:), or an underscore(_).
47 type: str
48 aliases: [descr]
49 tags:
50 description:
51 - List of tags in Key:<user-defined key> Value:<user-defined value> format.
52 type: list
53 elements: dict
54 enabled:
55 description:
56 - State of the SNMP Policy on the endpoint.
57 - If enabled, the endpoint sends SNMP traps to the designated host.
58 type: bool
59 default: true
60 v2c_enabled:
61 description:
62 - State of the SNMPv2c protocol.
63 - When enabled, SNMPv2c access is available for the associated servers.
64 type: bool
65 default: true
66 v3_enabled:
67 description:
68 - State of the SNMPv3 protocol.
69 - When enabled, SNMPv3 access is available for the associated servers.
70 type: bool
71 default: true
72 snmp_port:
73 description:
74 - Port on which Cisco IMC SNMP agent runs. Enter a value between 1-65535.
75 - Reserved ports not allowed (22, 23, 80, 123, 389, 443, 623, 636, 2068, 3268, 3269).
76 type: int
77 default: 161
78 sys_contact:
79 description:
80 - Contact person responsible for the SNMP implementation.
81 - Enter a string up to 64 characters, such as an email address or a name and telephone number.
82 - Required when C(enabled) is C(true).
83 type: str
84 sys_location:
85 description:
86 - Location of the host on which the SNMP agent (server) runs.
87 - Required when C(enabled) is C(true).
88 type: str
89 community_access:
90 description:
91 - Controls access to the information in the inventory tables.
92 - Applicable only for SNMPv2c users.
93 - For SNMPv3, this is always set to C(Disabled).
94 - For SNMPv2c, valid choices are C(Disabled), C(Limited), and C(Full).
95 - Required when C(enabled) is C(true).
96 type: str
97 choices: [Disabled, Limited, Full]
98 default: Disabled
99 access_community_string:
100 description:
101 - The default SNMPv1, SNMPv2c community name or SNMPv3 username to include on any trap messages sent to the SNMP host.
102 - The name can be 32 characters long.
103 - Used with SNMPv2c access only.
104 type: str
105 trap_community:
106 description:
107 - SNMP community group used for sending SNMP trap to other devices.
108 - Valid only for SNMPv2c users.
109 type: str
110 engine_input_id:
111 description:
112 - User-defined unique identification of the static engine.
113 - Used with SNMPv3 only.
114 type: str
115 snmp_users:
116 description:
117 - List of SNMP users for SNMPv3 authentication.
118 type: list
119 elements: dict
120 suboptions:
121 name:
122 description:
123 - SNMP username.
124 - Must have a minimum of 1 and and a maximum of 31 characters.
125 type: str
126 required: true
127 security_level:
128 description:
129 - Security mechanism used for communication between agent and manager.
130 type: str
131 choices: [AuthPriv, AuthNoPriv]
132 default: AuthPriv
133 auth_password:
134 description:
135 - Authorization password for the user.
136 - Required when security_level is AuthPriv or AuthNoPriv.
137 type: str
138 required: true
139 privacy_password:
140 description:
141 - Privacy password for the SNMP user.
142 - Required when security_level is AuthPriv.
143 type: str
144 snmp_traps:
145 description:
146 - List of SNMP trap destinations.
147 type: list
148 elements: dict
149 suboptions:
150 enabled:
151 description:
152 - Enables/disables the trap on the server If enabled, trap is active on the server.
153 type: bool
154 default: true
155 version:
156 description:
157 - SNMP version for the trap.
158 type: str
159 choices: [V2, V3]
160 required: true
161 community:
162 description:
163 - SNMP community group used for sending SNMP trap to other devices.
164 - Applicable only for SNMP v2c.
165 type: str
166 user:
167 description:
168 - SNMP user for the trap.
169 - Applicable only to SNMPv3.
170 type: str
171 type:
172 description:
173 - Type of trap which decides whether to receive a notification when a trap is received at the destination.
174 - Note that 'Inform' is only supported for V2 traps, V3 traps only support 'Trap' type.
175 type: str
176 choices: [Trap, Inform]
177 default: Trap
178 destination:
179 description:
180 - IP address or hostname of the trap destination.
181 type: str
182 required: true
183 port:
184 description:
185 - Port number for the trap destination.
186 type: int
187 default: 162
188 author:
189 - Ron Gershburg (@rgershbu)
190 '''
191
192 EXAMPLES = r'''
193 - name: Create SNMP Policy with SNMPv2 and SNMPv3 enabled
194 cisco.intersight.intersight_snmp_policy:
195 api_private_key: "{{ api_private_key }}"
196 api_key_id: "{{ api_key_id }}"
197 organization: "default"
198 name: "mixed-snmp-policy"
199 description: "SNMP policy with both v2 and v3 enabled"
200 enabled: true
201 v2c_enabled: true
202 v3_enabled: true
203 snmp_port: 161
204 sys_contact: "[email protected]"
205 sys_location: "Data Center A"
206 community_access: "Full"
207 access_community_string: "public"
208 trap_community: "trapcomm"
209 engine_input_id: "custom-engine-id"
210 snmp_users:
211 - name: "admin"
212 security_level: "AuthPriv"
213 auth_password: "authpassword123"
214 privacy_password: "privpassword123"
215 - name: "readonly"
216 security_level: "AuthNoPriv"
217 auth_password: "readonlypass123"
218 snmp_traps:
219 - enabled: true
220 version: "V2"
221 community: "trapcomm"
222 type: "Trap"
223 destination: "192.168.1.100"
224 port: 162
225 - enabled: true
226 version: "V3"
227 user: "admin"
228 type: "Trap"
229 destination: "192.168.1.101"
230 port: 162
231 tags:
232 - Key: "Environment"
233 Value: "Production"
234 state: present
235
236 - name: Create SNMP Policy with only SNMPv3 enabled
237 cisco.intersight.intersight_snmp_policy:
238 api_private_key: "{{ api_private_key }}"
239 api_key_id: "{{ api_key_id }}"
240 name: "v3-only-snmp-policy"
241 description: "SNMP policy with only v3 enabled"
242 enabled: true
243 v2c_enabled: false
244 v3_enabled: true
245 snmp_port: 161
246 sys_contact: "[email protected]"
247 sys_location: "Data Center B"
248 engine_input_id: "v3-engine-id"
249 snmp_users:
250 - name: "v3user"
251 security_level: "AuthPriv"
252 auth_password: "v3authpass123"
253 privacy_password: "v3privpass123"
254 state: present
255
256 - name: Create SNMP Policy with only SNMPv2 enabled
257 cisco.intersight.intersight_snmp_policy:
258 api_private_key: "{{ api_private_key }}"
259 api_key_id: "{{ api_key_id }}"
260 name: "v2-only-snmp-policy"
261 description: "SNMP policy with only v2 enabled"
262 enabled: true
263 v2c_enabled: true
264 v3_enabled: false
265 snmp_port: 161
266 sys_contact: "[email protected]"
267 sys_location: "Data Center C"
268 community_access: "Limited"
269 access_community_string: "readonly"
270 trap_community: "v2traps"
271 state: present
272
273 - name: Create disabled SNMP Policy
274 cisco.intersight.intersight_snmp_policy:
275 api_private_key: "{{ api_private_key }}"
276 api_key_id: "{{ api_key_id }}"
277 name: "disabled-snmp-policy"
278 description: "Disabled SNMP policy"
279 enabled: false
280 state: present
281
282 - name: Delete SNMP Policy
283 cisco.intersight.intersight_snmp_policy:
284 api_private_key: "{{ api_private_key }}"
285 api_key_id: "{{ api_key_id }}"
286 name: "mixed-snmp-policy"
287 state: absent
288 '''
289
290 RETURN = r'''
291 api_response:
292 description: The API response output returned by the specified resource.
293 returned: always
294 type: dict
295 sample:
296 "api_response": {
297 "Name": "mixed-snmp-policy",
298 "ObjectType": "snmp.Policy",
299 "Enabled": true,
300 "V2Enabled": true,
301 "V3Enabled": true,
302 "SnmpPort": 161,
303 "SysContact": "[email protected]",
304 "SysLocation": "Data Center A",
305 "CommunityAccess": "Full",
306 "AccessCommunityString": "public",
307 "TrapCommunity": "trapcomm",
308 "EngineId": "custom-engine-id",
309 "SnmpUsers": [
310 {
311 "Name": "admin",
312 "SecurityLevel": "AuthPriv",
313 "AuthType": "SHA",
314 "IsAuthPasswordSet": true,
315 "PrivacyType": "AES",
316 "IsPrivacyPasswordSet": true
317 }
318 ],
319 "SnmpTraps": [
320 {
321 "Enabled": true,
322 "Version": "V2",
323 "Community": "trapcomm",
324 "Type": "Trap",
325 "Destination": "192.168.1.100",
326 "Port": 162
327 }
328 ],
329 "Tags": [
330 {
331 "Key": "Environment",
332 "Value": "Production"
333 }
334 ]
335 }
336 '''
337
338 from ansible.module_utils.basic import AnsibleModule
339 from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec
340
341
342 def get_argument_spec():
343 snmp_user_spec = dict(
344 name=dict(type='str', required=True),
345 security_level=dict(type='str', choices=['AuthPriv', 'AuthNoPriv'], default='AuthPriv'),
346 auth_password=dict(type='str', no_log=True, required=True),
347 privacy_password=dict(type='str', no_log=True)
348 )
349
350 snmp_trap_spec = dict(
351 enabled=dict(type='bool', default=True),
352 version=dict(type='str', choices=['V2', 'V3'], required=True),
353 community=dict(type='str'),
354 user=dict(type='str'),
355 type=dict(type='str', choices=['Trap', 'Inform'], default='Trap'),
356 destination=dict(type='str', required=True),
357 port=dict(type='int', default=162)
358 )
359
360 argument_spec = intersight_argument_spec.copy()
361 argument_spec.update(
362 state=dict(type='str', choices=['present', 'absent'], default='present'),
363 organization=dict(type='str', default='default'),
364 name=dict(type='str', required=True),
365 description=dict(type='str', aliases=['descr']),
366 tags=dict(type='list', elements='dict'),
367 enabled=dict(type='bool', default=True),
368 v2c_enabled=dict(type='bool', default=True),
369 v3_enabled=dict(type='bool', default=True),
370 snmp_port=dict(type='int', default=161),
371 sys_contact=dict(type='str'),
372 sys_location=dict(type='str'),
373 community_access=dict(type='str', choices=['Disabled', 'Limited', 'Full'], default='Disabled'),
374 access_community_string=dict(type='str'),
375 trap_community=dict(type='str'),
376 engine_input_id=dict(type='str'),
377 snmp_users=dict(type='list', elements='dict', options=snmp_user_spec),
378 snmp_traps=dict(type='list', elements='dict', options=snmp_trap_spec)
379 )
380 return argument_spec
381
382
383 def validate_snmp_configuration(module):
384 """
385 Validate SNMP configuration parameters.
386 """
387 params = module.params
388 if params['state'] == 'present':
389 # If SNMP is disabled, we don't need to validate other parameters
390 if not params['enabled']:
391 return
392
393 # If SNMP is enabled, at least one version must be enabled
394 if not params['v2c_enabled'] and not params['v3_enabled']:
395 module.fail_json(msg="At least one of v2c_enabled or v3_enabled must be true when SNMP is enabled")
396
397 # Check if both sys_contact and sys_location are provided when SNMP is enabled
398 if not params.get('sys_contact') or not params.get('sys_location'):
399 module.fail_json(msg="sys_contact and sys_location are required when SNMP is enabled")
400
401 # SNMPv3 users can only be specified when SNMPv3 is enabled
402 if not params['v3_enabled'] and params.get('snmp_users'):
403 module.fail_json(msg="snmp_users cannot be specified when v3_enabled is false")
404
405 # SNMPv3 only specific validations
406 if params['v3_enabled'] and not params['v2c_enabled']:
407 # For SNMPv3, community access is always Disabled
408 if params['community_access'] != 'Disabled':
409 module.fail_json(msg="community_access must be 'Disabled' when v3_enabled is true and v2c_enabled is false")
410
411 # Validate SNMP users
412 if params.get('snmp_users'):
413 for user in params['snmp_users']:
414 if not user.get('auth_password'):
415 module.fail_json(msg="auth_password is required for security_level 'AuthPriv' or 'AuthNoPriv'")
416
417 if user['security_level'] == 'AuthPriv' and not user.get('privacy_password'):
418 module.fail_json(msg="privacy_password is required for security_level 'AuthPriv'")
419
420 # Validate SNMP traps
421 if params.get('snmp_traps'):
422 for trap in params['snmp_traps']:
423 if trap['version'] == 'V2' and not params['v2c_enabled']:
424 module.fail_json(msg="SNMP trap version 'V2' is not supported when v2c_enabled is false")
425 elif trap['version'] == 'V3' and not params['v3_enabled']:
426 module.fail_json(msg="SNMP trap version 'V3' is not supported when v3_enabled is false")
427
428 if trap['version'] == 'V2' and not trap.get('community'):
429 module.fail_json(msg="community is required for SNMP trap version 'V2'")
430 elif trap['version'] == 'V3' and not trap.get('user'):
431 module.fail_json(msg="user is required for SNMP trap version 'V3'")
432
433 # V3 traps only support 'Trap' type, not 'Inform'
434 if trap['version'] == 'V3' and trap.get('type') == 'Inform':
435 module.fail_json(msg="SNMP trap version 'V3' does not support type 'Inform', only 'Trap' is supported")
436
437
438 def build_snmp_users(snmp_users):
439 """
440 Build SNMP users list for API body.
441
442 Args:
443 snmp_users: List of SNMP user dictionaries
444
445 Returns:
446 list: List of SNMP user dictionaries formatted for API
447 """
448 if not snmp_users:
449 return []
450
451 users = []
452 for user in snmp_users:
453 snmp_user = {
454 'Name': user['name'],
455 'SecurityLevel': user['security_level'],
456 'AuthType': 'SHA',
457 'AuthPassword': user['auth_password']
458 }
459
460 # Only add privacy type and password if security level is AuthPriv
461 if user.get('security_level') == 'AuthPriv':
462 snmp_user['PrivacyType'] = 'AES'
463 snmp_user['PrivacyPassword'] = user['privacy_password']
464
465 users.append(snmp_user)
466
467 return users
468
469
470 def build_snmp_traps(snmp_traps):
471 """
472 Build SNMP traps list for API body.
473
474 Args:
475 snmp_traps: List of SNMP trap dictionaries
476
477 Returns:
478 list: List of SNMP trap dictionaries formatted for API
479 """
480 if not snmp_traps:
481 return []
482
483 traps = []
484 for trap in snmp_traps:
485 snmp_trap = {
486 'Enabled': trap['enabled'],
487 'Version': trap['version'],
488 'Type': trap['type'],
489 'Destination': trap['destination'],
490 'Port': trap['port'],
491 }
492
493 if trap['version'] == 'V3':
494 snmp_trap['User'] = trap['user']
495 elif trap['version'] == 'V2':
496 snmp_trap['Community'] = trap['community']
497
498 traps.append(snmp_trap)
499
500 return traps
501
502
503 def build_api_body(intersight):
504 """
505 Build the API body for SNMP policy configuration.
506
507 Args:
508 intersight: IntersightModule instance
509
510 Returns:
511 None: Updates intersight.api_body directly
512 """
513 params = intersight.module.params
514 if params['state'] == 'present':
515 # Base API body
516 intersight.api_body = {
517 'Organization': {
518 'Name': params['organization'],
519 },
520 'Name': params['name'],
521 'Enabled': params['enabled']
522 }
523
524 # Only include additional parameters if SNMP is enabled
525 if params['enabled']:
526 # Add version-specific parameters
527 intersight.api_body['V2Enabled'] = params.get('v2c_enabled', True)
528 intersight.api_body['V3Enabled'] = params.get('v3_enabled', True)
529
530 # Add SNMP port
531 intersight.api_body['SnmpPort'] = params['snmp_port']
532
533 # Add system contact and location
534 intersight.api_body['SysContact'] = params['sys_contact']
535 intersight.api_body['SysLocation'] = params['sys_location']
536
537 # Add community access
538 intersight.api_body['CommunityAccess'] = params['community_access']
539
540 # Add SNMPv2c specific parameters
541 if params['v2c_enabled']:
542 if params.get('access_community_string'):
543 intersight.api_body['AccessCommunityString'] = params['access_community_string']
544 if params.get('trap_community'):
545 intersight.api_body['TrapCommunity'] = params['trap_community']
546
547 # Add SNMPv3 specific parameters
548 if params['v3_enabled']:
549 if params.get('engine_input_id'):
550 intersight.api_body['EngineId'] = params['engine_input_id']
551
552 # Add SNMP users
553 intersight.api_body['SnmpUsers'] = build_snmp_users(params.get('snmp_users'))
554
555 # Add SNMP traps
556 intersight.api_body['SnmpTraps'] = build_snmp_traps(params.get('snmp_traps'))
557
558 else:
559 # When SNMP is disabled, send empty arrays
560 intersight.api_body['SnmpUsers'] = []
561 intersight.api_body['SnmpTraps'] = []
562
563 # Add optional parameters
564 intersight.set_tags_and_description()
565
566
567 def main():
568 # Get the argument specification
569 argument_spec = get_argument_spec()
570
571 # Create the module
572 module = AnsibleModule(
573 argument_spec,
574 supports_check_mode=True,
575 )
576
577 # Validate SNMP configuration
578 validate_snmp_configuration(module)
579
580 # Initialize Intersight module
581 intersight = IntersightModule(module)
582 intersight.result['api_response'] = {}
583 intersight.result['trace_id'] = ''
584
585 # Build API body
586 build_api_body(intersight)
587
588 # Resource path used to configure policy
589 resource_path = '/snmp/Policies'
590
591 # Configure the policy
592 intersight.configure_policy_or_profile(resource_path=resource_path)
593
594 # Exit with results
595 module.exit_json(**intersight.result)
596
597
598 if __name__ == '__main__':
599 main()