Debian Codegraph @

ansible_collections/purestorage/flasharray/plugins/modules/purefa_user.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2018, Simon Dodsley ([email protected])
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefa_user
20 version_added: '1.0.0'
21 short_description: Create, modify or delete FlashArray local user account
22 description:
23 - Create, modify or delete local users on a Pure Storage FlashArray.
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 state:
28 description:
29 - Create, delete or update local user account
30 default: present
31 type: str
32 choices: [ absent, present ]
33 name:
34 description:
35 - The name of the local user account
36 type: str
37 required: true
38 role:
39 description:
40 - Sets the local user's access level to the array
41 type: str
42 default: readonly
43 choices: [ readonly, ops_admin, storage_admin, array_admin ]
44 password:
45 description:
46 - Password for the local user.
47 type: str
48 old_password:
49 description:
50 - If changing an existing password, you must provide the old password for security
51 type: str
52 api:
53 description:
54 - Define whether to create an API token for this user
55 - Token can be exposed using the I(debug) module
56 type: bool
57 default: false
58 timeout:
59 description:
60 - The duration of API token validity.
61 - Valid values are weeks (w), days(d), hours(h), minutes(m) and seconds(s).
62 type: str
63 default: "0"
64 version_added: "1.34.0"
65 public_key:
66 description:
67 - Public key for SSH access.
68 - To remove existing key use an empty string
69 type: str
70 version_added: "1.34.0"
71 ad_user:
72 description:
73 - Whether the user is in the AD system
74 - Not required for local users
75 type: bool
76 default: false
77 version_added: "1.37.0"
78 extends_documentation_fragment:
79 - purestorage.flasharray.purestorage.fa
80 """
81
82 EXAMPLES = r"""
83 - name: Create new user ansible with API token
84 purestorage.flasharray.purefa_user:
85 name: ansible
86 password: apassword
87 role: storage_admin
88 api: true
89 timeout: 2d
90 fa_url: 10.10.10.2
91 api_token: e31060a7-21fc-e277-6240-25983c6c4592
92 register: result
93
94 debug:
95 msg: "API Token: {{ result['user_info']['user_api'] }}"
96
97 - name: Overwrite/add SSH public key for existing user
98 purestorage.flasharray.purefa_user:
99 name: ansible
100 role: array_admin
101 public_key: "{{lookup('file', 'id_rsa.pub') }}"
102 fa_url: 10.10.10.2
103 api_token: e31060a7-21fc-e277-6240-25983c6c4592
104
105 - name: Remove existing SSH public key from user
106 purestorage.flasharray.purefa_user:
107 name: ansible
108 role: array_admin
109 public_key: ""
110 fa_url: 10.10.10.2
111 api_token: e31060a7-21fc-e277-6240-25983c6c4592
112
113 - name: Change role type for existing user
114 purestorage.flasharray.purefa_user:
115 name: ansible
116 role: array_admin
117 fa_url: 10.10.10.2
118 api_token: e31060a7-21fc-e277-6240-25983c6c4592
119
120 - name: Change password type for existing user (NOT IDEMPOTENT)
121 purestorage.flasharray.purefa_user:
122 name: ansible
123 password: anewpassword
124 old_password: apassword
125 fa_url: 10.10.10.2
126 api_token: e31060a7-21fc-e277-6240-25983c6c4592
127
128 - name: Create an API token (TTL of 2 days) and assign a public key to an AD user
129 purestorage.flasharray.purefa_user:
130 name: ansible-ad
131 ad_user: true
132 public_key: "{{lookup('file', 'id_rsa.pub') }}"
133 api: true
134 timeout: 2d
135 fa_url: 10.10.10.2
136 api_token: e31060a7-21fc-e277-6240-25983c6c4592
137
138 - name: Change API token and token timeout for existing user
139 purestorage.flasharray.purefa_user:
140 name: ansible
141 api: true
142 role: array_admin
143 timeout: 1d
144 fa_url: 10.10.10.2
145 api_token: e31060a7-21fc-e277-6240-25983c6c4592
146 register: result
147
148 debug:
149 msg: "API Token: {{ result['user_info']['user_api'] }}"
150 """
151
152 RETURN = r"""
153 """
154
155
156 HAS_PURESTORAGE = True
157 try:
158 from pypureclient.flasharray import AdminPost, AdminPatch, AdminRole
159 except ImportError:
160 HAS_PURESTORAGE = False
161
162 import re
163 from ansible.module_utils.basic import AnsibleModule
164 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
165 get_array,
166 purefa_argument_spec,
167 )
168 from ansible_collections.purestorage.flasharray.plugins.module_utils.common import (
169 convert_time_to_millisecs,
170 )
171
172
173 def get_user(module, array):
174 """Return Local User Account or None"""
175 res = array.get_admins(names=[module.params["name"]])
176 if res.status_code != 200:
177 return None
178 return list(res.items)[0]
179
180
181 def create_local_user(module, array, user):
182 """Create or Update Local User Account"""
183 changed = key_changed = api_changed = role_changed = passwd_changed = False
184 role = module.params["role"]
185 api_token = "No API token created"
186 if not user:
187 changed = True
188 if not module.check_mode:
189 res = array.post_admins(
190 names=[module.params["name"]],
191 admin=AdminPost(
192 role=AdminRole(name=role),
193 password=module.params["password"],
194 ),
195 )
196 if res.status_code != 200:
197 module.fail_json(
198 msg="Failed to create user {0}. Error: {1}".format(
199 module.params["name"], res.errors[0].message
200 )
201 )
202 if module.params["api"]:
203 ttl = convert_time_to_millisecs(module.params["timeout"])
204 res = array.post_admins_api_tokens(
205 names=[module.params["name"]], timeout=ttl
206 )
207 if res.status_code != 200:
208 module.fail_json(
209 msg="Failed to create API token. Error: {0}".format(
210 res.errors[0].message
211 )
212 )
213 api_token = list(res.items)[0].api_token.token
214 if module.params["public_key"]:
215 res = array.patch_admins(
216 names=[module.params["name"]],
217 admin=AdminPatch(public_key=module.params["public_key"]),
218 )
219 if res.status_code != 200:
220 module.fail_json(
221 msg="Failed to add SSH key. Error: {0}".format(
222 res.errors[0].message
223 )
224 )
225 else:
226 if module.params["password"] and not module.params["old_password"]:
227 module.exit_json(changed=changed)
228 if (
229 module.params["password"]
230 and module.params["old_password"]
231 and module.params["password"] != module.params["old_password"]
232 ):
233 passwd_changed = True
234 if not module.check_mode:
235 res = array.patch_admins(
236 names=[module.params["name"]],
237 admin=AdminPatch(
238 password=module.params["password"],
239 old_password=module.params["old_password"],
240 ),
241 )
242 if res.status_code != 200:
243 module.fail_json(
244 msg="Local User {0} password reset failed. Error: {1}"
245 "Check old password.".format(
246 module.params["name"], res.errors[0].message
247 )
248 )
249 if module.params["api"]:
250 api_changed = True
251 ttl = convert_time_to_millisecs(module.params["timeout"])
252 res = array.delete_admins_api_tokens(names=[module.params["name"]])
253 if res.status_code != 200:
254 module.fail_json(
255 msg="Failed to delete original API token. Error: {0}".format(
256 res.errors[0].message
257 )
258 )
259 res = array.post_admins_api_tokens(
260 names=[module.params["name"]], timeout=ttl
261 )
262 if res.status_code != 200:
263 module.fail_json(
264 msg="Failed to recreate API token. Error: {0}".format(
265 res.errors[0].message
266 )
267 )
268 api_token = list(res.items)[0].api_token.token
269 if module.params["role"] and module.params["role"] != getattr(
270 user.role, "name", None
271 ):
272 if module.params["name"] != "pureuser":
273 role_changed = True
274 if not module.check_mode:
275 res = array.patch_admins(
276 names=[module.params["name"]],
277 admin=AdminPatch(role=AdminRole(name=module.params["role"])),
278 )
279 if res.status_code != 200:
280 module.fail_json(
281 msg="Local User {0} role changed failed. Error: {1}".format(
282 module.params["name"], res.errors[0].message
283 )
284 )
285 else:
286 module.warn("Role for 'pureuser' cannot be modified.")
287 if module.params["public_key"] is not None and module.params[
288 "public_key"
289 ] != getattr(user, "public_key", ""):
290 key_changed = True
291 res = array.patch_admins(
292 names=[module.params["name"]],
293 admin=AdminPatch(public_key=module.params["public_key"]),
294 )
295 if res.status_code != 200:
296 module.fail_json(
297 msg="Failed to change SSH key. Error: {0}".format(
298 res.errors[0].message
299 )
300 )
301 changed = bool(passwd_changed or role_changed or api_changed or key_changed)
302 module.exit_json(changed=changed, user_info=api_token)
303
304
305 def update_ad_user(module, array, user):
306 """Update AD user API token and/or SSH key"""
307 api_token = "No API token created"
308 api_changed = ssh_changed = False
309 if module.params["api"]:
310 if user:
311 api_changed = True
312 ttl = convert_time_to_millisecs(module.params["timeout"])
313 res = array.delete_admins_api_tokens(names=[module.params["name"]])
314 if res.status_code != 200:
315 module.fail_json(
316 msg="Failed to delete original API token. Error: {0}".format(
317 res.errors[0].message
318 )
319 )
320 res = array.post_admins_api_tokens(
321 names=[module.params["name"]], timeout=ttl
322 )
323 if res.status_code != 200:
324 module.fail_json(
325 msg="Failed to recreate API token. Error: {0}".format(
326 res.errors[0].message
327 )
328 )
329 api_token = list(res.items)[0].api_token.token
330 else:
331 api_changed = True
332 ttl = convert_time_to_millisecs(module.params["timeout"])
333 res = array.post_admins_api_tokens(
334 names=[module.params["name"]], timeout=ttl
335 )
336 if res.status_code != 200:
337 module.fail_json(
338 msg="Failed to create API token. Error: {0}".format(
339 res.errors[0].message
340 )
341 )
342 api_token = list(res.items)[0].api_token.token
343 if module.params["public_key"]:
344 ssh_changed = True
345 res = array.patch_admins(
346 names=[module.params["name"]],
347 admin=AdminPatch(public_key=module.params["public_key"]),
348 )
349 if res.status_code != 200:
350 module.fail_json(
351 msg="Failed to add SSH key. Error: {0}".format(res.errors[0].message)
352 )
353 changed = bool(api_changed or ssh_changed)
354 module.exit_json(changed=changed, user_info=api_token)
355
356
357 def delete_local_user(module, array):
358 """Delete Local User Account"""
359 changed = True
360 if not module.check_mode:
361 res = array.delete_admins(names=[module.params["name"]])
362 if res.status_code != 200:
363 module.fail_json(
364 msg="User Account {0} deletion failed. Error: {1}".format(
365 module.params["name"], res.errors[0].message
366 )
367 )
368 module.exit_json(changed=changed)
369
370
371 def delete_ad_user(module, array, user):
372 """Delete AD User Account references"""
373 changed = False
374 if not module.check_mode:
375 if user:
376 changed = True
377 res = array.delete_admins_api_tokens(names=[module.params["name"]])
378 if res.status_code != 200:
379 module.fail_json(
380 msg="AD Account {0} API token deletion failed. Error: {1}".format(
381 module.params["name"], res.errors[0].message
382 )
383 )
384 if hasattr(user, "public_key"):
385 res = array.patch_admins(
386 names=[module.params["name"]],
387 admin=AdminPatch(public_key=""),
388 )
389 if res.status_code != 200:
390 module.fail_json(
391 msg="AD Account {0} public key deletion failed. Error: {1}".format(
392 module.params["name"], res.errors[0].message
393 )
394 )
395 module.exit_json(changed=changed)
396
397
398 def main():
399 argument_spec = purefa_argument_spec()
400 argument_spec.update(
401 dict(
402 name=dict(required=True, type="str"),
403 role=dict(
404 type="str",
405 choices=["readonly", "ops_admin", "storage_admin", "array_admin"],
406 default="readonly",
407 ),
408 state=dict(type="str", default="present", choices=["absent", "present"]),
409 password=dict(type="str", no_log=True),
410 old_password=dict(type="str", no_log=True),
411 api=dict(type="bool", default=False),
412 timeout=dict(type="str", default="0"),
413 public_key=dict(type="str", no_log=True),
414 ad_user=dict(type="bool", default=False),
415 )
416 )
417
418 module = AnsibleModule(argument_spec, supports_check_mode=True)
419
420 if not HAS_PURESTORAGE:
421 module.fail_json(msg="py-pure-client sdk is required for this module")
422
423 state = module.params["state"]
424 array = get_array(module)
425 pattern = re.compile("^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$")
426 if not pattern.match(module.params["name"]):
427 module.fail_json(
428 msg="name must contain a minimum of 1 and a maximum of 32 characters "
429 "(alphanumeric or `-`). All letters must be lowercase."
430 )
431 user = get_user(module, array)
432 local_user = getattr(user, "is_local", False)
433 if state == "present" and not local_user and module.params["ad_user"]:
434 update_ad_user(module, array, user)
435 if state == "absent" and local_user:
436 delete_local_user(module, array)
437 if state == "absent" and not local_user:
438 delete_ad_user(module, array, user)
439 elif state == "present" and not module.params["ad_user"]:
440 create_local_user(module, array, user)
441 else:
442 module.exit_json(changed=False)
443
444
445 if __name__ == "__main__":
446 main()