Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2022-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 DOCUMENTATION = '''
10 module: na_ontap_file_security_permissions_acl
11 short_description: NetApp ONTAP file security permissions ACL
12 extends_documentation_fragment:
13 - netapp.ontap.netapp.na_ontap_rest
14 version_added: 22.0.0
15 author: NetApp Ansible Team (@carchi8py) <[email protected]>
16 description:
17 - Add, delete, or modify a file_security_permissions ACL on NetApp ONTAP.
18 - Note that ACLs are mached based on ('user', 'access', 'access_control', 'apply_to').
19 To modify any of these 4 properties, you would need to delete the ACL and create a new one.
20 Or use C(netapp.ontap.na_ontap_file_security_permissions).
21
22 options:
23 state:
24 description:
25 - Whether the specified file security permissions ACL should exist or not.
26 choices: ['present', 'absent']
27 type: str
28 default: 'present'
29
30 path:
31 description:
32 - The path of the file or directory on which to apply security permissions.
33 type: str
34 required: true
35
36 vserver:
37 description:
38 - Name of the vserver to use.
39 type: str
40 required: true
41
42 access_control:
43 description:
44 - An Access Control Level specifies the access control of the task to be applied.
45 - Valid values are "file-directory" or "Storage-Level Access Guard (SLAG)".
46 - SLAG is used to apply the specified security descriptors with the task for the volume or qtree.
47 - Otherwise, the security descriptors are applied on files and directories at the specified path.
48 - The value slag is not supported on FlexGroups volumes. The default value is "file-directory".
49 - This field requires ONTAP 9.10.1 or later. This defaults to "file_directory".
50 choices: ['file_directory', 'slag']
51 type: str
52 access:
53 description:
54 - An ACE is an element in an access control list (ACL). An ACL can have zero or more ACEs.
55 - Each ACE controls or monitors access to an object by a specified trustee.
56 choices: ['access_allow', 'access_deny', 'audit_failure', 'audit_success']
57 type: str
58 required: true
59 acl_user:
60 description:
61 - Specifies the account to which the ACE applies. Specify either name or SID.
62 - As of 22.0.0, the module is not idempotent when using a SID.
63 - Note - we cannot use C(user) as if conflicts with the option for the admin user.
64 type: str
65 required: true
66 rights:
67 description:
68 - Specifies the access right controlled by the ACE for the account specified.
69 - The "rights" parameter is mutually exclusive with the "advanced_rights" parameter.
70 - ONTAP translates rights into advanced_rights and this module is not idempotent when rights are used.
71 - Make sure to use C(advanced_rights) to maintain idempotency. C(rights) can be used to discover the mapping to C(advanced_rights).
72 choices: ['no_access', 'full_control', 'modify', 'read_and_execute', 'read', 'write']
73 type: str
74 apply_to:
75 description:
76 - Specifies where to apply the DACL or SACL entries.
77 - With SLAGs, ONTAP accepts the three suboptions to be set to true, but creates 2 ACLs.
78 This module requires the 2 ACLs to be present to preserve idempotency.
79 See also C(validate_changes).
80 type: dict
81 required: true
82 suboptions:
83 files:
84 description:
85 - Apply to Files.
86 type: bool
87 default: false
88 sub_folders:
89 description:
90 - Apply to all sub-folders.
91 type: bool
92 default: false
93 this_folder:
94 description:
95 - Apply only to this folder
96 type: bool
97 default: false
98 advanced_rights:
99 description:
100 - Specifies the advanced access right controlled by the ACE for the account specified.
101 type: dict
102 suboptions:
103 append_data:
104 description:
105 - Append Data.
106 type: bool
107 required: false
108 delete:
109 description:
110 - Delete.
111 type: bool
112 required: false
113 delete_child:
114 description:
115 - Delete Child.
116 type: bool
117 required: false
118 execute_file:
119 description:
120 - Execute File.
121 type: bool
122 required: false
123 full_control:
124 description:
125 - Full Control.
126 type: bool
127 required: false
128 read_attr:
129 description:
130 - Read Attributes.
131 type: bool
132 required: false
133 read_data:
134 description:
135 - Read Data.
136 type: bool
137 required: false
138 read_ea:
139 description:
140 - Read Extended Attributes.
141 type: bool
142 required: false
143 read_perm:
144 description:
145 - Read Permissions.
146 type: bool
147 required: false
148 write_attr:
149 description:
150 - Write Attributes.
151 type: bool
152 required: false
153 write_data:
154 description:
155 - Write Data.
156 type: bool
157 required: false
158 write_ea:
159 description:
160 - Write Extended Attributes.
161 type: bool
162 required: false
163 write_owner:
164 description:
165 - Write Owner.
166 type: bool
167 required: false
168 write_perm:
169 description:
170 - Write Permission.
171 type: bool
172 required: false
173 ignore_paths:
174 description:
175 - For each file or directory in the list, specifies that permissions on this file or directory cannot be replaced.
176 type: list
177 elements: str
178 propagation_mode:
179 description:
180 - Specifies how to propagate security settings to child subfolders and files.
181 - Defaults to propagate.
182 - This option is valid in create, but cannot modify.
183 choices: ['propagate', 'replace']
184 type: str
185
186 validate_changes:
187 description:
188 - ACLs may not be applied as expected.
189 - For instance, if Everyone is inherited will all permissions, additional users will be granted all permissions, regardless of the request.
190 - For this specific example, you can either delete the top level Everyone, or create a new ACL for Everyone at a lower level.
191 - When using C(rights), ONTAP translates them into C(advanced_rights) so the validation will always fail.
192 - Valid values are C(ignore), no checking; C(warn) to issue a warning; C(error) to fail the module.
193 - With SLAGS, ONTAP may split one ACL into two ACLs depending on the C(apply_to) settings. To maintain idempotency, please provide 2 ACLs as input.
194 choices: ['ignore', 'warn', 'error']
195 type: str
196 default: error
197
198 notes:
199 - Supports check_mode.
200 - Only supported with REST and requires ONTAP 9.9.1 or later.
201 - SLAG requires ONTAP 9.10.1 or later.
202 '''
203
204 EXAMPLES = """
205 - name: Add ACL for file or directory security permissions.
206 netapp.ontap.na_ontap_file_security_permissions_acl:
207 vserver: "{{ vserver_name }}"
208 access_control: file_directory
209 path: "{{ file_mount_path }}"
210 validate_changes: warn
211 access: access_allow
212 # Note, without quotes, use a single backslash in AD user names
213 # with quotes, it needs to be escaped as a double backslash
214 # user: "ANSIBLE_CIFS\\user1"
215 # we can't show an example with a single backslash as this is a python file, but it works in YAML.
216 acl_user: "user1"
217 apply_to:
218 this_folder: true
219 advanced_rights:
220 append_data: true
221 delete: false
222
223 - name: Modify ACL for file or directory security permissions.
224 netapp.ontap.na_ontap_file_security_permissions_acl:
225 vserver: "{{ vserver_name }}"
226 access_control: file_directory
227 path: "{{ file_mount_path }}"
228 validate_changes: warn
229 access: access_allow
230 acl_user: "user1"
231 apply_to:
232 this_folder: true
233 advanced_rights:
234 append_data: false
235 delete: true
236
237 - name: Delete ACL for file or directory security permissions.
238 netapp.ontap.na_ontap_file_security_permissions_acl:
239 vserver: "{{ vserver_name }}"
240 access_control: file_directory
241 path: "{{ file_mount_path }}"
242 validate_changes: warn
243 access: access_allow
244 acl_user: "user1"
245 apply_to:
246 this_folder: true
247 state: absent
248 """
249
250 RETURN = """
251 """
252
253 import traceback
254 from ansible.module_utils.basic import AnsibleModule
255 from ansible.module_utils._text import to_native
256 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
257 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
258 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic, rest_vserver
259
260
261 class NetAppOntapFileSecurityPermissionsACL:
262 def __init__(self):
263 self.argument_spec = netapp_utils.na_ontap_rest_only_spec()
264 self.argument_spec.update(dict(
265 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
266 vserver=dict(required=True, type='str'),
267 path=dict(required=True, type='str'),
268 access_control=dict(required=False, type='str', choices=['file_directory', 'slag']),
269 access=dict(required=True, choices=['access_allow', 'access_deny', 'audit_failure', 'audit_success'], type='str'),
270 apply_to=dict(required=True, type='dict', options=dict(
271 files=dict(required=False, type='bool', default=False),
272 sub_folders=dict(required=False, type='bool', default=False),
273 this_folder=dict(required=False, type='bool', default=False),
274 )),
275 advanced_rights=dict(required=False, type='dict', options=dict(
276 append_data=dict(required=False, type='bool'),
277 delete=dict(required=False, type='bool'),
278 delete_child=dict(required=False, type='bool'),
279 execute_file=dict(required=False, type='bool'),
280 full_control=dict(required=False, type='bool'),
281 read_attr=dict(required=False, type='bool'),
282 read_data=dict(required=False, type='bool'),
283 read_ea=dict(required=False, type='bool'),
284 read_perm=dict(required=False, type='bool'),
285 write_attr=dict(required=False, type='bool'),
286 write_data=dict(required=False, type='bool'),
287 write_ea=dict(required=False, type='bool'),
288 write_owner=dict(required=False, type='bool'),
289 write_perm=dict(required=False, type='bool'),
290 )),
291 ignore_paths=dict(required=False, type='list', elements='str'),
292 propagation_mode=dict(required=False, type='str', choices=['propagate', 'replace']),
293 rights=dict(required=False,
294 choices=['no_access', 'full_control', 'modify', 'read_and_execute', 'read', 'write'],
295 type='str'),
296 acl_user=dict(required=True, type='str'),
297 validate_changes=dict(required=False, type='str', choices=['ignore', 'warn', 'error'], default='error'),
298 ))
299 self.module = AnsibleModule(
300 argument_spec=self.argument_spec,
301 supports_check_mode=True
302 )
303 self.svm_uuid = None
304 self.na_helper = NetAppModule(self.module)
305 self.parameters = self.na_helper.check_and_set_parameters(self.module)
306 self.rest_api = netapp_utils.OntapRestAPI(self.module)
307 self.rest_api.fail_if_not_rest_minimum_version('na_ontap_file_security_permissions_acl', 9, 9, 1)
308 dummy, error = self.rest_api.is_rest(partially_supported_rest_properties=[['access_control', (9, 10, 1)]], parameters=self.parameters)
309 self.apply_to_keys = ['files', 'sub_folders', 'this_folder']
310 if self.parameters['state'] == 'present':
311 self.validate_acl()
312 self.parameters['user'] = self.parameters['acl_user']
313
314 def validate_acl(self):
315 self.parameters = self.na_helper.filter_out_none_entries(self.parameters)
316 if 'rights' in self.parameters:
317 if 'advanced_rights' in self.parameters:
318 self.module.fail_json(msg="Error: suboptions 'rights' and 'advanced_rights' are mutually exclusive.")
319 self.module.warn('This module is not idempotent when "rights" is used, make sure to use "advanced_rights".')
320 # validate that at least one suboption is true
321 if not any(self.na_helper.safe_get(self.parameters, ['apply_to', key]) for key in self.apply_to_keys):
322 self.module.fail_json(msg="Error: at least one suboption must be true for apply_to. Got: %s" % self.parameters.get('apply_to'))
323
324 @staticmethod
325 def url_encode(url_fragment):
326 """
327 replace special characters with URL encoding:
328 %2F for /, %5C for backslash
329 """
330 # \ is the escape character in python, so \\ means \
331 return url_fragment.replace("/", "%2F").replace("\\", "%5C")
332
333 def get_svm_uuid(self):
334 self.svm_uuid, dummy = rest_vserver.get_vserver_uuid(self.rest_api, self.parameters['vserver'], self.module, True)
335
336 def get_file_security_permissions_acl(self):
337 """ we cannot get a single ACL - get a list, and find ours"""
338 api = 'protocols/file-security/permissions/%s/%s' % (self.svm_uuid, self.url_encode(self.parameters['path']))
339 fields = 'acls'
340 record, error = rest_generic.get_one_record(self.rest_api, api, fields=fields)
341 # If we get 655865 the path we gave was not found, so we don't want to fail we want to return None
342 if error:
343 if '655865' in error and self.parameters['state'] == 'absent':
344 return None
345 self.module.fail_json(msg="Error fetching file security permissions %s: %s" % (self.parameters['path'], to_native(error)),
346 exception=traceback.format_exc())
347 if record and 'acls' in record:
348 record = self.form_current(record)
349 return self.match_acl_with_acls(self.parameters, record['acls'])
350 return None
351
352 def form_current(self, record):
353 current = {
354 'group': self.na_helper.safe_get(record, ['group']),
355 'owner': self.na_helper.safe_get(record, ['owner']),
356 'control_flags': self.na_helper.safe_get(record, ['control_flags']),
357 'path': record['path']
358 }
359 acls = []
360
361 def form_acl(acl):
362 advanced_rights_keys = ['append_data', 'delete', 'delete_child', 'execute_file', 'full_control', 'read_attr',
363 'read_data', 'read_ea', 'read_perm', 'write_attr', 'write_data', 'write_ea', 'write_owner', 'write_perm']
364 advanced_rights = {}
365 apply_to = {}
366 if 'advanced_rights' in acl:
367 for key in advanced_rights_keys:
368 # REST does not return the keys when the value is False
369 advanced_rights[key] = acl['advanced_rights'].get(key, False)
370 if 'apply_to' in acl:
371 for key in self.apply_to_keys:
372 # REST does not return the keys when the value is False
373 apply_to[key] = acl['apply_to'].get(key, False)
374 return {
375 'advanced_rights': advanced_rights or None,
376 'apply_to': apply_to or None
377 }
378
379 for acl in record.get('acls', []):
380 each_acl = {
381 'access': self.na_helper.safe_get(acl, ['access']),
382 'access_control': self.na_helper.safe_get(acl, ['access_control']),
383 'inherited': self.na_helper.safe_get(acl, ['inherited']),
384 'rights': self.na_helper.safe_get(acl, ['rights']),
385 'user': self.na_helper.safe_get(acl, ['user']),
386 }
387 each_acl.update(form_acl(acl))
388 acls.append(each_acl)
389 current['acls'] = acls or None
390 return current
391
392 def build_body(self, action):
393 keys = {
394 'create': ['access', 'access_control', 'advanced_rights', 'apply_to', 'ignore_paths', 'propagation_mode', 'rights', 'user'],
395 'modify': ['access', 'access_control', 'advanced_rights', 'apply_to', 'ignore_paths', 'rights'],
396 'delete': ['access', 'access_control', 'apply_to', 'ignore_paths', 'propagation_mode'],
397 # 'delete': ['access', 'access_control', 'ignore_paths', 'propagation_mode'],
398 }
399 if action not in keys:
400 self.module.fail_json(msg='Internal error - unexpected action %s' % action)
401 body = {}
402 for key in keys[action]:
403 if key in self.parameters:
404 body[key] = self.parameters[key]
405 return body
406
407 def create_file_security_permissions_acl(self):
408 api = 'protocols/file-security/permissions/%s/%s/acl' % (self.svm_uuid, self.url_encode(self.parameters['path']))
409 body = self.build_body('create')
410 dummy, error = rest_generic.post_async(self.rest_api, api, body, timeout=0)
411 if error:
412 self.module.fail_json(msg='Error creating file security permissions acl %s: %s' % (self.parameters['path'], to_native(error)),
413 exception=traceback.format_exc())
414
415 def modify_file_security_permissions_acl(self):
416 api = 'protocols/file-security/permissions/%s/%s/acl' % (self.svm_uuid, self.url_encode(self.parameters['path']))
417 body = self.build_body('modify')
418 dummy, error = rest_generic.patch_async(self.rest_api, api, self.url_encode(self.parameters['user']), body)
419 if error:
420 self.module.fail_json(msg='Error modifying file security permissions acl %s: %s' % (self.parameters['path'], to_native(error)),
421 exception=traceback.format_exc())
422
423 def delete_file_security_permissions_acl(self):
424 api = 'protocols/file-security/permissions/%s/%s/acl' % (self.svm_uuid, self.url_encode(self.parameters['path']))
425 body = self.build_body('delete')
426 dummy, error = rest_generic.delete_async(self.rest_api, api, self.url_encode(self.parameters['user']), body=body, timeout=0)
427 if error:
428 self.module.fail_json(msg='Error deleting file security permissions acl %s: %s' % (self.parameters['path'], to_native(error)),
429 exception=traceback.format_exc())
430
431 def match_acl_with_acls(self, acl, acls):
432 """ return acl if user and access and apply_to are matched, otherwiese None """
433 matches = []
434 for an_acl in acls:
435 # with 9.9.1, access_control is not supported. It will be set to None in received ACLs, and omitted in desired ACLs
436 # but we can assume the user would like to see file_directory.
437 # We can't modify inherited ACLs. But we can create a new one at a lower scope.
438 inherited = an_acl['inherited'] if 'inherited' in an_acl else False and (acl['inherited'] if 'inherited' in acl else False)
439 if (acl['user'] == an_acl['user']
440 and acl['access'] == an_acl['access']
441 and acl.get('access_control', 'file_directory') == an_acl.get('access_control', 'file_directory')
442 and acl['apply_to'] == an_acl['apply_to']
443 and not inherited):
444 matches.append(an_acl)
445 if len(matches) > 1:
446 self.module.fail_json(msg='Error matching ACLs, found more than one match. Found %s' % matches)
447 return matches[0] if matches else None
448
449 def get_actions(self):
450 current = self.get_file_security_permissions_acl()
451 modify = None
452 cd_action = self.na_helper.get_cd_action(current, self.parameters)
453 if cd_action is None and self.parameters['state'] == 'present':
454 modify = self.na_helper.get_modified_attributes(current, self.parameters)
455 return cd_action, modify
456
457 def apply(self):
458 self.get_svm_uuid()
459 cd_action, modify = self.get_actions()
460
461 if self.na_helper.changed and not self.module.check_mode:
462 if cd_action == 'create':
463 self.create_file_security_permissions_acl()
464 if cd_action == 'delete':
465 self.delete_file_security_permissions_acl()
466 if modify:
467 self.modify_file_security_permissions_acl()
468 self.validate_changes(cd_action, modify)
469 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
470 self.module.exit_json(**result)
471
472 def validate_changes(self, cd_action, modify):
473 if self.parameters['validate_changes'] == 'ignore':
474 return
475 new_cd_action, new_modify = self.get_actions()
476 errors = []
477 if new_cd_action is not None:
478 errors.append('%s still required after %s (with modify: %s)' % (new_cd_action, cd_action, modify))
479 if new_modify:
480 errors.append('modify: %s still required after %s' % (new_modify, modify))
481 if errors:
482 msg = 'Error - %s' % ' - '.join(errors)
483 if self.parameters['validate_changes'] == 'error':
484 self.module.fail_json(msg=msg)
485 if self.parameters['validate_changes'] == 'warn':
486 self.module.warn(msg)
487
488
489 def main():
490 """Apply volume operations from playbook"""
491 obj = NetAppOntapFileSecurityPermissionsACL()
492 obj.apply()
493
494
495 if __name__ == '__main__':
496 main()