Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2023-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 '''
7 na_ontap_ems_destination
8 '''
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = '''
14 module: na_ontap_ems_destination
15 short_description: NetApp ONTAP configuration for EMS event destination
16 extends_documentation_fragment:
17 - netapp.ontap.netapp.na_ontap_rest
18 version_added: 21.23.0
19 author: Bartosz Bielawski (@bielawb) <[email protected]>
20 description:
21 - Configure EMS destination.
22 options:
23 state:
24 description:
25 - Whether the destination should be present or not.
26 choices: ['present', 'absent']
27 type: str
28 default: present
29 name:
30 description:
31 - Name of the EMS destination.
32 required: true
33 type: str
34 type:
35 description:
36 - Type of the EMS destination.
37 choices: ['email', 'syslog', 'rest_api']
38 required: true
39 type: str
40 destination:
41 description:
42 - Destination - content depends on the type.
43 required: true
44 type: str
45 filters:
46 description:
47 - List of filters that destination is linked to.
48 required: true
49 type: list
50 elements: str
51 certificate:
52 description:
53 - Name of the certificate
54 required: false
55 type: str
56 version_added: 22.8.0
57 ca:
58 description:
59 - Name of the CA certificate
60 required: false
61 type: str
62 version_added: 22.8.0
63 syslog:
64 description:
65 - The parameter is specified when the EMS destination type is C(syslog).
66 required: false
67 version_added: 22.9.0
68 type: dict
69 suboptions:
70 transport:
71 choices: [udp_unencrypted, tcp_unencrypted, tcp_encrypted]
72 description:
73 - Syslog Transport Protocol.
74 type: str
75 default: 'udp_unencrypted'
76 timestamp_format_override:
77 choices: [no_override, rfc_3164, iso_8601_local_time, iso_8601_utc]
78 description:
79 - Syslog Timestamp Format Override.
80 type: str
81 default: 'no_override'
82 hostname_format_override:
83 choices: [no_override, fqdn, hostname_only]
84 description:
85 - Syslog Hostname Format Override.
86 type: str
87 default: 'no_override'
88 message_format:
89 choices: [legacy_netapp, rfc_5424]
90 description:
91 - Syslog Message Format.
92 type: str
93 default: 'legacy_netapp'
94 port:
95 description:
96 - Syslog Port.
97 type: int
98 default: 514
99 notes:
100 - Supports check_mode.
101 - This module only supports REST.
102 '''
103
104 EXAMPLES = """
105 - name: Configure REST EMS destination
106 netapp.ontap.na_ontap_ems_destination:
107 state: present
108 name: rest
109 type: rest_api
110 filters: ['important_events']
111 destination: http://my.rest.api/address
112 username: "{{ netapp_username }}"
113 password: "{{ netapp_password }}"
114 hostname: "{{ netapp_hostname }}"
115
116 - name: Configure REST EMS destination with a certificate
117 netapp.ontap.na_ontap_ems_destination:
118 state: present
119 name: rest
120 type: rest_api
121 filters: ['important_events']
122 destination: http://my.rest.api/address
123 certificate: my_cert
124 ca: my_cert_ca
125 username: "{{ netapp_username }}"
126 password: "{{ netapp_password }}"
127 hostname: "{{ netapp_hostname }}"
128
129 - name: Configure REST EMS destination with type syslog
130 netapp.ontap.na_ontap_ems_destination:
131 state: present
132 name: syslog_destination
133 type: syslog
134 filters: ['important_events']
135 destination: http://my.rest.api/address
136 certificate: my_cert
137 ca: my_cert_ca
138 syslog:
139 transport: udp_unencrypted
140 port: 514
141 message_format: legacy_netapp
142 hostname_format_override: no_override
143 timestamp_format_override: no_override
144 username: "{{ netapp_username }}"
145 password: "{{ netapp_password }}"
146 hostname: "{{ netapp_hostname }}"
147
148 - name: Remove email EMS destination
149 netapp.ontap.na_ontap_ems_destination:
150 state: absent
151 name: email_destination
152 type: email
153 filters: ['important_events']
154 destination: [email protected]
155 username: "{{ netapp_username }}"
156 password: "{{ netapp_password }}"
157 hostname: "{{ netapp_hostname }}"
158 """
159
160 RETURN = """
161
162 """
163 from ansible.module_utils.basic import AnsibleModule
164 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
165 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
166 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
167
168
169 class NetAppOntapEmsDestination:
170 """Create/Modify/Remove EMS destination"""
171 def __init__(self):
172 self.argument_spec = netapp_utils.na_ontap_rest_only_spec()
173 self.argument_spec.update(dict(
174 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
175 name=dict(required=True, type='str'),
176 type=dict(required=True, type='str', choices=['email', 'syslog', 'rest_api']),
177 syslog=dict(required=False, type='dict',
178 options=dict(
179 transport=dict(required=False, type='str', choices=['udp_unencrypted', 'tcp_unencrypted', 'tcp_encrypted'],
180 default='udp_unencrypted'),
181 port=dict(required=False, type='int', default=514),
182 message_format=dict(required=False, type='str', choices=['legacy_netapp', 'rfc_5424'], default='legacy_netapp'),
183 timestamp_format_override=dict(required=False, type='str',
184 choices=['no_override', 'rfc_3164', 'iso_8601_local_time', 'iso_8601_utc'], default='no_override'),
185 hostname_format_override=dict(required=False, type='str', choices=['no_override', 'fqdn', 'hostname_only'], default='no_override')
186 )),
187 destination=dict(required=True, type='str'),
188 filters=dict(required=True, type='list', elements='str'),
189 certificate=dict(required=False, type='str'),
190 ca=dict(required=False, type='str'),
191 ))
192 self.module = AnsibleModule(
193 argument_spec=self.argument_spec,
194 required_together=[('certificate', 'ca')],
195 supports_check_mode=True
196 )
197 self.na_helper = NetAppModule()
198 self.parameters = self.na_helper.set_parameters(self.module.params)
199 self.rest_api = netapp_utils.OntapRestAPI(self.module)
200 partially_supported_rest_properties = [['certificate', (9, 11, 1)], ['syslog', (9, 12, 1)]]
201 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, partially_supported_rest_properties=partially_supported_rest_properties)
202
203 if not self.use_rest:
204 self.module.fail_json(msg='na_ontap_ems_destination is only supported with REST API')
205
206 def fail_on_error(self, error, action):
207 if error is None:
208 return
209 self.module.fail_json(msg="Error %s: %s" % (action, error))
210
211 def generate_filters_list(self, filters):
212 return [{'name': filter} for filter in filters]
213
214 def get_ems_destination(self, name):
215 api = 'support/ems/destinations'
216 query = {'name': name,
217 'fields': 'type,'
218 'destination,'
219 'filters.name,'
220 'certificate.ca,'}
221 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 11, 1):
222 query['fields'] += 'certificate.name,'
223 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 12, 1):
224 syslog_option_9_12 = ('syslog.transport,'
225 'syslog.port,'
226 'syslog.format.message,'
227 'syslog.format.timestamp_override,'
228 'syslog.format.hostname_override,')
229 query['fields'] += syslog_option_9_12
230 record, error = rest_generic.get_one_record(self.rest_api, api, query)
231 self.fail_on_error(error, 'fetching EMS destination for %s' % name)
232 if record:
233 current = {
234 'name': self.na_helper.safe_get(record, ['name']),
235 'type': self.na_helper.safe_get(record, ['type']),
236 'destination': self.na_helper.safe_get(record, ['destination']),
237 'filters': None,
238 'certificate': self.na_helper.safe_get(record, ['certificate', 'name']),
239 'ca': self.na_helper.safe_get(record, ['certificate', 'ca']),
240 }
241 if record.get('syslog') is not None:
242 current['syslog'] = {
243 'port': self.na_helper.safe_get(record, ['syslog', 'port']),
244 'transport': self.na_helper.safe_get(record, ['syslog', 'transport']),
245 'timestamp_format_override': self.na_helper.safe_get(record, ['syslog', 'format', 'timestamp_override']),
246 'hostname_format_override': self.na_helper.safe_get(record, ['syslog', 'format', 'hostname_override']),
247 'message_format': self.na_helper.safe_get(record, ['syslog', 'format', 'message']),
248 }
249 # 9.9.0 and earlier versions returns rest-api, convert it to rest_api.
250 if current['type'] and '-' in current['type']:
251 current['type'] = current['type'].replace('-', '_')
252 if self.na_helper.safe_get(record, ['filters']):
253 current['filters'] = [filter['name'] for filter in record['filters']]
254 return current
255 return None
256
257 def get_certificate_serial(self, cert_name):
258 """Retrieve the serial of a certificate"""
259 api = 'security/certificates'
260 query = {
261 'scope': "cluster",
262 'type': "client",
263 'name': cert_name
264 }
265 fields = 'serial_number'
266 record, error = rest_generic.get_one_record(self.rest_api, api, query, fields)
267 if error:
268 self.module.fail_json(msg='Error retrieving certificates: %s' % error)
269
270 if not record:
271 self.module.fail_json(msg='Error certificate not found: %s.'
272 % (self.parameters['certificate']))
273 return record['serial_number']
274
275 def create_ems_destination(self):
276 api = 'support/ems/destinations'
277 name = self.parameters['name']
278 body = {
279 'name': name,
280 'type': self.parameters['type'],
281 'destination': self.parameters['destination'],
282 'filters': self.generate_filters_list(self.parameters['filters'])
283 }
284
285 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 11, 1):
286 if self.parameters.get('certificate') and self.parameters.get('ca') is not None:
287 body['certificate'] = {
288 'serial_number': self.get_certificate_serial(self.parameters['certificate']),
289 'ca': self.parameters['ca'],
290 }
291 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 12, 1):
292 if self.parameters.get('syslog') is not None:
293 body['syslog'] = {}
294 for key, option in [
295 ('syslog.port', 'port'),
296 ('syslog.transport', 'transport'),
297 ('syslog.format.message', 'message_format'),
298 ('syslog.format.timestamp_override', 'timestamp_format_override'),
299 ('syslog.format.hostname_override', 'hostname_format_override')
300 ]:
301 if self.parameters['syslog'].get(option) is not None:
302 body[key] = self.parameters['syslog'][option]
303 dummy, error = rest_generic.post_async(self.rest_api, api, body)
304 self.fail_on_error(error, 'creating EMS destinations for %s' % name)
305
306 def delete_ems_destination(self, name):
307 api = 'support/ems/destinations'
308 dummy, error = rest_generic.delete_async(self.rest_api, api, name)
309 self.fail_on_error(error, 'deleting EMS destination for %s' % name)
310
311 def modify_ems_destination(self, name, modify):
312 if 'type' in modify:
313 # changing type is not supported
314 self.delete_ems_destination(name)
315 self.create_ems_destination()
316 else:
317 body = {}
318 if any(item in modify for item in ['certificate', 'ca']):
319 body['certificate'] = {}
320 for option in modify:
321 if option == 'filters':
322 body[option] = self.generate_filters_list(modify[option])
323 elif option == 'certificate':
324 body[option]['serial_number'] = self.get_certificate_serial(modify[option])
325 elif option == 'ca':
326 body['certificate']['ca'] = modify[option]
327 elif option == 'syslog':
328 for key, option in [
329 ('syslog.port', 'port'),
330 ('syslog.transport', 'transport'),
331 ('syslog.format.message', 'message_format'),
332 ('syslog.format.timestamp_override', 'timestamp_format_override'),
333 ('syslog.format.hostname_override', 'hostname_format_override')
334 ]:
335 if option in modify['syslog']:
336 body[key] = modify['syslog'][option]
337 else:
338 body[option] = modify[option]
339 if body:
340 api = 'support/ems/destinations'
341 dummy, error = rest_generic.patch_async(self.rest_api, api, name, body)
342 self.fail_on_error(error, 'modifying EMS destination for %s' % name)
343
344 def apply(self):
345 name = self.parameters['name']
346 modify = None
347 current = self.get_ems_destination(name)
348 cd_action = self.na_helper.get_cd_action(current, self.parameters)
349 if cd_action is None and self.parameters['state'] == 'present':
350 modify = self.na_helper.get_modified_attributes(current, self.parameters)
351
352 saved_modify = str(modify)
353 if self.na_helper.changed and not self.module.check_mode:
354 if modify:
355 self.modify_ems_destination(name, modify)
356 elif cd_action == 'create':
357 self.create_ems_destination()
358 else:
359 self.delete_ems_destination(name)
360 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, saved_modify)
361 self.module.exit_json(**result)
362
363
364 def main():
365 obj = NetAppOntapEmsDestination()
366 obj.apply()
367
368
369 if __name__ == '__main__':
370 main()