1#!/usr/bin/python
2
3# (c) 2018, NetApp, Inc
4# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6from __future__ import absolute_import, division, print_function
7__metaclass__ = type
8
9ANSIBLE_METADATA = {'metadata_version': '1.1',
10                    'status': ['preview'],
11                    'supported_by': 'certified'}
12
13
14DOCUMENTATION = '''
15module: na_ontap_export_policy
16short_description: NetApp ONTAP manage export-policy
17extends_documentation_fragment:
18    - netapp.na_ontap
19version_added: '2.6'
20author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
21description:
22- Create or destroy or rename export-policies on ONTAP
23options:
24  state:
25    description:
26    - Whether the specified export policy should exist or not.
27    choices: ['present', 'absent']
28    default: present
29  name:
30    description:
31    - The name of the export-policy to manage.
32    required: true
33  from_name:
34    description:
35    - The name of the export-policy to be renamed.
36    version_added: '2.7'
37  vserver:
38    description:
39    - Name of the vserver to use.
40'''
41
42EXAMPLES = """
43    - name: Create Export Policy
44      na_ontap_export_policy:
45        state: present
46        name: ansiblePolicyName
47        vserver: vs_hack
48        hostname: "{{ netapp_hostname }}"
49        username: "{{ netapp_username }}"
50        password: "{{ netapp_password }}"
51    - name: Rename Export Policy
52      na_ontap_export_policy:
53        action: present
54        from_name: ansiblePolicyName
55        vserver: vs_hack
56        name: newPolicyName
57        hostname: "{{ netapp_hostname }}"
58        username: "{{ netapp_username }}"
59        password: "{{ netapp_password }}"
60    - name: Delete Export Policy
61      na_ontap_export_policy:
62        state: absent
63        name: ansiblePolicyName
64        vserver: vs_hack
65        hostname: "{{ netapp_hostname }}"
66        username: "{{ netapp_username }}"
67        password: "{{ netapp_password }}"
68"""
69
70RETURN = """
71"""
72
73import traceback
74from ansible.module_utils.basic import AnsibleModule
75from ansible.module_utils._text import to_native
76import ansible.module_utils.netapp as netapp_utils
77
78HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
79
80
81class NetAppONTAPExportPolicy(object):
82    """
83    Class with export policy methods
84    """
85
86    def __init__(self):
87
88        self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
89        self.argument_spec.update(dict(
90            state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
91            name=dict(required=True, type='str'),
92            from_name=dict(required=False, type='str', default=None),
93            vserver=dict(required=False, type='str')
94        ))
95        self.module = AnsibleModule(
96            argument_spec=self.argument_spec,
97            required_if=[
98                ('state', 'present', ['vserver'])
99            ],
100            supports_check_mode=True
101        )
102        parameters = self.module.params
103        # set up state variables
104        self.state = parameters['state']
105        self.name = parameters['name']
106        self.from_name = parameters['from_name']
107        self.vserver = parameters['vserver']
108
109        if HAS_NETAPP_LIB is False:
110            self.module.fail_json(msg="the python NetApp-Lib module is required")
111        else:
112            self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.vserver)
113
114    def get_export_policy(self, name=None):
115        """
116        Return details about the export-policy
117        :param:
118            name : Name of the export-policy
119        :return: Details about the export-policy. None if not found.
120        :rtype: dict
121        """
122        if name is None:
123            name = self.name
124        export_policy_iter = netapp_utils.zapi.NaElement('export-policy-get-iter')
125        export_policy_info = netapp_utils.zapi.NaElement('export-policy-info')
126        export_policy_info.add_new_child('policy-name', name)
127        query = netapp_utils.zapi.NaElement('query')
128        query.add_child_elem(export_policy_info)
129        export_policy_iter.add_child_elem(query)
130        result = self.server.invoke_successfully(export_policy_iter, True)
131        return_value = None
132        # check if query returns the expected export-policy
133        if result.get_child_by_name('num-records') and \
134                int(result.get_child_content('num-records')) == 1:
135
136            export_policy = result.get_child_by_name('attributes-list').get_child_by_name('export-policy-info').get_child_by_name('policy-name')
137            return_value = {
138                'policy-name': export_policy
139            }
140        return return_value
141
142    def create_export_policy(self):
143        """
144        Creates an export policy
145        """
146        export_policy_create = netapp_utils.zapi.NaElement.create_node_with_children(
147            'export-policy-create', **{'policy-name': self.name})
148        try:
149            self.server.invoke_successfully(export_policy_create,
150                                            enable_tunneling=True)
151        except netapp_utils.zapi.NaApiError as error:
152            self.module.fail_json(msg='Error creating export-policy %s: %s'
153                                  % (self.name, to_native(error)),
154                                  exception=traceback.format_exc())
155
156    def delete_export_policy(self):
157        """
158        Delete export-policy
159        """
160        export_policy_delete = netapp_utils.zapi.NaElement.create_node_with_children(
161            'export-policy-destroy', **{'policy-name': self.name, })
162        try:
163            self.server.invoke_successfully(export_policy_delete,
164                                            enable_tunneling=True)
165        except netapp_utils.zapi.NaApiError as error:
166            self.module.fail_json(msg='Error deleting export-policy %s: %s'
167                                  % (self.name,
168                                     to_native(error)), exception=traceback.format_exc())
169
170    def rename_export_policy(self):
171        """
172        Rename the export-policy.
173        """
174        export_policy_rename = netapp_utils.zapi.NaElement.create_node_with_children(
175            'export-policy-rename', **{'policy-name': self.from_name,
176                                       'new-policy-name': self.name})
177        try:
178            self.server.invoke_successfully(export_policy_rename,
179                                            enable_tunneling=True)
180        except netapp_utils.zapi.NaApiError as error:
181            self.module.fail_json(msg='Error renaming export-policy %s:%s'
182                                  % (self.name, to_native(error)),
183                                  exception=traceback.format_exc())
184
185    def apply(self):
186        """
187        Apply action to export-policy
188        """
189        changed = False
190        export_policy_exists = False
191        netapp_utils.ems_log_event("na_ontap_export_policy", self.server)
192        rename_flag = False
193        export_policy_details = self.get_export_policy()
194        if export_policy_details:
195            export_policy_exists = True
196            if self.state == 'absent':  # delete
197                changed = True
198        else:
199            if self.state == 'present':  # create or rename
200                if self.from_name is not None:
201                    if self.get_export_policy(self.from_name):
202                        changed = True
203                        rename_flag = True
204                    else:
205                        self.module.fail_json(msg='Error renaming export-policy %s: does not exists' % self.from_name)
206                else:  # create
207                    changed = True
208        if changed:
209            if self.module.check_mode:
210                pass
211            else:
212                if self.state == 'present':  # execute create or rename_export_policy
213                    if rename_flag:
214                        self.rename_export_policy()
215                    else:
216                        self.create_export_policy()
217                elif self.state == 'absent':  # execute delete
218                    self.delete_export_policy()
219        self.module.exit_json(changed=changed)
220
221
222def main():
223    """
224    Execute action
225    """
226    export_policy = NetAppONTAPExportPolicy()
227    export_policy.apply()
228
229
230if __name__ == '__main__':
231    main()
232