Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/modules/na_santricity_ldap.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 # (c) 2024, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8
9 DOCUMENTATION = """
10 ---
11 module: na_santricity_ldap
12 short_description: NetApp E-Series manage LDAP integration to use for authentication
13 description:
14 - Configure an E-Series system to allow authentication via an LDAP server
15 author:
16 - Michael Price (@lmprice)
17 - Nathan Swartz (@swartzn)
18 - Vu Tran (@VuTran007)
19 extends_documentation_fragment:
20 - netapp_eseries.santricity.santricity.santricity_doc
21 options:
22 state:
23 description:
24 - When I(state=="present") the defined LDAP domain will be added to the storage system.
25 - When I(state=="absent") the domain specified will be removed from the storage system.
26 - I(state=="disabled") will result in deleting all existing LDAP domains on the storage system.
27 type: str
28 choices:
29 - present
30 - absent
31 - disabled
32 default: present
33 identifier:
34 description:
35 - This is a unique identifier for the configuration (for cases where there are multiple domains configured).
36 type: str
37 default: "default"
38 required: false
39 bind_user:
40 description:
41 - This is the user account that will be used for querying the LDAP server.
42 - Required when I(bind_password) is specified.
43 - "Example: CN=MyBindAcct,OU=ServiceAccounts,DC=example,DC=com"
44 type: str
45 required: false
46 bind_password:
47 description:
48 - This is the password for the bind user account.
49 - Required when I(bind_user) is specified.
50 type: str
51 required: false
52 server_url:
53 description:
54 - This is the LDAP server url.
55 - The connection string should be specified as using the ldap or ldaps protocol along with the port information.
56 type: str
57 required: false
58 names:
59 description:
60 - The domain name[s] that will be utilized when authenticating to identify which domain to utilize.
61 - Default to use the DNS name of the I(server).
62 - The only requirement is that the name[s] be resolvable.
63 - "Example: [email protected]"
64 type: list
65 elements: str
66 required: false
67 search_base:
68 description:
69 - The search base is used to find group memberships of the user.
70 - "Example: ou=users,dc=example,dc=com"
71 type: str
72 required: false
73 role_mappings:
74 description:
75 - This is where you specify which groups should have access to what permissions for the
76 storage-system.
77 - For example, all users in group A will be assigned all 4 available roles, which will allow access
78 to all the management functionality of the system (super-user). Those in group B only have the
79 storage.monitor role, which will allow only read-only access.
80 - This is specified as a mapping of regular expressions to a list of roles. See the examples.
81 - The roles that will be assigned to to the group/groups matching the provided regex.
82 - storage.admin allows users full read/write access to storage objects and operations.
83 - storage.monitor allows users read-only access to storage objects and operations.
84 - support.admin allows users access to hardware, diagnostic information, the Major Event
85 Log, and other critical support-related functionality, but not the storage configuration.
86 - security.admin allows users access to authentication/authorization configuration, as well
87 as the audit log configuration, and certification management.
88 type: dict
89 required: false
90 group_attributes:
91 description:
92 - The user attributes that should be considered for the group to role mapping.
93 - Typically this is used with something like "memberOf", and a user"s access is tested against group
94 membership or lack thereof.
95 type: list
96 elements: str
97 default: ["memberOf"]
98 required: false
99 user_attribute:
100 description:
101 - This is the attribute we will use to match the provided username when a user attempts to
102 authenticate.
103 type: str
104 default: "sAMAccountName"
105 required: false
106 notes:
107 - Check mode is supported
108 - This module allows you to define one or more LDAP domains identified uniquely by I(identifier) to use for
109 authentication. Authorization is determined by I(role_mappings), in that different groups of users may be given
110 different (or no), access to certain aspects of the system and API.
111 - The local user accounts will still be available if the LDAP server becomes unavailable/inaccessible.
112 - Generally, you"ll need to get the details of your organization"s LDAP server before you"ll be able to configure
113 the system for using LDAP authentication; every implementation is likely to be very different.
114 - This API is currently only supported with the Embedded Web Services API v2.0 and higher, or the Web Services Proxy
115 v3.0 and higher.
116 """
117
118 EXAMPLES = """
119 - name: Disable LDAP authentication
120 na_santricity_ldap:
121 ssid: "1"
122 api_url: "https://192.168.1.100:8443/devmgr/v2"
123 api_username: "admin"
124 api_password: "adminpass"
125 validate_certs: true
126 state: absent
127
128 - name: Remove the "default" LDAP domain configuration
129 na_santricity_ldap:
130 ssid: "1"
131 api_url: "https://192.168.1.100:8443/devmgr/v2"
132 api_username: "admin"
133 api_password: "adminpass"
134 validate_certs: true
135 state: absent
136 identifier: default
137
138 - name: Define a new LDAP domain, utilizing defaults where possible
139 na_santricity_ldap:
140 ssid: "1"
141 api_url: "https://192.168.1.100:8443/devmgr/v2"
142 api_username: "admin"
143 api_password: "adminpass"
144 validate_certs: true
145 state: enabled
146 bind_username: "CN=MyBindAccount,OU=ServiceAccounts,DC=example,DC=com"
147 bind_password: "mySecretPass"
148 server: "ldap://example.com:389"
149 search_base: "OU=Users,DC=example,DC=com"
150 role_mappings:
151 ".*dist-dev-storage.*":
152 - storage.admin
153 - security.admin
154 - support.admin
155 - storage.monitor
156 """
157
158 RETURN = """
159 msg:
160 description: Success message
161 returned: on success
162 type: str
163 sample: The ldap settings have been updated.
164 """
165 from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import NetAppESeriesModule
166 from ansible.module_utils._text import to_native
167
168 try:
169 import urlparse
170 except ImportError:
171 import urllib.parse as urlparse
172
173
174 class NetAppESeriesLdap(NetAppESeriesModule):
175 NO_CHANGE_MSG = "No changes were necessary."
176 TEMPORARY_DOMAIN = "ANSIBLE_TMP_DOMAIN"
177
178 def __init__(self):
179 ansible_options = dict(state=dict(type="str", required=False, default="present", choices=["present", "absent", "disabled"]),
180 identifier=dict(type="str", required=False, default="default"),
181 bind_user=dict(type="str", required=False),
182 bind_password=dict(type="str", required=False, no_log=True),
183 names=dict(type="list", elements="str", required=False),
184 server_url=dict(type="str", required=False),
185 search_base=dict(type="str", required=False),
186 role_mappings=dict(type="dict", required=False, no_log=True),
187 group_attributes=dict(type="list", elements="str", default=["memberOf"], required=False),
188 user_attribute=dict(type="str", required=False, default="sAMAccountName"))
189
190 required_if = [["state", "present", ["server_url"]]]
191 required_together = [["bind_user", "bind_password"]]
192 super(NetAppESeriesLdap, self).__init__(ansible_options=ansible_options,
193 web_services_version="02.00.0000.0000",
194 required_if=required_if,
195 required_together=required_together,
196 supports_check_mode=True)
197
198 args = self.module.params
199 self.state = args["state"]
200 self.id = args["identifier"]
201 self.bind_user = args["bind_user"]
202 self.bind_password = args["bind_password"]
203 self.names = args["names"]
204 self.server = args["server_url"]
205 self.search_base = args["search_base"]
206 self.role_mappings = args["role_mappings"]
207 self.group_attributes = args["group_attributes"]
208 self.user_attribute = args["user_attribute"]
209
210 if self.server and not self.names:
211 parts = urlparse.urlparse(self.server)
212 self.names = [parts.netloc.split(':')[0]]
213
214 # Check whether request needs to be forwarded on to the controller web services rest api.
215 self.url_path_prefix = ""
216 if self.is_embedded():
217 self.url_path_prefix = "storage-systems/1/"
218 elif self.ssid != "0" and self.ssid.lower() != "proxy":
219 self.url_path_prefix = "storage-systems/%s/forward/devmgr/v2/storage-systems/1/" % self.ssid
220
221 self.existing_domain_ids = []
222 self.domain = {} # Existing LDAP domain
223 self.body = {} # Request body
224
225 def get_domains(self):
226 """Retrieve all domain information from storage system."""
227 domains = None
228 try:
229 rc, response = self.request(self.url_path_prefix + "ldap")
230 domains = response["ldapDomains"]
231 except Exception as error:
232 self.module.fail_json(msg="Failed to retrieve current LDAP configuration. Array Id [%s]. Error [%s]." % (self.ssid, to_native(error)))
233
234 return domains
235
236 def build_request_body(self):
237 """Build the request body."""
238 self.body.update({"id": self.id, "groupAttributes": self.group_attributes, "ldapUrl": self.server, "names": self.names, "roleMapCollection": []})
239
240 if self.search_base:
241 self.body.update({"searchBase": self.search_base})
242 if self.user_attribute:
243 self.body.update({"userAttribute": self.user_attribute})
244 if self.bind_user and self.bind_password:
245 self.body.update({"bindLookupUser": {"password": self.bind_password, "user": self.bind_user}})
246 if self.role_mappings:
247 for regex, names in self.role_mappings.items():
248 for name in names:
249 self.body["roleMapCollection"].append({"groupRegex": regex, "ignorecase": True, "name": name})
250
251 def are_changes_required(self):
252 """Determine whether any changes are required and build request body."""
253 change_required = False
254 domains = self.get_domains()
255
256 if self.state == "disabled" and domains:
257 self.existing_domain_ids = [domain["id"] for domain in domains]
258 change_required = True
259
260 elif self.state == "present":
261 for domain in domains:
262 if self.id == domain["id"]:
263 self.domain = domain
264
265 if self.state == "absent":
266 change_required = True
267 elif (len(self.group_attributes) != len(domain["groupAttributes"]) or
268 any(a not in domain["groupAttributes"] for a in self.group_attributes)):
269 change_required = True
270 elif self.user_attribute != domain["userAttribute"]:
271 change_required = True
272 elif self.search_base.lower() != domain["searchBase"].lower():
273 change_required = True
274 elif self.server != domain["ldapUrl"]:
275 change_required = True
276 elif any(name not in domain["names"] for name in self.names) or any(name not in self.names for name in domain["names"]):
277 change_required = True
278 elif self.role_mappings:
279 if len(self.body["roleMapCollection"]) != len(domain["roleMapCollection"]):
280 change_required = True
281 else:
282 for role_map in self.body["roleMapCollection"]:
283 for existing_role_map in domain["roleMapCollection"]:
284 if role_map["groupRegex"] == existing_role_map["groupRegex"] and role_map["name"] == existing_role_map["name"]:
285 break
286 else:
287 change_required = True
288
289 if not change_required and self.bind_user and self.bind_password:
290 if self.bind_user != domain["bindLookupUser"]["user"]:
291 change_required = True
292 elif self.bind_password:
293 temporary_domain = None
294 try:
295 # Check whether temporary domain exists
296 if any(domain["id"] == self.TEMPORARY_DOMAIN for domain in domains):
297 self.delete_domain(self.TEMPORARY_DOMAIN)
298
299 temporary_domain = self.add_domain(temporary=True, skip_test=True)
300 rc, tests = self.request(self.url_path_prefix + "ldap/test", method="POST")
301
302 temporary_domain_test = {}
303 domain_test = {}
304 for test in tests:
305 if test["id"] == temporary_domain["id"]:
306 temporary_domain_test = test["result"]
307 if self.id == test["id"]:
308 domain_test = test["result"]
309
310 if temporary_domain_test["authenticationTestResult"] == "ok" and domain_test["authenticationTestResult"] != "ok":
311 change_required = True
312 elif temporary_domain_test["authenticationTestResult"] != "ok":
313 self.module.fail_json(msg="Failed to authenticate bind credentials! Array Id [%s]." % self.ssid)
314
315 finally:
316 if temporary_domain:
317 self.delete_domain(self.TEMPORARY_DOMAIN)
318 break
319 else:
320 change_required = True
321 elif self.state == "absent":
322 for domain in domains:
323 if self.id == domain["id"]:
324 change_required = True
325
326 return change_required
327
328 def add_domain(self, temporary=False, skip_test=False):
329 """Add domain to storage system."""
330 domain = None
331 body = self.body.copy()
332 if temporary:
333 body.update({"id": self.TEMPORARY_DOMAIN, "names": [self.TEMPORARY_DOMAIN]})
334
335 try:
336 rc, response = self.request(self.url_path_prefix + "ldap/addDomain?skipTest=%s" % ("true" if not skip_test else "false"),
337 method="POST", data=body)
338 domain = response["ldapDomains"][0]
339 except Exception as error:
340 self.module.fail_json(msg="Failed to create LDAP domain. Array Id [%s]. Error [%s]." % (self.ssid, to_native(error)))
341
342 return domain
343
344 def update_domain(self):
345 """Update existing domain on storage system."""
346 try:
347 rc, response = self.request(self.url_path_prefix + "ldap/%s" % self.domain["id"], method="POST", data=self.body)
348 except Exception as error:
349 self.module.fail_json(msg="Failed to update LDAP domain. Array Id [%s]. Error [%s]." % (self.ssid, to_native(error)))
350
351 def delete_domain(self, domain_id):
352 """Delete specific domain on the storage system."""
353 try:
354 url = self.url_path_prefix + "ldap/%s" % domain_id
355 rc, response = self.request(self.url_path_prefix + "ldap/%s" % domain_id, method="DELETE")
356 except Exception as error:
357 self.module.fail_json(msg="Failed to delete LDAP domain. Array Id [%s]. Error [%s]." % (self.ssid, to_native(error)))
358
359 def disable_domains(self):
360 """Delete all existing domains on storage system."""
361 for domain_id in self.existing_domain_ids:
362 self.delete_domain(domain_id)
363
364 def apply(self):
365 """Apply any necessary changes to the LDAP configuration."""
366 self.build_request_body()
367 change_required = self.are_changes_required()
368
369 if change_required and not self.module.check_mode:
370 if self.state == "present":
371 if self.domain:
372 self.update_domain()
373 self.module.exit_json(msg="LDAP domain has been updated. Array Id: [%s]" % self.ssid, changed=change_required)
374 else:
375 self.add_domain()
376 self.module.exit_json(msg="LDAP domain has been added. Array Id: [%s]" % self.ssid, changed=change_required)
377 elif self.state == "absent":
378 if self.domain:
379 self.delete_domain(self.domain["id"])
380 self.module.exit_json(msg="LDAP domain has been removed. Array Id: [%s]" % self.ssid, changed=change_required)
381 else:
382 self.disable_domains()
383 self.module.exit_json(msg="All LDAP domains have been removed. Array Id: [%s]" % self.ssid, changed=change_required)
384
385 self.module.exit_json(msg="No changes have been made to the LDAP configuration. Array Id: [%s]" % self.ssid, changed=change_required)
386
387
388 def main():
389 ldap = NetAppESeriesLdap()
390 ldap.apply()
391
392
393 if __name__ == "__main__":
394 main()