summaryrefslogtreecommitdiffstats
path: root/ansible_collections/netapp/ontap/plugins/modules/na_ontap_ldap.py
blob: d75d17ee9fcca5abfd28986ba053d9ef33f63a56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/python
'''
(c) 2018-2022, NetApp, Inc
GNU General Public License v3.0+
(see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
'''

from __future__ import absolute_import, division, print_function
__metaclass__ = type

DOCUMENTATION = '''

module: na_ontap_ldap

short_description: NetApp ONTAP LDAP
extends_documentation_fragment:
    - netapp.ontap.netapp.na_ontap_zapi
version_added: 2.9.0
author: Milan Zink (@zeten30) <zeten30@gmail.com>/<mzink@redhat.com>

description:
- Create, modify or delete LDAP on NetApp ONTAP SVM/vserver

options:

  state:
    description:
      - Whether the LDAP is present or not.
    choices: ['present', 'absent']
    default: 'present'
    type: str

  vserver:
    description:
      - vserver/svm configured to use LDAP
    required: true
    type: str

  name:
    description:
      - The name of LDAP client configuration
    required: true
    type: str

  skip_config_validation:
    description:
      - Skip LDAP validation
    choices: ['true', 'false']
    type: str
'''

EXAMPLES = '''

    - name: Enable LDAP on SVM
      netapp.ontap.na_ontap_ldap:
        state:         present
        name:          'example_ldap'
        vserver:       'vserver1'
        hostname:      "{{ netapp_hostname }}"
        username:      "{{ netapp_username }}"
        password:      "{{ netapp_password }}"

'''

RETURN = '''
'''

import traceback
import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule


class NetAppOntapLDAP:
    '''
    LDAP Client definition class
    '''

    def __init__(self):
        self.argument_spec = netapp_utils.na_ontap_zapi_only_spec()
        self.argument_spec.update(dict(
            name=dict(required=True, type='str'),
            skip_config_validation=dict(required=False, default=None, choices=['true', 'false']),
            state=dict(required=False, choices=['present', 'absent'], default='present'),
            vserver=dict(required=True, type='str')
        ))

        self.module = AnsibleModule(
            argument_spec=self.argument_spec,
            supports_check_mode=True
        )
        self.na_helper = NetAppModule()
        self.parameters = self.na_helper.set_parameters(self.module.params)
        msg = 'Error: na_ontap_ldap only supports ZAPI.netapp.ontap.na_ontap_ldap_client should be used instead.'
        self.na_helper.fall_back_to_zapi(self.module, msg, self.parameters)

        if not netapp_utils.has_netapp_lib():
            self.module.fail_json(msg="the python NetApp-Lib module is required")
        self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])

    def get_ldap(self, client_config_name=None):
        '''
        Checks if LDAP config exists.

        :return:
            ldap config object if found
            None if not found
        :rtype: object/None
        '''
        # Make query
        config_info = netapp_utils.zapi.NaElement('ldap-config-get-iter')

        if client_config_name is None:
            client_config_name = self.parameters['name']

        query_details = netapp_utils.zapi.NaElement.create_node_with_children('ldap-config', **{'client-config': client_config_name})

        query = netapp_utils.zapi.NaElement('query')
        query.add_child_elem(query_details)
        config_info.add_child_elem(query)

        result = self.server.invoke_successfully(config_info, enable_tunneling=True)

        # Get LDAP configuration details
        config_details = None
        if (result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1):
            attributes_list = result.get_child_by_name('attributes-list')
            config_info = attributes_list.get_child_by_name('ldap-config')

            # Define config details structure
            config_details = {'client_config': config_info.get_child_content('client-config'),
                              'skip_config_validation': config_info.get_child_content('skip-config-validation'),
                              'vserver': config_info.get_child_content('vserver')}

        return config_details

    def create_ldap(self):
        '''
        Create LDAP configuration
        '''
        options = {
            'client-config': self.parameters['name'],
            'client-enabled': 'true'
        }

        if self.parameters.get('skip_config_validation') is not None:
            options['skip-config-validation'] = self.parameters['skip_config_validation']

        # Initialize NaElement
        ldap_create = netapp_utils.zapi.NaElement.create_node_with_children('ldap-config-create', **options)

        # Try to create LDAP configuration
        try:
            self.server.invoke_successfully(ldap_create, enable_tunneling=True)
        except netapp_utils.zapi.NaApiError as errcatch:
            self.module.fail_json(msg='Error creating LDAP configuration %s: %s' % (self.parameters['name'], to_native(errcatch)),
                                  exception=traceback.format_exc())

    def delete_ldap(self):
        '''
        Delete LDAP configuration
        '''
        ldap_client_delete = netapp_utils.zapi.NaElement.create_node_with_children('ldap-config-delete', **{})

        try:
            self.server.invoke_successfully(ldap_client_delete, enable_tunneling=True)
        except netapp_utils.zapi.NaApiError as errcatch:
            self.module.fail_json(msg='Error deleting LDAP configuration %s: %s' % (
                self.parameters['name'], to_native(errcatch)), exception=traceback.format_exc())

    def modify_ldap(self, modify):
        '''
        Modify LDAP
        :param modify: list of modify attributes
        '''
        ldap_modify = netapp_utils.zapi.NaElement('ldap-config-modify')
        ldap_modify.add_new_child('client-config', self.parameters['name'])

        for attribute in modify:
            if attribute == 'skip_config_validation':
                ldap_modify.add_new_child('skip-config-validation', self.parameters[attribute])

        # Try to modify LDAP
        try:
            self.server.invoke_successfully(ldap_modify, enable_tunneling=True)
        except netapp_utils.zapi.NaApiError as errcatch:
            self.module.fail_json(msg='Error modifying LDAP %s: %s' % (self.parameters['name'], to_native(errcatch)),
                                  exception=traceback.format_exc())

    def apply(self):
        '''Call create/modify/delete operations.'''
        current = self.get_ldap()
        cd_action = self.na_helper.get_cd_action(current, self.parameters)
        modify = self.na_helper.get_modified_attributes(current, self.parameters)

        if self.na_helper.changed:
            if self.module.check_mode:
                pass
            else:
                if cd_action == 'create':
                    self.create_ldap()
                elif cd_action == 'delete':
                    self.delete_ldap()
                elif modify:
                    self.modify_ldap(modify)
        result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
        self.module.exit_json(**result)


#
# MAIN
#
def main():
    '''ONTAP LDAP client configuration'''
    ldapclient = NetAppOntapLDAP()
    ldapclient.apply()


if __name__ == '__main__':
    main()