Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2026, 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_export_policy_rule
8 '''
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14
15 module: na_ontap_export_policy_rule
16
17 short_description: NetApp ONTAP manage export policy rules
18 extends_documentation_fragment:
19 - netapp.ontap.netapp.na_ontap
20 version_added: 2.6.0
21 author: NetApp Ansible Team (@carchi8py) <[email protected]>
22
23 description:
24 - Create or delete or modify export rules in ONTAP
25
26 options:
27 state:
28 description:
29 - Whether the specified export policy rule should exist or not.
30 required: false
31 choices: ['present', 'absent']
32 type: str
33 default: present
34
35 name:
36 description:
37 - The name of the export policy this rule will be added to (or modified, or removed from).
38 required: True
39 type: str
40 aliases:
41 - policy_name
42
43 client_match:
44 description:
45 - List of Client Match host names, IP Addresses, Netgroups, or Domains.
46 type: list
47 elements: str
48
49 anonymous_user_id:
50 description:
51 - User name or ID to which anonymous users are mapped. Default value is '65534'.
52 type: str
53
54 ro_rule:
55 description:
56 - List of Read only access specifications for the rule
57 choices: ['any','none','never','krb5','krb5i','krb5p','ntlm','sys']
58 type: list
59 elements: str
60
61 rw_rule:
62 description:
63 - List of Read Write access specifications for the rule
64 choices: ['any','none','never','krb5','krb5i','krb5p','ntlm','sys']
65 type: list
66 elements: str
67
68 super_user_security:
69 description:
70 - List of Read Write access specifications for the rule
71 choices: ['any','none','krb5','krb5i','krb5p','ntlm','sys']
72 type: list
73 elements: str
74
75 allow_suid:
76 description:
77 - If 'true', NFS server will honor SetUID bits in SETATTR operation. Default value on creation is 'true'
78 type: bool
79
80 protocol:
81 description:
82 - List of Client access protocols.
83 - Default value is set to 'any' during create.
84 choices: [any,nfs,nfs3,nfs4,cifs,flexcache]
85 type: list
86 elements: str
87 aliases:
88 - protocols
89
90 rule_index:
91 description:
92 - Index of the export policy rule.
93 - When rule_index is not set, we try to find a rule with an exact match.
94 If found, no action is taken with state set to present, and the rule is deleted with state set to absent.
95 An error is reported if more than one rule is found.
96 - When rule_index is set and state is present, if a rule cannot be found with this index,
97 we try to find a rule with an exact match and assign the index to this rule if found.
98 If no match is found, a new rule is created.
99 - All attributes that are set are used for an exact match. As a minimum, client_match, ro_rule, and rw_rule are required.
100 type: int
101
102 from_rule_index:
103 description:
104 - index of the export policy rule to be re-indexed
105 type: int
106 version_added: 21.20.0
107
108 vserver:
109 description:
110 - Name of the vserver to use.
111 required: true
112 type: str
113
114 ntfs_unix_security:
115 description:
116 - NTFS export UNIX security options.
117 - With REST, supported from ONTAP 9.9.1 version.
118 type: str
119 choices: ['fail', 'ignore']
120 version_added: 21.18.0
121
122 force_delete_on_first_match:
123 description:
124 - when rule_index is not set, the default is to report an error on multiple matches.
125 - when this option is set, one of the rules with an exact match is deleted when state is absent.
126 - ignored when state is present.
127 type: bool
128 default: false
129 version_added: 21.23.0
130
131 chown_mode:
132 description:
133 - Specifies who is authorized to change the ownership mode of a file.
134 - With REST, supported from ONTAP 9.9.1 version.
135 type: str
136 choices: ['restricted', 'unrestricted']
137 version_added: 22.0.0
138
139 allow_device_creation:
140 description:
141 - Specifies whether or not device creation is allowed.
142 - default is true.
143 - With REST, supported from ONTAP 9.9.1 version.
144 type: bool
145 version_added: 22.0.0
146
147 lambda_config:
148 description:
149 - Configuration parameters for AWS Lambda proxy functionality.
150 - These option and suboptions are only supported with REST.
151 type: dict
152 version_added: 23.5.0
153 suboptions:
154 function_name:
155 description:
156 - The name of the AWS Lambda function to invoke.
157 type: str
158 required: true
159 aws_region:
160 description:
161 - The name of the AWS region.
162 type: str
163 required: true
164 aws_profile:
165 description:
166 - The name of the AWS profile to use for authentication.
167 type: str
168
169 notes:
170 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
171 '''
172
173 EXAMPLES = """
174 - name: Create ExportPolicyRule
175 netapp.ontap.na_ontap_export_policy_rule:
176 state: present
177 name: default123
178 rule_index: 100
179 vserver: ci_dev
180 client_match: 0.0.0.0/0,1.1.1.0/24
181 ro_rule: krb5,krb5i
182 rw_rule: any
183 protocol: nfs,nfs3
184 super_user_security: any
185 anonymous_user_id: 65534
186 allow_suid: true
187 ntfs_unix_security: ignore
188 hostname: "{{ netapp_hostname }}"
189 username: "{{ netapp_username }}"
190 password: "{{ netapp_password }}"
191
192 - name: Modify ExportPolicyRule
193 netapp.ontap.na_ontap_export_policy_rule:
194 state: present
195 name: default123
196 rule_index: 100
197 vserver: ci_dev
198 client_match: 0.0.0.0/0
199 anonymous_user_id: 65521
200 ro_rule: ntlm
201 rw_rule: any
202 protocol: any
203 allow_suid: false
204 ntfs_unix_security: fail
205 hostname: "{{ netapp_hostname }}"
206 username: "{{ netapp_username }}"
207 password: "{{ netapp_password }}"
208
209 - name: Rename ExportPolicyRule index
210 netapp.ontap.na_ontap_export_policy_rule:
211 state: present
212 name: default123
213 from_rule_index: 100
214 rule_index: 99
215 client_match: 0.0.0.0/0
216 anonymous_user_id: 65521
217 ro_rule: ntlm
218 rw_rule: any
219 protocol: any
220 allow_suid: false
221 ntfs_unix_security: fail
222 hostname: "{{ netapp_hostname }}"
223 username: "{{ netapp_username }}"
224 password: "{{ netapp_password }}"
225
226 - name: Delete ExportPolicyRule
227 netapp.ontap.na_ontap_export_policy_rule:
228 state: absent
229 name: default123
230 rule_index: 99
231 vserver: ci_dev
232 hostname: "{{ netapp_hostname }}"
233 username: "{{ netapp_username }}"
234 password: "{{ netapp_password }}"
235 """
236
237 RETURN = """
238
239
240 """
241 import traceback
242
243 from ansible.module_utils.basic import AnsibleModule
244 from ansible.module_utils._text import to_native
245 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
246 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
247 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
248
249
250 class NetAppontapExportRule:
251 ''' object initialize and class methods '''
252
253 def __init__(self):
254 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
255 self.argument_spec.update(dict(
256 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
257 name=dict(required=True, type='str', aliases=['policy_name']),
258 protocol=dict(required=False,
259 type='list', elements='str', default=None,
260 choices=['any', 'nfs', 'nfs3', 'nfs4', 'cifs', 'flexcache'],
261 aliases=['protocols']),
262 client_match=dict(required=False, type='list', elements='str'),
263 ro_rule=dict(required=False,
264 type='list', elements='str', default=None,
265 choices=['any', 'none', 'never', 'krb5', 'krb5i', 'krb5p', 'ntlm', 'sys']),
266 rw_rule=dict(required=False,
267 type='list', elements='str', default=None,
268 choices=['any', 'none', 'never', 'krb5', 'krb5i', 'krb5p', 'ntlm', 'sys']),
269 super_user_security=dict(required=False,
270 type='list', elements='str', default=None,
271 choices=['any', 'none', 'krb5', 'krb5i', 'krb5p', 'ntlm', 'sys']),
272 allow_suid=dict(required=False, type='bool'),
273 from_rule_index=dict(required=False, type='int'),
274 rule_index=dict(required=False, type='int'),
275 anonymous_user_id=dict(required=False, type='str'),
276 vserver=dict(required=True, type='str'),
277 ntfs_unix_security=dict(required=False, type='str', choices=['fail', 'ignore']),
278 force_delete_on_first_match=dict(required=False, type='bool', default=False),
279 chown_mode=dict(required=False, type='str', choices=['restricted', 'unrestricted']),
280 allow_device_creation=dict(required=False, type='bool'),
281 ))
282 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
283 self.module = AnsibleModule(
284 argument_spec=self.argument_spec,
285 supports_check_mode=True,
286 required_if=[('use_lambda', True, ('lambda_config',))],
287 )
288
289 self.na_helper = NetAppModule()
290 self.parameters = self.na_helper.set_parameters(self.module.params)
291 self.set_playbook_zapi_key_map()
292 self.policy_id = None
293
294 self.rest_api = netapp_utils.OntapRestAPI(self.module)
295 partially_supported_rest_properties = [['ntfs_unix_security', (9, 9, 1)], ['allow_suid', (9, 9, 1)],
296 ['allow_device_creation', (9, 9, 1)], ['chown_mode', (9, 9, 1)]]
297 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, None, partially_supported_rest_properties)
298 if not self.use_rest:
299 if self.parameters.get('use_lambda'):
300 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
301 if not netapp_utils.has_netapp_lib():
302 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
303 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
304 if 'rule_index' not in self.parameters:
305 self.fail_on_missing_required_params('matching (as rule_index is not specified) or creating')
306
307 def fail_on_missing_required_params(self, action):
308 missing_keys = [key for key in ('client_match', 'ro_rule', 'rw_rule') if self.parameters.get(key) is None]
309 plural = 's' if len(missing_keys) > 1 else ''
310 if missing_keys:
311 self.module.fail_json(msg='Error: Missing required option%s for %s export policy rule: %s' % (plural, action, ', '.join(missing_keys)))
312
313 def set_playbook_zapi_key_map(self):
314 self.na_helper.zapi_string_keys = {
315 'anonymous_user_id': 'anonymous-user-id',
316 'client_match': 'client-match',
317 'name': 'policy-name',
318 'ntfs_unix_security': 'export-ntfs-unix-security-ops',
319 'chown_mode': 'export-chown-mode'
320 }
321 self.na_helper.zapi_list_keys = {
322 'protocol': ('protocol', 'access-protocol'),
323 'ro_rule': ('ro-rule', 'security-flavor'),
324 'rw_rule': ('rw-rule', 'security-flavor'),
325 'super_user_security': ('super-user-security', 'security-flavor'),
326 }
327 self.na_helper.zapi_bool_keys = {
328 'allow_suid': 'is-allow-set-uid-enabled',
329 'allow_device_creation': 'is-allow-dev-is-enabled'
330 }
331 self.na_helper.zapi_int_keys = {
332 'rule_index': 'rule-index'
333 }
334
335 @staticmethod
336 def set_dict_when_not_none(query, key, value):
337 if value is not None:
338 query[key] = value
339
340 @staticmethod
341 def list_to_string(alist):
342 return ','.join(alist).replace(' ', '') if alist else ''
343
344 def set_query_parameters(self, rule_index):
345 """
346 Return dictionary of query parameters and
347 :return:
348 """
349 query = {
350 'policy-name': self.parameters['name'],
351 'vserver': self.parameters['vserver']
352 }
353 if rule_index is not None:
354 query['rule-index'] = rule_index
355 else:
356 for item_key, value in self.parameters.items():
357 zapi_key = None
358 if item_key in self.na_helper.zapi_string_keys and item_key != 'client_match':
359 # ignore client_match as ZAPI query is string based and preserves order
360 zapi_key = self.na_helper.zapi_string_keys[item_key]
361 elif item_key in self.na_helper.zapi_bool_keys:
362 zapi_key = self.na_helper.zapi_bool_keys[item_key]
363 value = self.na_helper.get_value_for_bool(from_zapi=False, value=value)
364 # skipping int keys to not include rule index in query as we're matching on attributes
365 elif item_key in self.na_helper.zapi_list_keys:
366 zapi_key, child_key = self.na_helper.zapi_list_keys[item_key]
367 value = [{child_key: item} for item in value] if value else None
368 if zapi_key:
369 self.set_dict_when_not_none(query, zapi_key, value)
370
371 return {
372 'query': {
373 'export-rule-info': query
374 }
375 }
376
377 def get_export_policy_rule(self, rule_index):
378 """
379 Return details about the export policy rule
380 If rule_index is None, fetch policy based on attributes
381 :param:
382 name : Name of the export_policy
383 :return: Details about the export_policy. None if not found.
384 :rtype: dict
385 """
386 if self.use_rest:
387 return self.get_export_policy_rule_rest(rule_index)
388 result = None
389 rule_iter = netapp_utils.zapi.NaElement('export-rule-get-iter')
390 query = self.set_query_parameters(rule_index)
391 rule_iter.translate_struct(query)
392 try:
393 result = self.server.invoke_successfully(rule_iter, True)
394 except netapp_utils.zapi.NaApiError as error:
395 self.module.fail_json(msg='Error getting export policy rule %s: %s'
396 % (self.parameters['name'], to_native(error)),
397 exception=traceback.format_exc())
398 if result is not None and result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
399 if rule_index is None:
400 return self.match_export_policy_rule_exactly(result.get_child_by_name('attributes-list').get_children(), query, is_rest=False)
401 return self.zapi_export_rule_info_to_dict(result.get_child_by_name('attributes-list').get_child_by_name('export-rule-info'))
402 return None
403
404 def zapi_export_rule_info_to_dict(self, rule_info):
405 current = {}
406 for item_key, zapi_key in self.na_helper.zapi_string_keys.items():
407 current[item_key] = rule_info.get_child_content(zapi_key)
408 if item_key == 'client_match' and current[item_key]:
409 current[item_key] = current[item_key].split(',')
410 for item_key, zapi_key in self.na_helper.zapi_bool_keys.items():
411 current[item_key] = self.na_helper.get_value_for_bool(from_zapi=True,
412 value=rule_info[zapi_key])
413 for item_key, zapi_key in self.na_helper.zapi_int_keys.items():
414 current[item_key] = self.na_helper.get_value_for_int(from_zapi=True,
415 value=rule_info[zapi_key])
416 for item_key, zapi_key in self.na_helper.zapi_list_keys.items():
417 parent, dummy = zapi_key
418 current[item_key] = self.na_helper.get_value_for_list(from_zapi=True,
419 zapi_parent=rule_info.get_child_by_name(parent))
420 return current
421
422 def set_export_policy_id(self):
423 """
424 Fetch export-policy id
425 :param:
426 name : Name of the export-policy
427
428 :return: Set self.policy_id
429 """
430 if self.policy_id is not None:
431 return
432 if self.use_rest:
433 return self.set_export_policy_id_rest()
434 export_policy_iter = netapp_utils.zapi.NaElement('export-policy-get-iter')
435 attributes = {
436 'query': {
437 'export-policy-info': {
438 'policy-name': self.parameters['name'],
439 'vserver': self.parameters['vserver']
440 }
441 }
442 }
443
444 export_policy_iter.translate_struct(attributes)
445 try:
446 result = self.server.invoke_successfully(export_policy_iter, True)
447 except netapp_utils.zapi.NaApiError as error:
448 self.module.fail_json(msg='Error getting export policy %s: %s'
449 % (self.parameters['name'], to_native(error)),
450 exception=traceback.format_exc())
451
452 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) == 1:
453 self.policy_id = self.na_helper.safe_get(result, ['attributes-list', 'export-policy-info', 'policy-id'])
454 if self.policy_id is None:
455 self.module.fail_json(msg='Error getting export policy id for %s: got: %s.'
456 % (self.parameters['name'], result.to_string()))
457
458 def add_parameters_for_create_or_modify(self, na_element_object, params):
459 """
460 Add children node for create or modify NaElement object
461 :param na_element_object: modify or create NaElement object
462 :param values: dictionary of cron values to be added
463 :return: None
464 """
465 for key, value in params.items():
466 if key in self.na_helper.zapi_string_keys:
467 zapi_key = self.na_helper.zapi_string_keys.get(key)
468 # convert client_match list to comma-separated string
469 if value and key == 'client_match':
470 value = self.list_to_string(value)
471 elif key in self.na_helper.zapi_list_keys:
472 parent_key, child_key = self.na_helper.zapi_list_keys.get(key)
473 value = self.na_helper.get_value_for_list(from_zapi=False, zapi_parent=parent_key, zapi_child=child_key, data=value)
474 elif key in self.na_helper.zapi_int_keys:
475 zapi_key = self.na_helper.zapi_int_keys.get(key)
476 value = self.na_helper.get_value_for_int(from_zapi=False, value=value)
477 elif key in self.na_helper.zapi_bool_keys:
478 zapi_key = self.na_helper.zapi_bool_keys.get(key)
479 value = self.na_helper.get_value_for_bool(from_zapi=False, value=value)
480 else:
481 # ignore options that are not relevant
482 value = None
483
484 if value is not None:
485 if key in self.na_helper.zapi_list_keys:
486 na_element_object.add_child_elem(value)
487 else:
488 na_element_object[zapi_key] = value
489
490 def create_export_policy_rule(self):
491 """
492 create rule for the export policy.
493 """
494 if self.use_rest:
495 return self.create_export_policy_rule_rest()
496 export_rule_create = netapp_utils.zapi.NaElement('export-rule-create')
497 self.add_parameters_for_create_or_modify(export_rule_create, self.parameters)
498 try:
499 self.server.invoke_successfully(export_rule_create, enable_tunneling=True)
500 except netapp_utils.zapi.NaApiError as error:
501 self.module.fail_json(msg='Error creating export policy rule %s: %s'
502 % (self.parameters['name'], to_native(error)), exception=traceback.format_exc())
503
504 def create_export_policy(self):
505 """
506 Creates an export policy
507 """
508 if self.use_rest:
509 return self.create_export_policy_rest()
510 export_policy_create = netapp_utils.zapi.NaElement.create_node_with_children(
511 'export-policy-create', **{'policy-name': self.parameters['name']})
512 try:
513 self.server.invoke_successfully(export_policy_create,
514 enable_tunneling=True)
515 except netapp_utils.zapi.NaApiError as error:
516 self.module.fail_json(msg='Error creating export policy %s: %s'
517 % (self.parameters['name'], to_native(error)),
518 exception=traceback.format_exc())
519
520 def delete_export_policy_rule(self, rule_index):
521 """
522 delete rule for the export policy.
523 """
524 if self.use_rest:
525 return self.delete_export_policy_rule_rest(rule_index)
526 export_rule_delete = netapp_utils.zapi.NaElement.create_node_with_children(
527 'export-rule-destroy', **{'policy-name': self.parameters['name'],
528 'rule-index': str(rule_index)})
529
530 try:
531 self.server.invoke_successfully(export_rule_delete,
532 enable_tunneling=True)
533 except netapp_utils.zapi.NaApiError as error:
534 self.module.fail_json(msg='Error deleting export policy rule %s: %s'
535 % (self.parameters['name'], to_native(error)),
536 exception=traceback.format_exc())
537
538 def modify_export_policy_rule(self, params, rule_index=None, rename=False):
539 '''
540 Modify an existing export policy rule
541 :param params: dict() of attributes with desired values
542 :return: None
543 '''
544 if self.use_rest:
545 return self.modify_export_policy_rule_rest(params, rule_index, rename)
546 params.pop('rule_index', None)
547 if params:
548 export_rule_modify = netapp_utils.zapi.NaElement.create_node_with_children(
549 'export-rule-modify', **{'policy-name': self.parameters['name'],
550 'rule-index': str(rule_index)})
551 self.add_parameters_for_create_or_modify(export_rule_modify, params)
552 try:
553 self.server.invoke_successfully(export_rule_modify, enable_tunneling=True)
554 except netapp_utils.zapi.NaApiError as error:
555 self.module.fail_json(msg='Error modifying export policy rule index %s: %s'
556 % (rule_index, to_native(error)),
557 exception=traceback.format_exc())
558 if rename:
559 export_rule_set_index = netapp_utils.zapi.NaElement.create_node_with_children(
560 'export-rule-set-index', **{'policy-name': self.parameters['name'],
561 'rule-index': str(self.parameters['from_rule_index']),
562 'new-rule-index': str(self.parameters['rule_index'])})
563 try:
564 self.server.invoke_successfully(export_rule_set_index, enable_tunneling=True)
565 except netapp_utils.zapi.NaApiError as error:
566 self.module.fail_json(msg='Error reindexing export policy rule index %s: %s'
567 % (self.parameters['from_rule_index'], to_native(error)),
568 exception=traceback.format_exc())
569
570 def set_export_policy_id_rest(self):
571 if self.policy_id is not None:
572 return
573 options = {'fields': 'name,id',
574 'svm.name': self.parameters['vserver'],
575 'name': self.parameters['name']}
576 api = 'protocols/nfs/export-policies'
577 record, error = rest_generic.get_one_record(self.rest_api, api, options)
578 if error:
579 self.module.fail_json(msg="Error on fetching export policy: %s" % error)
580 if record:
581 self.policy_id = record['id']
582
583 def get_export_policy_rule_exact_match(self, query):
584 """ fetch rules based on attributes
585 REST queries only allow for one value at a time in a list, so:
586 1. get a short list of matches using a simple query
587 2. then look for an exact match
588 """
589 api = 'protocols/nfs/export-policies/%s/rules' % self.policy_id
590 query.update(self.create_query(self.parameters))
591 records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query)
592 if error:
593 # If no rule matches the query, return None
594 if "entry doesn't exist" in error:
595 return None
596 self.module.fail_json(msg="Error on fetching export policy rules: %s" % error)
597 return self.match_export_policy_rule_exactly(records, query, is_rest=True)
598
599 def match_export_policy_rule_exactly(self, records, query, is_rest):
600 if not records:
601 return None
602 founds = []
603 for record in records:
604 record = self.filter_get_results(record) if is_rest else self.zapi_export_rule_info_to_dict(record)
605 modify = self.na_helper.get_modified_attributes(record, self.parameters)
606 modify.pop('rule_index', None)
607 if not modify:
608 founds.append(record)
609 if founds and len(founds) > 1 and not (self.parameters['state'] == 'absent' and self.parameters['force_delete_on_first_match']):
610 self.module.fail_json(msg='Error multiple records exist for query: %s. Specify index to modify or delete a rule. Found: %s'
611 % (query, founds))
612 return founds[0] if founds else None
613
614 def get_export_policy_rule_rest(self, rule_index):
615 self.set_export_policy_id_rest()
616 if not self.policy_id:
617 return None
618 query = {'fields': 'anonymous_user,clients,index,protocols,ro_rule,rw_rule,superuser'}
619 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
620 query['fields'] += ',ntfs_unix_security,allow_suid,chown_mode,allow_device_creation'
621 if rule_index is None:
622 return self.get_export_policy_rule_exact_match(query)
623 api = 'protocols/nfs/export-policies/%s/rules/%s' % (self.policy_id, rule_index)
624 record, error = rest_generic.get_one_record(self.rest_api, api, query)
625 if error:
626 # If rule index passed in doesn't exist, return None
627 if "entry doesn't exist" in error:
628 return None
629 self.module.fail_json(msg="Error on fetching export policy rule: %s" % error)
630 return self.filter_get_results(record) if record else None
631
632 def filter_get_results(self, record):
633 record['rule_index'] = record.pop('index')
634 record['anonymous_user_id'] = record.pop('anonymous_user')
635 record['protocol'] = record.pop('protocols')
636 record['super_user_security'] = record.pop('superuser')
637 record['client_match'] = [each['match'] for each in record['clients']]
638 record.pop('clients')
639 return record
640
641 def create_export_policy_rest(self):
642 body = {'name': self.parameters['name'], 'svm.name': self.parameters['vserver']}
643 api = 'protocols/nfs/export-policies'
644 dummy, error = rest_generic.post_async(self.rest_api, api, body)
645 if error is not None:
646 self.module.fail_json(msg="Error on creating export policy: %s" % error)
647
648 def create_export_policy_rule_rest(self):
649 api = 'protocols/nfs/export-policies/%s/rules' % self.policy_id
650 query = {'return_records': 'true'}
651 response, error = rest_generic.post_async(self.rest_api, api, self.create_body(self.parameters), query)
652 if error:
653 self.module.fail_json(msg="Error on creating export policy rule: %s" % error)
654 # force a 'rename' to set the index
655 rule_index = None
656 if response and response.get('num_records') == 1:
657 rule_index = self.na_helper.safe_get(response, ['records', 0, 'index'])
658 if rule_index is None:
659 self.module.fail_json(msg="Error on creating export policy rule, returned response is invalid: %s" % response)
660 if self.parameters.get('rule_index'):
661 self.modify_export_policy_rule_rest({}, rule_index, True)
662
663 def client_match_format(self, client_match):
664 return [{'match': each} for each in client_match]
665
666 def delete_export_policy_rule_rest(self, rule_index):
667 api = 'protocols/nfs/export-policies/%s/rules' % self.policy_id
668 dummy, error = rest_generic. delete_async(self.rest_api, api, rule_index)
669 if error:
670 self.module.fail_json(msg="Error on deleting export policy Rule: %s" % error)
671
672 def create_body(self, params, rename=False):
673 body = self.create_body_or_query_common(params)
674 # lists
675 if params.get('rule_index') is not None and not rename:
676 body['index'] = self.parameters['rule_index']
677 if params.get('protocol'):
678 body['protocols'] = self.parameters['protocol']
679 if params.get('super_user_security'):
680 body['superuser'] = self.parameters['super_user_security']
681 if params.get('client_match'):
682 body['clients'] = self.client_match_format(self.parameters['client_match'])
683 if params.get('ro_rule'):
684 body['ro_rule'] = self.parameters['ro_rule']
685 if params.get('rw_rule'):
686 body['rw_rule'] = self.parameters['rw_rule']
687 return body
688
689 def create_query(self, params):
690 query = self.create_body_or_query_common(params)
691 # for list, do an initial query based on first element
692 if params.get('protocol'):
693 query['protocols'] = self.parameters['protocol'][0]
694 if params.get('super_user_security'):
695 query['superuser'] = self.parameters['super_user_security'][0]
696 if params.get('client_match'):
697 query['clients.match'] = self.parameters['client_match'][0]
698 if params.get('ro_rule'):
699 query['ro_rule'] = self.parameters['ro_rule'][0]
700 if params.get('rw_rule'):
701 query['rw_rule'] = self.parameters['rw_rule'][0]
702 return query
703
704 def create_body_or_query_common(self, params):
705 result = {}
706 if params.get('anonymous_user_id') is not None:
707 result['anonymous_user'] = self.parameters['anonymous_user_id']
708 if params.get('ntfs_unix_security') is not None:
709 result['ntfs_unix_security'] = self.parameters['ntfs_unix_security']
710 if params.get('allow_suid') is not None:
711 result['allow_suid'] = self.parameters['allow_suid']
712 if params.get('chown_mode') is not None:
713 result['chown_mode'] = self.parameters['chown_mode']
714 if params.get('allow_device_creation') is not None:
715 result['allow_device_creation'] = self.parameters['allow_device_creation']
716 return result
717
718 def modify_export_policy_rule_rest(self, params, rule_index, rename=False):
719 api = 'protocols/nfs/export-policies/%s/rules' % self.policy_id
720 query = {'new_index': self.parameters['rule_index']} if rename else None
721 dummy, error = rest_generic.patch_async(self.rest_api, api, rule_index, self.create_body(params, rename), query)
722
723 if error:
724 self.module.fail_json(msg="Error on modifying export policy Rule: %s" % error)
725
726 def apply(self):
727 ''' Apply required action from the play'''
728 current = self.get_export_policy_rule(self.parameters.get('rule_index'))
729 cd_action, rename, modify = None, None, None
730 cd_action = self.na_helper.get_cd_action(current, self.parameters)
731 # if rule_index is not None, see if we need to re-index an existing rule
732 # the existing rule may be indexed by from_rule_index or we can match the attributes
733 if cd_action == 'create' and self.parameters.get('rule_index') and self.parameters.get('from_rule_index') is not None:
734 from_current = self.get_export_policy_rule(self.parameters.get('from_rule_index'))
735 rename = self.na_helper.is_rename_action(from_current, current)
736 if rename is None and self.parameters.get('from_rule_index') is not None:
737 self.module.fail_json(
738 msg="Error reindexing: export policy rule %s does not exist." % self.parameters['from_rule_index'])
739 if rename:
740 current = from_current
741 cd_action = None
742 self.parameters['from_rule_index'] = current['rule_index']
743
744 if cd_action is None and self.parameters['state'] == 'present':
745 modify = self.na_helper.get_modified_attributes(current, self.parameters)
746
747 if self.na_helper.changed:
748 self.set_export_policy_id()
749 if cd_action == 'create':
750 self.fail_on_missing_required_params('creating')
751
752 if self.na_helper.changed and not self.module.check_mode:
753 # create export policy (if policy doesn't exist) only when changed=True
754 if rename:
755 self.modify_export_policy_rule(modify, self.parameters['from_rule_index'], rename=True)
756 elif cd_action == 'create':
757 if not self.policy_id:
758 self.create_export_policy()
759 self.set_export_policy_id()
760 self.create_export_policy_rule()
761 elif cd_action == 'delete':
762 self.delete_export_policy_rule(current['rule_index'])
763 elif modify:
764 self.modify_export_policy_rule(modify, current['rule_index'])
765
766 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
767 self.module.exit_json(**result)
768
769
770 def main():
771 ''' Create object and call apply '''
772 rule_obj = NetAppontapExportRule()
773 rule_obj.apply()
774
775
776 if __name__ == '__main__':
777 main()