Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_snmp.py

raw
1 #!/usr/bin/python
2 """
3 create SNMP module to add/delete/modify SNMP user
4 """
5
6 # (c) 2018-2025, NetApp, Inc
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 author: NetApp Ansible Team (@carchi8py) <[email protected]>
14 description:
15 - Create/Delete SNMP user.
16 extends_documentation_fragment:
17 - netapp.ontap.netapp.na_ontap
18 module: na_ontap_snmp
19 options:
20 access_control:
21 choices: ['ro']
22 description:
23 - Access control for the community. The only supported value is 'ro' (read-only).
24 - Ignored with REST.
25 default: 'ro'
26 type: str
27 snmp_username:
28 description:
29 - The name of the SNMP user to manage.
30 required: true
31 type: str
32 version_added: 22.8.0
33 state:
34 choices: ['present', 'absent']
35 description:
36 - Whether the specified SNMP user should exist or not.
37 default: 'present'
38 type: str
39 authentication_method:
40 choices: ['community', 'usm', 'both']
41 description:
42 - Authentication method for SNMP user.
43 - Only supported with REST. The default value is community.
44 type: str
45 version_added: 22.8.0
46 snmpv3:
47 description:
48 - Specify only when C(authentication_method) is either C(usm) or C(both).
49 - This option defines the SNMPv3 credentials for an SNMPv3 user or also called usm user.
50 - Only supported with REST.
51 type: dict
52 version_added: 22.8.0
53 suboptions:
54 authentication_password:
55 description:
56 - Authentication protocol password.
57 type: str
58 required: true
59 authentication_protocol:
60 choices: ['none', 'md5', 'sha', 'sha2_256']
61 description:
62 - Authentication protocol for SNMPv3.
63 default: 'none'
64 type: str
65 privacy_password:
66 description:
67 - Privacy protocol password.
68 type: str
69 required: true
70 privacy_protocol:
71 choices: ['none', 'des', 'aes128']
72 description:
73 - Privacy protocol for SNMPv3.
74 default: 'none'
75 type: str
76 short_description: NetApp ONTAP SNMP user
77 version_added: 2.6.0
78 '''
79
80 EXAMPLES = """
81 - name: Create SNMP community (ZAPI only)
82 netapp.ontap.na_ontap_snmp:
83 state: present
84 snmp_username: communityName
85 access_control: 'ro'
86 use_rest: never
87 hostname: "{{ netapp_hostname }}"
88 username: "{{ netapp_username }}"
89 password: "{{ netapp_password }}"
90
91 - name: Create SNMP community (snmpv1 or snmpv2) (REST only)
92 netapp.ontap.na_ontap_snmp:
93 state: present
94 snmp_username: communityName
95 use_rest: always
96 hostname: "{{ netapp_hostname }}"
97 username: "{{ netapp_username }}"
98 password: "{{ netapp_password }}"
99
100 - name: Create SNMP user (snmpv3) (REST only)
101 netapp.ontap.na_ontap_snmp:
102 state: present
103 snmp_username: username
104 use_rest: always
105 authentication_method: usm
106 snmpv3:
107 authentication_protocol: sha
108 authentication_password: humTdumt*@t0nAwa21
109 privacy_protocol: aes128
110 privacy_password: p@**GOandCLCt*300
111 hostname: "{{ netapp_hostname }}"
112 username: "{{ netapp_username }}"
113 password: "{{ netapp_password }}"
114
115 - name: Delete SNMP community (ZAPI only)
116 netapp.ontap.na_ontap_snmp:
117 state: absent
118 snmp_username: communityName
119 access_control: 'ro'
120 use_rest: never
121 hostname: "{{ netapp_hostname }}"
122 username: "{{ netapp_username }}"
123 password: "{{ netapp_password }}"
124
125 - name: Delete SNMP community (snmpv1 or snmpv2) (REST only)
126 netapp.ontap.na_ontap_snmp:
127 state: absent
128 snmp_username: communityName
129 use_rest: always
130 hostname: "{{ netapp_hostname }}"
131 username: "{{ netapp_username }}"
132 password: "{{ netapp_password }}"
133
134 - name: Delete SNMP user (snmpv3) (REST only)
135 netapp.ontap.na_ontap_snmp:
136 state: absent
137 snmp_username: username
138 use_rest: always
139 hostname: "{{ netapp_hostname }}"
140 username: "{{ netapp_username }}"
141 password: "{{ netapp_password }}"
142 """
143
144 RETURN = """
145 """
146 import traceback
147 from ansible.module_utils.basic import AnsibleModule
148 from ansible.module_utils._text import to_native
149 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
150 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
151 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
152 import ansible_collections.netapp.ontap.plugins.module_utils.rest_response_helpers as rrh
153
154 HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
155
156
157 class NetAppONTAPSnmp(object):
158 '''Class with SNMP methods, doesn't support check mode'''
159
160 def __init__(self):
161 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
162 self.argument_spec.update(dict(
163 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
164 snmp_username=dict(required=True, type='str'),
165 access_control=dict(required=False, type='str', choices=['ro'], default='ro'),
166 authentication_method=dict(required=False, type='str', choices=['community', 'usm', 'both']),
167 snmpv3=dict(required=False, type='dict',
168 options=dict(
169 authentication_password=dict(required=True, type='str', no_log=True),
170 privacy_protocol=dict(required=False, type='str', choices=['none', 'des', 'aes128'], default='none'),
171 authentication_protocol=dict(required=False, type='str', choices=['none', 'md5', 'sha', 'sha2_256'], default='none'),
172 privacy_password=dict(required=True, type='str', no_log=True),
173 )
174 )
175 ))
176
177 self.module = AnsibleModule(
178 argument_spec=self.argument_spec,
179 supports_check_mode=True
180 )
181
182 self.na_helper = NetAppModule()
183 # set up state variables
184 self.parameters = self.na_helper.set_parameters(self.module.params)
185
186 # Set up Rest API
187 self.rest_api = OntapRestAPI(self.module)
188 self.use_rest = self.rest_api.is_rest()
189
190 self.unsupported_zapi_properties = ['authentication_method', 'snmpv3', 'authentication_protocol', 'authentication_password', 'privacy_protocol',
191 'privacy_password']
192
193 if self.use_rest:
194 if self.parameters.get('authentication_method') == 'community' and 'snmpv3' in self.parameters:
195 self.module.fail_json("SNMPv3 user can be created when 'authentication_method' is either 'usm' or 'both'")
196
197 if not self.use_rest:
198 if HAS_NETAPP_LIB is False:
199 self.module.fail_json(msg="the python NetApp-Lib module is required")
200
201 for unsupported_zapi_property in self.unsupported_zapi_properties:
202 if self.parameters.get(unsupported_zapi_property) is not None:
203 msg = "Error: %s option is not supported with ZAPI. It can only be used with REST." % unsupported_zapi_property
204 self.module.fail_json(msg=msg)
205 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
206
207 def invoke_snmp_community(self, zapi):
208 """
209 Invoke zapi - add/delete take the same NaElement structure
210 """
211 snmp_community = netapp_utils.zapi.NaElement.create_node_with_children(
212 zapi, **{'community': self.parameters['snmp_username'],
213 'access-control': self.parameters['access_control']})
214 try:
215 self.server.invoke_successfully(snmp_community, enable_tunneling=True)
216 except netapp_utils.zapi.NaApiError as error:
217 if zapi == 'snmp-community-add':
218 action = 'adding'
219 elif zapi == 'snmp-community-delete':
220 action = 'deleting'
221 else:
222 action = 'unexpected'
223 self.module.fail_json(msg='Error %s community %s: %s' % (action, self.parameters['snmp_username'], to_native(error)),
224 exception=traceback.format_exc())
225
226 def get_snmp(self):
227 """
228 Check if SNMP community exists
229 """
230 if self.use_rest:
231 return self.get_snmp_rest()
232 snmp_obj = netapp_utils.zapi.NaElement('snmp-status')
233 try:
234 result = self.server.invoke_successfully(snmp_obj, True)
235 except netapp_utils.zapi.NaApiError as error:
236 self.module.fail_json(msg=to_native(error), exception=traceback.format_exc())
237 if result.get_child_by_name('communities') is not None:
238 for snmp_entry in result.get_child_by_name('communities').get_children():
239 snmp_username = snmp_entry.get_child_content('community')
240 if snmp_username == self.parameters['snmp_username']:
241 return {
242 'snmp_username': snmp_entry.get_child_content('community'),
243 'access_control': snmp_entry.get_child_content('access-control'),
244 }
245 return None
246
247 def get_snmp_rest(self):
248 # There can be SNMPv1, SNMPv2 (called community) or
249 # SNMPv3 (called usm users)
250 api = 'support/snmp/users'
251 params = {'name': self.parameters['snmp_username'],
252 'fields': 'name,engine_id'}
253 message, error = self.rest_api.get(api, params)
254 record, error = rrh.check_for_0_or_1_records(api, message, error)
255 if error:
256 self.module.fail_json(msg=error)
257 if record:
258 # access control does not exist in rest
259 return dict(snmp_username=record['name'], engine_id=record['engine_id'], access_control='ro')
260 return None
261
262 def add_snmp_user(self):
263 """
264 Add a SNMP user
265 """
266 if self.use_rest:
267 self.add_snmp_rest()
268 else:
269 self.invoke_snmp_community('snmp-community-add')
270
271 def add_snmp_rest(self):
272 api = 'support/snmp/users'
273 self.parameters['authentication_method'] = self.parameters.get('authentication_method', 'community')
274 body = {
275 'name': self.parameters['snmp_username'],
276 'authentication_method': self.parameters['authentication_method']
277 }
278 if self.parameters.get('authentication_method') == 'usm' or self.parameters.get('authentication_method') == 'both':
279 if self.parameters.get('snmpv3'):
280 body['snmpv3'] = self.parameters['snmpv3']
281 message, error = self.rest_api.post(api, body)
282 if error:
283 self.module.fail_json(msg=error)
284
285 def delete_snmp_user(self, current=None):
286 """
287 Delete a SNMP user
288 """
289 if self.use_rest:
290 self.delete_snmp_rest(current)
291 else:
292 self.invoke_snmp_community('snmp-community-delete')
293
294 def delete_snmp_rest(self, current):
295 api = 'support/snmp/users/' + current['engine_id'] + '/' + self.parameters["snmp_username"]
296 dummy, error = self.rest_api.delete(api)
297 if error:
298 self.module.fail_json(msg=error)
299
300 def apply(self):
301 # TODO: This module should have been called snmp_community as it only deals with community and not snmp
302 current = self.get_snmp()
303 cd_action = self.na_helper.get_cd_action(current, self.parameters)
304 if self.na_helper.changed and not self.module.check_mode:
305 if cd_action == 'create':
306 self.add_snmp_user()
307 elif cd_action == 'delete':
308 self.delete_snmp_user(current)
309 result = netapp_utils.generate_result(self.na_helper.changed, cd_action)
310 self.module.exit_json(**result)
311
312
313 def main():
314 '''Execute action'''
315 community_obj = NetAppONTAPSnmp()
316 community_obj.apply()
317
318
319 if __name__ == '__main__':
320 main()