summaryrefslogtreecommitdiff
path: root/storage/netapp/netapp_e_auth.py
blob: 19bdb0bfea51316dd7610c776cca0739e61c555a (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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/python

# (c) 2016, NetApp, Inc
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = '''
---
module: netapp_e_auth
short_description: Sets or updates the password for a storage array.
description:
     - Sets or updates the password for a storage array.  When the password is updated on the storage array, it must be updated on the SANtricity Web Services proxy. Note, all storage arrays do not have a Monitor or RO role.
version_added: "2.2"
author: Kevin Hulquest (@hulquest)
options:
    validate_certs:
        required: false
        default: true
        description:
        - Should https certificates be validated?
    name:
      description:
        - The name of the storage array. Note that if more than one storage array with this name is detected, the task will fail and you'll have to use the ID instead.
      required: False
    ssid:
      description:
        - the identifier of the storage array in the Web Services Proxy.
      required: False
    set_admin:
      description:
        - Boolean value on whether to update the admin password. If set to false then the RO account is updated.
      default: False
    current_password:
      description:
        - The current admin password. This is not required if the password hasn't been set before.
      required: False
    new_password:
      description:
        - The password you would like to set. Cannot be more than 30 characters.
      required: True
    api_url:
      description:
        - The full API url.
        - "Example: http://ENDPOINT:8080/devmgr/v2"
        - This can optionally be set via an environment variable, API_URL
      required: False
    api_username:
      description:
        - The username used to authenticate against the API
        - This can optionally be set via an environment variable, API_USERNAME
      required: False
    api_password:
      description:
        - The password used to authenticate against the API
        - This can optionally be set via an environment variable, API_PASSWORD
      required: False
'''

EXAMPLES = '''
- name: Test module
  netapp_e_auth:
    name: trex
    current_password: OldPasswd
    new_password: NewPasswd
    set_admin: yes
    api_url: '{{ netapp_api_url }}'
    api_username: '{{ netapp_api_username }}'
    api_password: '{{ netapp_api_password }}'
'''

RETURN = '''
msg:
    description: Success message
    returned: success
    type: string
    sample: "Password Updated Successfully"
'''
import json

from ansible.module_utils.api import basic_auth_argument_spec
from ansible.module_utils.basic import AnsibleModule

from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.urls import open_url
from ansible.module_utils.six.moves.urllib.error import HTTPError


HEADERS = {
    "Content-Type": "application/json",
    "Accept": "application/json"
}


def request(url, data=None, headers=None, method='GET', use_proxy=True,
            force=False, last_mod_time=None, timeout=10, validate_certs=True,
            url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
    try:
        r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
                     force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
                     url_username=url_username, url_password=url_password, http_agent=http_agent,
                     force_basic_auth=force_basic_auth)
    except HTTPError:
        err = get_exception()
        r = err.fp

    try:
        raw_data = r.read()
        if raw_data:
            data = json.loads(raw_data)
        else:
            raw_data = None
    except:
        if ignore_errors:
            pass
        else:
            raise Exception(raw_data)

    resp_code = r.getcode()

    if resp_code >= 400 and not ignore_errors:
        raise Exception(resp_code, data)
    else:
        return resp_code, data


def get_ssid(module, name, api_url, user, pwd):
    count = 0
    all_systems = 'storage-systems'
    systems_url = api_url + all_systems
    rc, data = request(systems_url, headers=HEADERS, url_username=user, url_password=pwd)
    for system in data:
        if system['name'] == name:
            count += 1
            if count > 1:
                module.fail_json(
                    msg="You supplied a name for the Storage Array but more than 1 array was found with that name. " +
                        "Use the id instead")
            else:
                ssid = system['id']
        else:
            continue

    if count == 0:
        module.fail_json(msg="No storage array with the name %s was found" % name)

    else:
        return ssid


def get_pwd_status(module, ssid, api_url, user, pwd):
    pwd_status = "storage-systems/%s/passwords" % ssid
    url = api_url + pwd_status
    try:
        rc, data = request(url, headers=HEADERS, url_username=user, url_password=pwd)
        return data['readOnlyPasswordSet'], data['adminPasswordSet']
    except HTTPError:
        error = get_exception()
        module.fail_json(msg="There was an issue with connecting, please check that your "
                             "endpoint is properly defined and your credentials are correct: %s" % str(error))


def update_storage_system_pwd(module, ssid, pwd, api_url, api_usr, api_pwd):
    update_pwd = 'storage-systems/%s' % ssid
    url = api_url + update_pwd
    post_body = json.dumps(dict(storedPassword=pwd))
    try:
        rc, data = request(url, data=post_body, method='POST', headers=HEADERS, url_username=api_usr,
                           url_password=api_pwd)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to update system password. Id [%s].  Error [%s]" % (ssid, str(err)))
    return data


def set_password(module, ssid, api_url, user, pwd, current_password=None, new_password=None, set_admin=False):
    set_pass = "storage-systems/%s/passwords" % ssid
    url = api_url + set_pass

    if not current_password:
        current_password = ""

    post_body = json.dumps(
        dict(currentAdminPassword=current_password, adminPassword=set_admin, newPassword=new_password))

    try:
        rc, data = request(url, method='POST', data=post_body, headers=HEADERS, url_username=user, url_password=pwd,
                           ignore_errors=True)
    except:
        err = get_exception()
        module.fail_json(msg="Failed to set system password. Id [%s].  Error [%s]" % (ssid, str(err)))

    if rc == 422:
        post_body = json.dumps(dict(currentAdminPassword='', adminPassword=set_admin, newPassword=new_password))
        try:
            rc, data = request(url, method='POST', data=post_body, headers=HEADERS, url_username=user, url_password=pwd)
        except Exception:
            module.fail_json(msg="Wrong or no admin password supplied. Please update your playbook and try again")

    update_data = update_storage_system_pwd(module, ssid, new_password, api_url, user, pwd)

    if int(rc) == 204:
        return update_data
    else:
        module.fail_json(msg="%s:%s" % (rc, data))


def main():
    argument_spec = basic_auth_argument_spec()
    argument_spec.update(dict(
        name=dict(required=False, type='str'),
        ssid=dict(required=False, type='str'),
        current_password=dict(required=False, no_log=True),
        new_password=dict(required=True, no_log=True),
        set_admin=dict(required=True, type='bool'),
        api_url=dict(required=True),
        api_username=dict(required=False),
        api_password=dict(required=False, no_log=True)
    )
    )
    module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['name', 'ssid']],
                           required_one_of=[['name', 'ssid']])

    name = module.params['name']
    ssid = module.params['ssid']
    current_password = module.params['current_password']
    new_password = module.params['new_password']
    set_admin = module.params['set_admin']
    user = module.params['api_username']
    pwd = module.params['api_password']
    api_url = module.params['api_url']

    if not api_url.endswith('/'):
        api_url += '/'

    if name:
        ssid = get_ssid(module, name, api_url, user, pwd)

    ro_pwd, admin_pwd = get_pwd_status(module, ssid, api_url, user, pwd)

    if admin_pwd and not current_password:
        module.fail_json(
            msg="Admin account has a password set. " +
                "You must supply current_password in order to update the RO or Admin passwords")

    if len(new_password) > 30:
        module.fail_json(msg="Passwords must not be greater than 30 characters in length")

    success = set_password(module, ssid, api_url, user, pwd, current_password=current_password,
                           new_password=new_password,
                           set_admin=set_admin)

    module.exit_json(changed=True, msg="Password Updated Successfully", **success)


if __name__ == '__main__':
    main()