Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_application_alerts_smtp.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Dell OpenManage Ansible Modules
4 # Version 9.12.4
5 # Copyright (C) 2021-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
6 # GNU General Public License v3.0+
7 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9
10 from __future__ import (absolute_import, division, print_function)
11
12 __metaclass__ = type
13
14 DOCUMENTATION = r'''
15 ---
16 module: ome_application_alerts_smtp
17 short_description: This module allows to configure SMTP or email configurations
18 version_added: "4.3.0"
19 description:
20 - This module allows to configure SMTP or email configurations on OpenManage Enterprise
21 and OpenManage Enterprise Modular.
22 extends_documentation_fragment:
23 - dellemc.openmanage.ome_auth_options
24 options:
25 destination_address:
26 description: The IP address or FQDN of the SMTP destination server.
27 type: str
28 required: true
29 port_number:
30 description: The port number of the SMTP destination server.
31 type: int
32 use_ssl:
33 description: Use SSL to connect with the SMTP server.
34 type: bool
35 enable_authentication:
36 description:
37 - Enable or disable authentication to access the SMTP server.
38 - The I(credentials) are mandatory if I(enable_authentication) is C(true).
39 - The module will always report change when this is C(true).
40 type: bool
41 required: true
42 credentials:
43 description: The credentials for the SMTP server
44 type: dict
45 suboptions:
46 username:
47 description:
48 - The username to access the SMTP server.
49 type: str
50 required: true
51 password:
52 description:
53 - The password to access the SMTP server.
54 type: str
55 required: true
56 requirements:
57 - "python >= 3.9.6"
58 notes:
59 - The module will always report change when I(enable_authentication) is C(true).
60 - Run this module from a system that has direct access to Dell OpenManage Enterprise
61 or OpenManage Enterprise Modular.
62 - This module support C(check_mode).
63 author:
64 - Sachin Apagundi(@sachin-apa)
65 - Bhavneet Sharma (@Bhavneet-Sharma)
66 '''
67
68 EXAMPLES = """
69 ---
70 - name: Update SMTP destination server configuration with authentication
71 dellemc.openmanage.ome_application_alerts_smtp:
72 hostname: "192.168.0.1"
73 username: "user_name"
74 password: "user_password"
75 ca_path: "/path/to/ca_cert.pem"
76 destination_address: "localhost"
77 port_number: 25
78 use_ssl: true
79 enable_authentication: true
80 credentials:
81 username: "username"
82 password: "password"
83 - name: Update SMTP destination server configuration without authentication
84 dellemc.openmanage.ome_application_alerts_smtp:
85 hostname: "192.168.0.1"
86 username: "user_name"
87 password: "user_password"
88 ca_path: "/path/to/ca_cert.pem"
89 destination_address: "localhost"
90 port_number: 25
91 use_ssl: false
92 enable_authentication: false
93 """
94
95 RETURN = """
96 ---
97 msg:
98 type: str
99 description: Overall status of the SMTP settings update.
100 returned: always
101 sample: "Successfully updated the SMTP settings."
102 smtp_details:
103 type: dict
104 description: returned when SMTP settings are updated successfully.
105 returned: success
106 sample: {
107 "DestinationAddress": "localhost",
108 "PortNumber": 25,
109 "UseCredentials": true,
110 "UseSSL": false,
111 "Credential": {
112 "User": "admin",
113 "Password": null
114 }
115 }
116
117 error_info:
118 description: Details of the HTTP Error.
119 returned: on HTTP error
120 type: dict
121 sample: {
122 "error": {
123 "code": "Base.1.0.GeneralError",
124 "message": "A general error has occurred. See ExtendedInfo for more information.",
125 "@Message.ExtendedInfo": [{
126 "MessageId": "CAPP1106",
127 "RelatedProperties": [],
128 "Message": "Unable to update the SMTP settings because the entered credential is invalid or empty.",
129 "MessageArgs": [],
130 "Severity": "Critical",
131 "Resolution": "Either enter valid credentials or disable the Use Credentials option and retry the operation."
132 }
133 ]
134 }
135 }
136 """
137
138 import json
139 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
140 from ansible.module_utils.urls import ConnectionError
141 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
142 from ansible.module_utils.common.dict_transformations import recursive_diff
143
144 SUCCESS_MSG = "Successfully updated the SMTP settings."
145 SMTP_URL = "AlertService/AlertDestinations/SMTPConfiguration"
146 NO_CHANGES = "No changes found to be applied."
147 CHANGES_FOUND = "Changes found to be applied."
148
149
150 def fetch_smtp_settings(rest_obj):
151 final_resp = rest_obj.invoke_request("GET", SMTP_URL)
152 ret_data = final_resp.json_data.get('value')[0]
153 ret_data.pop("@odata.type")
154 return ret_data
155
156
157 def update_smtp_settings(rest_obj, payload):
158 final_resp = rest_obj.invoke_request("POST", SMTP_URL, data=payload)
159 return final_resp
160
161
162 def update_payload(module, curr_payload):
163 smtp_data_payload = {
164 "DestinationAddress": get_value(module, curr_payload, "destination_address", "DestinationAddress"),
165 "UseCredentials": get_value(module, curr_payload, "enable_authentication", "UseCredentials"),
166 "PortNumber": get_value(module, curr_payload, "port_number", "PortNumber"),
167 "UseSSL": get_value(module, curr_payload, "use_ssl", "UseSSL")
168 }
169 if module.params.get("credentials") and smtp_data_payload.get("UseCredentials"):
170 cred_payload = {
171 "Credential": {
172 "User": module.params.get("credentials").get("username"),
173 "Password": module.params.get("credentials").get("password")
174 }
175 }
176 smtp_data_payload.update(cred_payload)
177 return smtp_data_payload
178
179
180 def get_value(module, resp, mod_key, attr_key):
181 ret_value = module.params.get(mod_key)
182 if module.params.get(mod_key) is None:
183 ret_value = resp.get(attr_key)
184 return ret_value
185
186
187 def _diff_payload(curr_resp, update_resp):
188 is_change = False
189 if update_resp:
190 diff = recursive_diff(update_resp, curr_resp)
191 if diff and diff[0]:
192 is_change = True
193 return is_change
194
195
196 def password_no_log(attributes):
197 if isinstance(attributes, dict) and 'password' in attributes:
198 attributes['password'] = "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
199
200
201 def exit_module(module, **existmsg):
202 password_no_log(module.params.get("credentials"))
203 module.exit_json(**existmsg)
204
205
206 def process_check_mode(module, diff):
207 if not diff:
208 exit_module(module, msg=NO_CHANGES)
209 elif module.check_mode:
210 exit_module(module, msg=CHANGES_FOUND, changed=True)
211
212
213 def main():
214 credentials_options = {"username": {"type": "str", "required": True},
215 "password": {"type": "str", "required": True, "no_log": True}}
216
217 specs = {
218 "destination_address": {"required": True, "type": "str"},
219 "port_number": {"required": False, "type": "int"},
220 "use_ssl": {"required": False, "type": "bool"},
221 "enable_authentication": {"required": True, "type": "bool"},
222 "credentials":
223 {"required": False, "type": "dict",
224 "options": credentials_options,
225 },
226 }
227
228 module = OmeAnsibleModule(
229 argument_spec=specs,
230 required_if=[['enable_authentication', True, ['credentials']], ],
231 supports_check_mode=True
232 )
233 try:
234 with RestOME(module.params, req_session=True) as rest_obj:
235 curr_resp = fetch_smtp_settings(rest_obj)
236 payload = update_payload(module, curr_resp)
237 diff = _diff_payload(curr_resp, payload)
238 process_check_mode(module, diff)
239 resp = update_smtp_settings(rest_obj, payload)
240 exit_module(module, msg=SUCCESS_MSG,
241 smtp_details=resp.json_data, changed=True)
242
243 except HTTPError as err:
244 exit_module(module, msg=str(err), error_info=json.load(err), failed=True)
245 except URLError as err:
246 exit_module(module, msg=str(err), unreachable=True)
247 except (
248 IOError, ValueError, TypeError, ConnectionError, AttributeError, IndexError, KeyError,
249 OSError) as err:
250 exit_module(module, msg=str(err), error_info={"error": str(err)}, failed=True)
251
252
253 if __name__ == '__main__':
254 main()