Debian Codegraph @

ansible_collections/netapp/storagegrid/plugins/modules/na_sg_grid_alert_receiver.py

raw
1 #!/usr/bin/python
2
3 # (c) 2025, NetApp Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """NetApp StorageGRID - Manage Alert Receiver"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 ANSIBLE_METADATA = {
14 "metadata_version": "1.0",
15 "status": ["preview"],
16 "supported_by": "community",
17 }
18
19
20 DOCUMENTATION = """
21 module: na_sg_grid_alert_receiver
22 short_description: NetApp StorageGRID manage alert receiver.
23 extends_documentation_fragment:
24 - netapp.storagegrid.netapp.sg
25 version_added: '21.15.0'
26 author: NetApp Ansible Team (@vinaykus) <[email protected]>
27 description:
28 - Create, update, or delete alert receivers on NetApp StorageGRID.
29 options:
30 state:
31 description:
32 - Whether the alert receiver should be present or absent.
33 choices: ['present', 'absent']
34 default: 'present'
35 type: str
36 type:
37 description:
38 - The type of notification receiver.
39 required: true
40 choices: ['email']
41 type: str
42 enable:
43 description:
44 - Whether alert notifications are sent to this receiver.
45 type: bool
46 default: true
47 smtp_host:
48 description:
49 - The IP address or hostname of the SMTP server.
50 type: str
51 smtp_port:
52 description:
53 - The port to use to communicate with the SMTP server.
54 type: int
55 username:
56 description:
57 - Use C(smtp_username) instead.
58 - This parameter has been deprecated.
59 type: str
60 password:
61 description:
62 - Use C(smtp_password) instead.
63 - This parameter has been deprecated.
64 type: str
65 smtp_username:
66 description:
67 - Username for the SMTP server.
68 type: str
69 version_added: 21.16.0
70 smtp_password:
71 description:
72 - Password for the SMTP server.
73 type: str
74 version_added: 21.16.0
75 from_email:
76 description:
77 - Sender email address.
78 type: str
79 to_emails:
80 description:
81 - List of recipient email addresses.
82 type: list
83 elements: str
84 minimum_severity:
85 description:
86 - Minimum severity level for triggering an alert.
87 choices: ['minor', 'major', 'critical']
88 type: str
89 ca_cert:
90 description:
91 - CA certificate used to verify the identity of the SMTP server.
92 type: str
93 client_cert:
94 description:
95 - Client certificate for the SMTP server.
96 type: str
97 client_key:
98 description:
99 - The PEM-encoded private key for the client certificate.
100 type: str
101 """
102
103 EXAMPLES = """
104 - name: Create alert receiver
105 netapp.storagegrid.na_sg_grid_alert_receiver:
106 api_url: "https://<storagegrid-endpoint-url>"
107 auth_token: "storagegrid-auth-token"
108 validate_certs: false
109 state: present
110 type: email
111 enable: true
112 smtp_host: "smtp.example.com"
113 smtp_port: 25
114 smtp_username: "smtp-user"
115 smtp_password: "smtp-password"
116 from_email: "[email protected]"
117 to_emails:
118 - "[email protected]"
119 minimum_severity: "minor"
120 ca_cert: "-----BEGIN CERTIFICATE-----*******-----END CERTIFICATE-----"
121 client_cert: "-----BEGIN CERTIFICATE-----*******-----END CERTIFICATE-----"
122 client_key: "-----BEGIN PRIVATE KEY-----*******-----END PRIVATE KEY-----"
123
124 - name: Delete alert receiver
125 netapp.storagegrid.na_sg_alert_receiver:
126 api_url: "https://<storagegrid-endpoint-url>"
127 auth_token: "storagegrid-auth-token"
128 validate_certs: false
129 state: present
130 type: email
131 """
132
133 RETURN = """
134 resp:
135 description: Returns the response from the StorageGRID API for alert receiver.
136 returned: success
137 type: dict
138 sample: {
139 "type": "email",
140 "enable": true,
141 "smtpHost": "smtp.example.com",
142 "smtpPort": 25,
143 "username": "smtp-user",
144 "password": "smtp-password",
145 "fromEmail": "[email protected]",
146 "toEmails": [
147 "[email protected]"
148 ],
149 "minimumSeverity": "minor",
150 "caCert": "-----BEGIN CERTIFICATE-----*******-----END CERTIFICATE-----",
151 "clientCert": "-----BEGIN CERTIFICATE-----*******-----END CERTIFICATE-----",
152 "clientKey": "-----BEGIN PRIVATE KEY-----*******-----END PRIVATE KEY-----",
153 }
154 """
155
156 import ansible_collections.netapp.storagegrid.plugins.module_utils.netapp as netapp_utils
157 from ansible.module_utils.basic import AnsibleModule
158 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp_module import NetAppModule
159 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp import SGRestAPI
160
161
162 class SgAlertReceiver:
163 """
164 Create, modify and delete Alert receiver for StorageGRID
165 """
166
167 def __init__(self):
168 """
169 Parse arguments, setup state variables,
170 check parameters and ensure request module is installed
171 """
172 self.argument_spec = netapp_utils.na_storagegrid_host_argument_spec()
173 self.argument_spec.update(
174 dict(
175 state=dict(type="str", choices=["present", "absent"], default="present"),
176 type=dict(required=True, type="str", choices=["email"]),
177 enable=dict(required=False, type="bool", default=True),
178 smtp_host=dict(required=False, type="str"),
179 smtp_port=dict(required=False, type="int"),
180 username=dict(required=False, type="str"),
181 password=dict(required=False, type="str", no_log=True),
182 smtp_username=dict(required=False, type="str"),
183 smtp_password=dict(required=False, type="str", no_log=True),
184 from_email=dict(required=False, type="str"),
185 to_emails=dict(required=False, type="list", elements="str"),
186 minimum_severity=dict(required=False, type="str", choices=["minor", "major", "critical"]),
187 ca_cert=dict(required=False, type="str"),
188 client_cert=dict(required=False, type="str"),
189 client_key=dict(required=False, type="str", no_log=True),
190 )
191 )
192 self.module = AnsibleModule(
193 argument_spec=self.argument_spec,
194 required_if=[("state", "present", ["type", "smtp_host", "smtp_port", "from_email", "to_emails", "minimum_severity"])],
195 supports_check_mode=True
196 )
197 self.na_helper = NetAppModule()
198
199 # set up state variables
200 self.parameters = self.na_helper.set_parameters(self.module.params)
201 # Calling generic SG rest_api class
202 self.rest_api = SGRestAPI(self.module)
203 # Get API version
204 self.rest_api.get_sg_product_version()
205 self.api_version = self.rest_api.get_api_version()
206
207 # Checking for the parameters passed and create new parameters list
208 self.data = {}
209 self.data["type"] = self.parameters["type"]
210
211 if self.parameters.get("smtp_host"):
212 self.data["smtpHost"] = self.parameters["smtp_host"]
213 if self.parameters.get("smtp_port"):
214 self.data["smtpPort"] = self.parameters["smtp_port"]
215 if self.parameters.get("from_email"):
216 self.data["fromEmail"] = self.parameters["from_email"]
217 if self.parameters.get("to_emails"):
218 self.data["toEmails"] = self.parameters["to_emails"]
219 if self.parameters.get("minimum_severity"):
220 self.data["minimumSeverity"] = self.parameters["minimum_severity"]
221 if self.parameters.get("enable") is not None:
222 self.data["enable"] = self.parameters["enable"]
223 if self.parameters.get("username"):
224 self.data["username"] = self.parameters["username"]
225 if self.parameters.get("password"):
226 self.data["password"] = self.parameters["password"]
227 if self.parameters.get("smtp_username"):
228 self.data["username"] = self.parameters["smtp_username"]
229 if self.parameters.get("smtp_password"):
230 self.data["password"] = self.parameters["smtp_password"]
231 if self.parameters.get("ca_cert"):
232 self.data["caCert"] = self.parameters.get("ca_cert")
233 if self.parameters.get("client_cert"):
234 self.data["clientCert"] = self.parameters.get("client_cert")
235 if self.parameters.get("client_key"):
236 self.data["clientKey"] = self.parameters.get("client_key")
237
238 def get_alert_receiver(self):
239 ''' Get alert receiver '''
240 api = "api/%s/grid/alert-receivers" % self.api_version
241 response, error = self.rest_api.get(api)
242 if error:
243 self.module.fail_json(msg=error)
244 # if alert 'type' exists, return it, else none
245 for alert in response["data"]:
246 if alert["type"] == self.parameters["type"]:
247 self.id = alert["id"]
248 return alert
249 return None
250
251 def create_alert_receiver(self):
252 ''' Create alert receiver '''
253 api = "api/%s/grid/alert-receivers" % self.api_version
254 response, error = self.rest_api.post(api, self.data)
255 if error:
256 self.module.fail_json(msg=error)
257 else:
258 return response["data"]
259
260 def delete_alert_receiver(self, alert_receiver_id):
261 ''' Delete alert receiver '''
262 api = "api/%s/grid/alert-receivers/%s" % (self.api_version, alert_receiver_id)
263 response, error = self.rest_api.delete(api, self.data)
264 if error:
265 self.module.fail_json(msg=error)
266
267 def update_alert_receiver(self, alert_receiver_id):
268 ''' Update alert receiver '''
269 api = "api/%s/grid/alert-receivers/%s" % (self.api_version, alert_receiver_id)
270 response, error = self.rest_api.put(api, self.data)
271 if error:
272 self.module.fail_json(msg=error)
273 else:
274 return response["data"]
275
276 def apply(self):
277 ''' Apply alert receiver '''
278
279 current_receiver = self.get_alert_receiver()
280
281 cd_action = self.na_helper.get_cd_action(current_receiver, self.parameters)
282 modify = None
283
284 if cd_action is None and self.parameters["state"] == "present":
285 # let's see if we need to update parameters
286 if not current_receiver["enable"] and not self.parameters["enable"]:
287 self.module.exit_json(changed=False, msg="Alert receiver is disabled.")
288 else:
289 modify = self.na_helper.get_modified_attributes(current_receiver, self.data)
290
291 result_message = ""
292 resp_data = current_receiver
293 if self.na_helper.changed:
294 if self.module.check_mode:
295 pass
296 else:
297 if cd_action == "create":
298 resp_data = self.create_alert_receiver()
299 result_message = "Alert receiver created successfully."
300 elif cd_action == "delete":
301 self.delete_alert_receiver(current_receiver["id"])
302 result_message = "Alert receiver deleted successfully."
303 elif modify:
304 resp_data = self.update_alert_receiver(current_receiver["id"])
305 result_message = "Alert receiver updated successfully."
306
307 self.module.exit_json(changed=self.na_helper.changed, msg=result_message, resp=resp_data)
308
309
310 def main():
311 """
312 Main function
313 """
314 na_sg_grid_alert_receiver = SgAlertReceiver()
315 na_sg_grid_alert_receiver.apply()
316
317
318 if __name__ == "__main__":
319 main()