Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, 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_host
20 version_added: '1.0.0'
21 short_description: Manage hosts on Pure Storage FlashArrays
22 description:
23 - Create, delete or modify hosts on Pure Storage FlashArrays.
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 notes:
27 - If specifying C(lun) option ensure host support requested value
28 options:
29 name:
30 description:
31 - The name of the host.
32 - Note that hostnames are case-sensitive however FlashArray hostnames are unique
33 and ignore case - you cannot have I(hosta) and I(hostA)
34 - Multi-host support available from Purity//FA 6.0.0
35 B(***NOTE***) Manual deletion of individual hosts created
36 using multi-host will cause idempotency to fail
37 - Multi-host support only exists for host creation
38 type: str
39 required: true
40 aliases: [ host ]
41 protocol:
42 description:
43 - Defines the host connection protocol for volumes.
44 - DEPRECATED No longer a necessary parameter
45 type: str
46 choices: [ fc, iscsi, nvme, mixed ]
47 rename:
48 description:
49 - The name to rename to.
50 - Note that hostnames are case-sensitive however FlashArray hostnames are unique
51 and ignore case - you cannot have I(hosta) and I(hostA)
52 type: str
53 state:
54 description:
55 - Define whether the host should exist or not.
56 - When removing host all connected volumes will be disconnected.
57 type: str
58 default: present
59 choices: [ absent, present ]
60 wwns:
61 type: list
62 elements: str
63 description:
64 - List of wwns of the host.
65 iqn:
66 type: list
67 elements: str
68 description:
69 - List of IQNs of the host.
70 nqn:
71 type: list
72 elements: str
73 description:
74 - List of NQNs of the host. Note that NMVe hosts can only possess NQNs.
75 Multi-protocol is not allowed for these hosts.
76 volume:
77 type: str
78 description:
79 - Volume name to map to the host.
80 lun:
81 description:
82 - LUN ID to assign to volume for host. Must be unique.
83 - If not provided the ID will be automatically assigned.
84 - Range for LUN ID is 1 to 4095.
85 type: int
86 count:
87 description:
88 - Number of hosts to be created in a multiple host creation
89 - Only supported from Purity//FA v6.0.0 and higher
90 type: int
91 start:
92 description:
93 - Number at which to start the multiple host creation index
94 - Only supported from Purity//FA v6.0.0 and higher
95 type: int
96 default: 0
97 digits:
98 description:
99 - Number of digits to use for multiple host count. This
100 will pad the index number with zeros where necessary
101 - Only supported from Purity//FA v6.0.0 and higher
102 - Range is between 1 and 10
103 type: int
104 default: 1
105 suffix:
106 description:
107 - Suffix string, if required, for multiple host create
108 - Host names will be formed as I(<name>#<suffix>), where
109 I(#) is a placeholder for the host index
110 See associated descriptions
111 - Suffix string is optional
112 - Only supported from Purity//FA v6.0.0 and higher
113 type: str
114 personality:
115 type: str
116 description:
117 - Define which operating system the host is. Recommended for
118 ActiveCluster integration.
119 default: ''
120 choices: ['hpux', 'vms', 'aix', 'esxi', 'solaris', 'hitachi-vsp', 'oracle-vm-server', 'delete', '']
121 preferred_array:
122 type: list
123 elements: str
124 description:
125 - List of preferred arrays in an ActiveCluster environment.
126 - To remove existing preferred arrays from the host, specify I(delete).
127 target_user:
128 type: str
129 description:
130 - Sets the target user name for CHAP authentication
131 - Required with I(target_password)
132 - To clear the username/password pair use I(clear) as the password
133 target_password:
134 type: str
135 description:
136 - Sets the target password for CHAP authentication
137 - Password length between 12 and 255 characters
138 - To clear the username/password pair use I(clear) as the password
139 - SETTING A PASSWORD IS NON-IDEMPOTENT
140 host_user:
141 type: str
142 description:
143 - Sets the host user name for CHAP authentication
144 - Required with I(host_password)
145 - To clear the username/password pair use I(clear) as the password
146 host_password:
147 type: str
148 description:
149 - Sets the host password for CHAP authentication
150 - Password length between 12 and 255 characters
151 - To clear the username/password pair use I(clear) as the password
152 - SETTING A PASSWORD IS NON-IDEMPOTENT
153 vlan:
154 type: str
155 description:
156 - The VLAN ID that the host is associated with.
157 - If not set or set to I(any), the host can access any VLAN.
158 - If set to I(untagged), the host can only access untagged VLANs.
159 - If set to a number between 1 and 4094, the host can only access the specified VLAN with that number.
160 version_added: '1.16.0'
161 context:
162 description:
163 - Name of fleet member on which to perform the operation.
164 - This requires the array receiving the request is a member of a fleet
165 and the context name to be a member of the same fleet.
166 type: str
167 default: ""
168 version_added: '1.33.0'
169 move:
170 description:
171 - Move a host in and out of a local member realm(s) or local array
172 - Provide the name of realm(s) to move to
173 - To move to the local array, specify C(local)
174 - Host cannot have connected volume(s) for move operation
175 type: list
176 elements: str
177 version_added: '1.35.0'
178 modify_resource_access:
179 description:
180 - Describes how to modify a resource accesses of a resource when
181 that resource is moved.
182 - The none value indicates that no resource access should be modified.
183 - The create value is used when a resource is moving out of a realm into
184 the array and it needs to create a resource access of the moved
185 resource to the realm from which it is moving.
186 - The delete value is used when a resource that is moving from an array
187 into a realm already has a resource access into that realm.
188 type: str
189 choices: ["none", "create", "delete"]
190 default: none
191 version_added: '1.35.0'
192 extends_documentation_fragment:
193 - purestorage.flasharray.purestorage.fa
194 """
195
196 EXAMPLES = r"""
197 - name: Create new AIX host
198 purestorage.flasharray.purefa_host:
199 name: foo
200 personality: aix
201 fa_url: 10.10.10.2
202 api_token: e31060a7-21fc-e277-6240-25983c6c4592
203
204 - name: Create host bar in existing realm foo
205 purestorage.flasharray.purefa_host:
206 name: foo::bar
207 fa_url: 10.10.10.2
208 api_token: e31060a7-21fc-e277-6240-25983c6c4592
209
210 - name: Create 10 hosts with index starting at 10 but padded with 3 digits
211 purestorage.flasharray.purefa_host:
212 name: foo
213 personality: vms
214 suffix: bar
215 count: 10
216 start: 10
217 digits: 3
218 fa_url: 10.10.10.2
219 api_token: e31060a7-21fc-e277-6240-25983c6c4592
220 state: present
221
222 - name: Rename host foo to bar
223 purestorage.flasharray.purefa_host:
224 name: foo
225 rename: bar
226 fa_url: 10.10.10.2
227 api_token: e31060a7-21fc-e277-6240-25983c6c4592
228
229 - name: Delete host
230 purestorage.flasharray.purefa_host:
231 name: foo
232 fa_url: 10.10.10.2
233 api_token: e31060a7-21fc-e277-6240-25983c6c4592
234 state: absent
235
236 - name: Make host bar with wwn ports
237 purestorage.flasharray.purefa_host:
238 name: bar
239 wwns:
240 - 00:00:00:00:00:00:00:00
241 - 11:11:11:11:11:11:11:11
242 fa_url: 10.10.10.2
243 api_token: e31060a7-21fc-e277-6240-25983c6c4592
244
245 - name: Make host bar with iSCSI ports
246 purestorage.flasharray.purefa_host:
247 name: bar
248 iqn:
249 - iqn.1994-05.com.redhat:7d366003913
250 fa_url: 10.10.10.2
251 api_token: e31060a7-21fc-e277-6240-25983c6c4592
252
253 - name: Make host bar with NVMe ports
254 purestorage.flasharray.purefa_host:
255 name: bar
256 nqn:
257 - nqn.2014-08.com.vendor:nvme:nvm-subsystem-sn-d78432
258 fa_url: 10.10.10.2
259 api_token: e31060a7-21fc-e277-6240-25983c6c4592
260
261 - name: Make mixed protocol host
262 purestorage.flasharray.purefa_host:
263 name: bar
264 iqn:
265 - iqn.1994-05.com.redhat:7d366003914
266 wwns:
267 - 00:00:00:00:00:00:00:01
268 - 11:11:11:11:11:11:11:12
269 fa_url: 10.10.10.2
270 api_token: e31060a7-21fc-e277-6240-25983c6c4592
271
272 - name: Map host foo to volume bar as LUN ID 12
273 purestorage.flasharray.purefa_host:
274 name: foo
275 volume: bar
276 lun: 12
277 fa_url: 10.10.10.2
278 api_token: e31060a7-21fc-e277-6240-25983c6c4592
279
280 - name: Disconnect volume bar from host foo
281 purestorage.flasharray.purefa_host:
282 name: foo
283 volume: bar
284 state: absent
285 fa_url: 10.10.10.2
286 api_token: e31060a7-21fc-e277-6240-25983c6c4592
287
288 - name: Add preferred arrays to host foo
289 purestorage.flasharray.purefa_host:
290 name: foo
291 preferred_array:
292 - array1
293 - array2
294 fa_url: 10.10.10.2
295 api_token: e31060a7-21fc-e277-6240-25983c6c4592
296
297 - name: Delete preferred arrays from host foo
298 purestorage.flasharray.purefa_host:
299 name: foo
300 preferred_array: delete
301 fa_url: 10.10.10.2
302 api_token: e31060a7-21fc-e277-6240-25983c6c4592
303
304 - name: Delete existing WWNs from host foo (does not delete host object)
305 purestorage.flasharray.purefa_host:
306 name: foo
307 wwns: ""
308 fa_url: 10.10.10.2
309 api_token: e31060a7-21fc-e277-6240-25983c6c4592
310
311 - name: Set CHAP target and host username/password pairs
312 purestorage.flasharray.purefa_host:
313 name: foo
314 target_user: user1
315 target_password: passwrodpassword
316 host_user: user2
317 host_password: passwrodpassword
318 fa_url: 10.10.10.2
319 api_token: e31060a7-21fc-e277-6240-25983c6c4592
320
321 - name: Delete CHAP target and host username/password pairs
322 purestorage.flasharray.purefa_host:
323 name: foo
324 target_user: user
325 target_password: clear
326 host_user: user
327 host_password: clear
328 fa_url: 10.10.10.2
329 api_token: e31060a7-21fc-e277-6240-25983c6c4592
330
331 - name: Move host foo from the array to realm bar
332 purestorage.flasharray.purefa_host:
333 name: foo
334 move: bar
335 fa_url: 10.10.10.2
336 api_token: e31060a7-21fc-e277-6240-25983c6c4592
337
338 - name: Move host foo from realm bar back to array
339 purestorage.flasharray.purefa_host:
340 name: bar::foo
341 move: local
342 fa_url: 10.10.10.2
343 api_token: e31060a7-21fc-e277-6240-25983c6c4592
344
345 - name: Rename host foo in realm test to bar
346 purestorage.flasharray.purefa_host:
347 name: test::foo
348 rename: test::bar
349 fa_url: 10.10.10.2
350 api_token: e31060a7-21fc-e277-6240-25983c6c4592
351 """
352
353 RETURN = r"""
354 """
355
356 HAS_PURESTORAGE = True
357 try:
358 from pypureclient.flasharray import (
359 Chap,
360 HostPatch,
361 HostPost,
362 ConnectionPost,
363 Reference,
364 )
365 except ImportError:
366 HAS_PURESTORAGE = False
367
368 import re
369 from ansible.module_utils.basic import AnsibleModule
370 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
371 get_array,
372 purefa_argument_spec,
373 )
374 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
375 LooseVersion,
376 )
377
378 VLAN_API_VERSION = "2.16"
379 CONTEXT_API_VERSION = "2.38"
380 REALMS_CONTEXT_VERSION = "2.47"
381
382
383 def _is_cbs(array, is_cbs=False):
384 """Is the selected array a Cloud Block Store"""
385 # api_version = array.get_rest_version()
386 #
387 # Until get_controller has context_names we can check against a target system
388 # so CBS can't be support for Fusion until 6.8.4??
389 #
390 # if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
391 # model = list(
392 # array.get_controllers(context_names=[module.params["context"]]).items
393 # )[0].model
394 # else:
395 model = list(array.get_controllers().items)[0].model
396 is_cbs = bool("CBS" in model)
397 return is_cbs
398
399
400 def _set_host_initiators(module, array):
401 """Set host initiators."""
402 api_version = array.get_rest_version()
403 if module.params["nqn"]:
404 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
405 res = array.patch_hosts(
406 names=[module.params["name"]],
407 host=HostPatch(nqns=module.params["nqn"]),
408 context_names=[module.params["context"]],
409 )
410 else:
411 res = array.patch_hosts(
412 names=[module.params["name"]],
413 host=HostPatch(nqns=module.params["nqn"]),
414 )
415 if res.status_code != 200:
416 module.fail_json(
417 msg="Setting of NVMe NQN failed for host {0}. Error: {1}.".format(
418 module.params["name"], res.errors[0].message
419 )
420 )
421 if module.params["iqn"]:
422 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
423 res = array.patch_hosts(
424 names=[module.params["name"]],
425 host=HostPatch(iqns=module.params["iqn"]),
426 context_names=[module.params["context"]],
427 )
428 else:
429 res = array.patch_hosts(
430 names=[module.params["name"]],
431 host=HostPatch(iqns=module.params["iqn"]),
432 )
433 if res.status_code != 200:
434 module.fail_json(
435 msg="Setting of iSCSI IQN failed for host {0}. Error: {1}.".format(
436 module.params["name"], res.errors[0].message
437 )
438 )
439 if module.params["wwns"]:
440 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
441 res = array.patch_hosts(
442 names=[module.params["name"]],
443 host=HostPatch(wwns=module.params["wwns"]),
444 context_names=[module.params["context"]],
445 )
446 else:
447 res = array.patch_hosts(
448 names=[module.params["name"]],
449 host=HostPatch(wwns=module.params["wwns"]),
450 )
451 if res.status_code != 200:
452 module.fail_json(
453 msg="Setting of FC WWNs failed for host {0}. Error: {1}.".format(
454 module.params["name"], res.errors[0].message
455 )
456 )
457
458
459 def _update_host_initiators(module, array, answer=False):
460 """Change host initiator if iscsi or nvme or add new FC WWNs"""
461 api_version = array.get_rest_version()
462 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
463 current_connectors = list(
464 array.get_hosts(
465 names=[module.params["name"]],
466 context_names=[module.params["context"]],
467 ).items
468 )[0]
469 else:
470 current_connectors = list(array.get_hosts(names=[module.params["name"]]).items)[
471 0
472 ]
473 if module.params["nqn"]:
474 if module.params["nqn"] != [""]:
475 if sorted(current_connectors.nqns) != sorted(module.params["nqn"]):
476 answer = True
477 if not module.check_mode:
478 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
479 res = array.patch_hosts(
480 names=[module.params["name"]],
481 context_names=[module.params["context"]],
482 host=HostPatch(nqns=module.params["nqn"]),
483 )
484 else:
485 res = array.patch_hosts(
486 names=[module.params["name"]],
487 host=HostPatch(nqns=module.params["nqn"]),
488 )
489 if res.status_code != 200:
490 module.fail_json(
491 msg="Change of NVMe NQNs failed on host {0}. Error: {1}.".format(
492 module.params["name"], res.errors[0].message
493 )
494 )
495 elif current_connectors.nqns:
496 answer = True
497 if not module.check_mode:
498 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
499 res = array.patch_hosts(
500 names=[module.params["name"]],
501 context_names=[module.params["context"]],
502 host=HostPatch(remove_nqns=current_connectors.nqns),
503 )
504 else:
505 res = array.patch_hosts(
506 names=[module.params["name"]],
507 host=HostPatch(remove_nqns=current_connectors.nqns),
508 )
509 if res.status_code != 200:
510 module.fail_json(
511 msg="Removal of NVMe NQNs failed on host {0}. Error: {1}.".format(
512 module.params["name"], res.errors[0].message
513 )
514 )
515 if module.params["iqn"]:
516 if module.params["iqn"] != [""]:
517 if sorted(current_connectors.iqns) != sorted(module.params["iqn"]):
518 answer = True
519 if not module.check_mode:
520 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
521 res = array.patch_hosts(
522 names=[module.params["name"]],
523 context_names=[module.params["context"]],
524 host=HostPatch(iqns=module.params["iqn"]),
525 )
526 else:
527 res = array.patch_hosts(
528 names=[module.params["name"]],
529 host=HostPatch(iqns=module.params["iqn"]),
530 )
531 if res.status_code != 200:
532 module.fail_json(
533 msg="Change of iSCSI IQNs failed on host {0}. Error: {1}.".format(
534 module.params["name"], res.errors[0].message
535 )
536 )
537 elif current_connectors.iqns:
538 answer = True
539 if not module.check_mode:
540 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
541 res = array.patch_hosts(
542 names=[module.params["name"]],
543 context_names=[module.params["context"]],
544 host=HostPatch(remove_iqns=current_connectors.iqns),
545 )
546 else:
547 res = array.patch_hosts(
548 names=[module.params["name"]],
549 host=HostPatch(remove_iqns=current_connectors.iqns),
550 )
551 if res.status_code != 200:
552 module.fail_json(
553 msg="Removal of iSCSI IQNs failed on host {0}. Error: {1}.".format(
554 module.params["name"], res.errors[0].message
555 )
556 )
557 if module.params["wwns"]:
558 module.params["wwns"] = [wwn.replace(":", "") for wwn in module.params["wwns"]]
559 module.params["wwns"] = [wwn.upper() for wwn in module.params["wwns"]]
560 if module.params["wwns"] != [""]:
561 if sorted(current_connectors.wwns) != sorted(module.params["wwns"]):
562 answer = True
563 if not module.check_mode:
564 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
565 res = array.patch_hosts(
566 names=module.params["name"],
567 context_names=[module.params["context"]],
568 host=HostPatch(wwns=module.params["wwns"]),
569 )
570 else:
571 res = array.patch_hosts(
572 names=module.params["name"],
573 host=HostPatch(wwns=module.params["wwns"]),
574 )
575 if res.status_code != 200:
576 module.fail_json(
577 msg="Change of FC WWNs failed on host {0}. Error: {1}.".format(
578 module.params["name"], res.errors[0].message
579 )
580 )
581 elif current_connectors.wwns:
582 answer = True
583 if not module.check_mode:
584 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
585 res = array.patch_hosts(
586 names=[module.params["name"]],
587 context_names=[module.params["context"]],
588 host=HostPatch(remove_wwns=current_connectors.wwns),
589 )
590 else:
591 res = array.patch_hosts(
592 names=[module.params["name"]],
593 host=HostPatch(remove_wwns=current_connectors.wwns),
594 )
595 if res.status_code != 200:
596 module.fail_json(
597 msg="Removal of FC WWNs failed on host {0}. Error: {1}.".format(
598 module.params["name"], res.errors[0].message
599 )
600 )
601 return answer
602
603
604 def _connect_new_volume(module, array):
605 """Connect volume to host"""
606 api_version = array.get_rest_version()
607 if not module.check_mode:
608 if module.params["lun"]:
609 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
610 res = array.post_connections(
611 host_names=[module.params["name"]],
612 context_names=[module.params["context"]],
613 volume_names=[module.params["volume"]],
614 connection=ConnectionPost(lun=module.params["lun"]),
615 )
616 else:
617 res = array.post_connections(
618 host_names=[module.params["name"]],
619 volume_names=[module.params["volume"]],
620 connection=ConnectionPost(lun=module.params["lun"]),
621 )
622 else:
623 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
624 res = array.post_connections(
625 host_names=[module.params["name"]],
626 context_names=[module.params["context"]],
627 volume_names=[module.params["volume"]],
628 )
629 else:
630 res = array.post_connections(
631 host_names=[module.params["name"]],
632 volume_names=[module.params["volume"]],
633 )
634 if res.status_code != 200:
635 module.fail_json(
636 msg="Failed to connect volume {0} to host {1}. Error: {2}".format(
637 module.params["volume"],
638 module.params["name"],
639 res.errors[0].message,
640 )
641 )
642 return True
643
644
645 def _disconnect_volume(module, array):
646 """Disconnect volume from host"""
647 api_version = array.get_rest_version()
648 if not module.check_mode:
649 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
650 res = array.delete_connections(
651 host_names=[module.params["name"]],
652 context_names=[module.params["context"]],
653 volume_names=[module.params["volume"]],
654 )
655 else:
656 res = array.delete_connections(
657 host_names=[module.params["name"]],
658 volume_names=[module.params["volume"]],
659 )
660 if res.status_code != 200:
661 module.fail_json(
662 msg="Failed to disconnect volume {0} from host {1}. Error: {2}".format(
663 module.params["volume"],
664 module.params["name"],
665 res.errors[0].message,
666 )
667 )
668 return True
669
670
671 def _set_host_personality(module, array):
672 """Set host personality"""
673 api_version = array.get_rest_version()
674 if module.params["personality"] != "delete":
675 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
676 res = array.patch_hosts(
677 names=[module.params["name"]],
678 context_names=[module.params["context"]],
679 host=HostPatch(personality=module.params["personality"]),
680 )
681 else:
682 res = array.patch_hosts(
683 names=[module.params["name"]],
684 host=HostPatch(personality=module.params["personality"]),
685 )
686 else:
687 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
688 res = array.patch_hosts(
689 names=[module.params["name"]],
690 context_names=[module.params["context"]],
691 host=HostPatch(personality=""),
692 )
693 else:
694 res = array.patch_hosts(
695 names=[module.params["name"]], host=HostPatch(personality="")
696 )
697 if res.status_code != 200:
698 module.fail_json(
699 msg="Failed to set personality on host {0}. Error: {1}".format(
700 module.params["name"], res.errors[0].message
701 )
702 )
703
704
705 def _set_preferred_array(module, array):
706 """Set preferred array list"""
707 api_version = array.get_rest_version()
708 if module.params["preferred_array"] != ["delete"]:
709 preferred_array_list = []
710 for preferred_array in module.params["preferred_array"]:
711 preferred_array_list.append(Reference(name=preferred_array))
712 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
713 res = array.patch_hosts(
714 names=[module.params["name"]],
715 context_names=[module.params["context"]],
716 host=HostPatch(preferred_arrays=preferred_array_list),
717 )
718 else:
719 res = array.patch_hosts(
720 names=[module.params["name"]],
721 host=HostPatch(preferred_arrays=preferred_array_list),
722 )
723 else:
724 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
725 res = array.patch_hosts(
726 names=[module.params["name"]],
727 context_names=[module.params["context"]],
728 host=HostPatch(preferred_arrays=[]),
729 )
730 else:
731 res = array.patch_hosts(
732 names=[module.params["name"]], host=HostPatch(preferred_arrays=[])
733 )
734 if res.status_code != 200:
735 module.fail_json(
736 msg="Failed to set preferred arrays on host {0}. Error: {1}".format(
737 module.params["name"], res.errors[0].message
738 )
739 )
740
741
742 def _set_chap_security(module, array):
743 """Set CHAP usernames and passwords"""
744 api_version = array.get_rest_version()
745 pattern = re.compile("[^ ]{12,255}")
746 if module.params["host_user"]:
747 if not pattern.match(module.params["host_password"]):
748 module.fail_json(
749 msg="host_password must contain a minimum of 12 and a maximum of 255 characters"
750 )
751 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
752 res = array.patch_hosts(
753 names=[module.params["name"]],
754 context_names=[module.params["context"]],
755 host=HostPatch(
756 chap=Chap(
757 host_user=module.params["host_user"],
758 host_password=module.params["host_password"],
759 )
760 ),
761 )
762 else:
763 res = array.patch_hosts(
764 names=[module.params["name"]],
765 host=HostPatch(
766 chap=Chap(
767 host_user=module.params["host_user"],
768 host_password=module.params["host_password"],
769 )
770 ),
771 )
772 if res.status_code != 200:
773 module.fail_json(
774 msg="Failed to set CHAP host username and password. Error: {0}".format(
775 res.errors[0].message
776 )
777 )
778 if module.params["target_user"]:
779 if not pattern.match(module.params["target_password"]):
780 module.fail_json(
781 msg="target_password must contain a minimum of 12 and a maximum of 255 characters"
782 )
783 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
784 res = array.patch_hosts(
785 names=[module.params["name"]],
786 context_names=[module.params["context"]],
787 host=HostPatch(
788 chap=Chap(
789 target_user=module.params["target_user"],
790 target_password=module.params["target_password"],
791 )
792 ),
793 )
794 else:
795 res = array.patch_hosts(
796 names=[module.params["name"]],
797 host=HostPatch(
798 chap=Chap(
799 target_user=module.params["target_user"],
800 target_password=module.params["target_password"],
801 )
802 ),
803 )
804 if res.status_code != 200:
805 module.fail_json(
806 msg="Failed to set CHAP target username and password. Error: {0}".format(
807 res.errors[0].message
808 )
809 )
810
811
812 def _update_chap_security(module, array, answer=False):
813 """Change CHAP usernames and passwords"""
814 api_version = array.get_rest_version()
815 pattern = re.compile("[^ ]{12,255}")
816 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
817 chap = list(
818 array.get_hosts(
819 names=[module.params["name"]],
820 context_names=[module.params["context"]],
821 ).items
822 )[0].chap
823 else:
824 chap = list(array.get_hosts(names=[module.params["name"]]).items)[0].chap
825 if module.params["host_user"]:
826 if module.params["host_password"] == "clear":
827 if hasattr(chap, "host_user"):
828 answer = True
829 if not module.check_mode:
830 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
831 res = array.patch_hosts(
832 names=[module.params["name"]],
833 context_names=[module.params["context"]],
834 host=HostPatch(chap=Chap(host_user="", host_password="")),
835 )
836 else:
837 res = array.patch_hosts(
838 names=[module.params["name"]],
839 host=HostPatch(chap=Chap(host_user="", host_password="")),
840 )
841 if res.status_code != 200:
842 module.fail_json(
843 msg="Failed to clear CHAP host username and password. Error: {0}".format(
844 res.errors[0].message
845 )
846 )
847 else:
848 if not pattern.match(module.params["host_password"]):
849 module.fail_json(
850 msg="host_password must contain a minimum of 12 and a maximum of 255 characters"
851 )
852 answer = True
853 if not module.check_mode:
854 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
855 res = array.patch_hosts(
856 names=[module.params["name"]],
857 context_names=[module.params["context"]],
858 host=HostPatch(
859 chap=Chap(
860 host_user=module.params["host_user"],
861 host_password=module.params["host_password"],
862 )
863 ),
864 )
865 else:
866 res = array.patch_hosts(
867 names=[module.params["name"]],
868 host=HostPatch(
869 chap=Chap(
870 host_user=module.params["host_user"],
871 host_password=module.params["host_password"],
872 )
873 ),
874 )
875 if res.status_code != 200:
876 module.fail_json(
877 msg="Failed to update CHAP host username and password. Error: {0}".format(
878 res.errors[0].message
879 )
880 )
881 if module.params["target_user"]:
882 if module.params["target_password"] == "clear":
883 if hasattr(chap, "target_user"):
884 answer = True
885 if not module.check_mode:
886 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
887 res = array.patch_hosts(
888 names=[module.params["name"]],
889 context_names=[module.params["context"]],
890 host=HostPatch(
891 chap=Chap(target_user="", target_password="")
892 ),
893 )
894 else:
895 res = array.patch_hosts(
896 names=[module.params["name"]],
897 host=HostPatch(
898 chap=Chap(target_user="", target_password="")
899 ),
900 )
901 if res.status_code != 200:
902 module.fail_json(
903 msg="Failed to clear CHAP target username and password. Error: {0}".format(
904 res.errors[0].message
905 )
906 )
907 else:
908 if not pattern.match(module.params["target_password"]):
909 module.fail_json(
910 msg="target_password must contain a minimum of 12 and a maximum of 255 characters"
911 )
912 answer = True
913 if not module.check_mode:
914 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
915 res = array.patch_hosts(
916 names=[module.params["name"]],
917 context_names=[module.params["context"]],
918 host=HostPatch(
919 chap=Chap(
920 target_user=module.params["target_user"],
921 target_password=module.params["target_password"],
922 )
923 ),
924 )
925 else:
926 res = array.patch_hosts(
927 names=[module.params["name"]],
928 host=HostPatch(
929 chap=Chap(
930 target_user=module.params["target_user"],
931 target_password=module.params["target_password"],
932 )
933 ),
934 )
935 if res.status_code != 200:
936 module.fail_json(
937 msg="Failed to update CHAP target username and password. Error: {0}".format(
938 res.errors[0].message
939 )
940 )
941 return answer
942
943
944 def _update_host_personality(module, array, answer=False):
945 """Change host personality"""
946 api_version = array.get_rest_version()
947 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
948 host = list(
949 array.get_hosts(
950 names=[module.params["name"]],
951 context_names=[module.params["context"]],
952 ).items
953 )[0]
954 else:
955 host = list(array.get_hosts(names=[module.params["name"]]).items)[0]
956 if not hasattr(host, "personality") and module.params["personality"] != "delete":
957 answer = True
958 if not module.check_mode:
959 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
960 res = array.patch_hosts(
961 names=[module.params["name"]],
962 context_names=[module.params["context"]],
963 host=HostPatch(personality=module.params["personality"]),
964 )
965 else:
966 res = array.patch_hosts(
967 names=[module.params["name"]],
968 host=HostPatch(personality=module.params["personality"]),
969 )
970 if res.status_code != 200:
971 module.fail_json(
972 msg="Update host personality failed. Error: {0}".format(
973 res.errors[0].message
974 )
975 )
976 if hasattr(host, "personality"):
977 if module.params["personality"] == "delete":
978 answer = True
979 if not module.check_mode:
980 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
981 res = array.patch_hosts(
982 names=[module.params["name"]],
983 host=HostPatch(personality=""),
984 context_names=[module.params["context"]],
985 )
986 else:
987 res = array.patch_hosts(
988 names=[module.params["name"]], host=HostPatch(personality="")
989 )
990 if res.status_code != 200:
991 module.fail_json(
992 msg="Host personality deletion failed. Error: {0}".format(
993 res.errors[0].message
994 )
995 )
996 elif host.personality != module.params["personality"]:
997 answer = True
998 if not module.check_mode:
999 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1000 res = array.patch_hosts(
1001 names=[module.params["name"]],
1002 context_names=[module.params["context"]],
1003 host=HostPatch(personality=module.params["personality"]),
1004 )
1005 else:
1006 res = array.patch_hosts(
1007 names=[module.params["name"]],
1008 host=HostPatch(personality=module.params["personality"]),
1009 )
1010 if res.status_code != 200:
1011 module.fail_json(
1012 msg="Host personality change failed. Error: {0}".format(
1013 res.errors[0].message
1014 )
1015 )
1016 return answer
1017
1018
1019 def _update_preferred_array(module, array, answer=False):
1020 """Update existing preferred array list"""
1021 api_version = array.get_rest_version()
1022 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1023 preferred_array = list(
1024 array.get_hosts(
1025 names=[module.params["name"]],
1026 context_names=[module.params["context"]],
1027 ).items
1028 )[0].preferred_arrays
1029 else:
1030 preferred_array = list(array.get_hosts(names=[module.params["name"]]).items)[
1031 0
1032 ].preferred_arrays
1033 if preferred_array == [] and module.params["preferred_array"] != ["delete"]:
1034 answer = True
1035 preferred_array_list = []
1036 for preferred_array in module.params["preferred_array"]:
1037 preferred_array_list.append(Reference(name=preferred_array))
1038 if not module.check_mode:
1039 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1040 res = array.patch_hosts(
1041 names=[module.params["name"]],
1042 context_names=[module.params["context"]],
1043 host=HostPatch(preferred_arrays=preferred_array_list),
1044 )
1045 else:
1046 res = array.patch_hosts(
1047 names=[module.params["name"]],
1048 host=HostPatch(preferred_arrays=preferred_array_list),
1049 )
1050 if res.status_code != 200:
1051 module.fail_json(
1052 msg="Preferred array list creation failed for host {0}. Error: {1}".format(
1053 module.params["name"], res.errors[0].message
1054 )
1055 )
1056 elif preferred_array != []:
1057 if module.params["preferred_array"] == ["delete"]:
1058 answer = True
1059 if not module.check_mode:
1060 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1061 res = array.patch_hosts(
1062 names=[module.params["name"]],
1063 host=HostPatch(preferred_arrays=[]),
1064 context_names=[module.params["context"]],
1065 )
1066 else:
1067 res = array.patch_hosts(
1068 names=[module.params["name"]],
1069 host=HostPatch(preferred_arrays=[]),
1070 )
1071 if res.status_code != 200:
1072 module.fail_json(
1073 msg="Preferred array list deletion failed for {0}. Error: {1}".format(
1074 module.params["name"], res.errors[0].message
1075 )
1076 )
1077 else:
1078 current_preferred_array_list = []
1079 for array_name in preferred_array:
1080 current_preferred_array_list.append(array_name.name)
1081 if sorted(current_preferred_array_list) != sorted(
1082 module.params["preferred_array"]
1083 ):
1084 answer = True
1085 if not module.check_mode:
1086 preferred_array_list = []
1087 for array_name in module.params["preferred_array"]:
1088 preferred_array_list.append(Reference(name=array_name))
1089 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1090 res = array.patch_hosts(
1091 names=[module.params["name"]],
1092 context_names=[module.params["context"]],
1093 host=HostPatch(preferred_arrays=preferred_array_list),
1094 )
1095 else:
1096 res = array.patch_hosts(
1097 names=[module.params["name"]],
1098 host=HostPatch(preferred_arrays=preferred_array_list),
1099 )
1100 if res.status_code != 200:
1101 module.fail_json(
1102 msg="Preferred array list change failed for {0}. Error: {1}".format(
1103 module.params["name"], res.errors[0].message
1104 )
1105 )
1106 return answer
1107
1108
1109 def _set_vlan(module, array):
1110 api_version = array.get_rest_version()
1111 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1112 res = array.patch_hosts(
1113 names=[module.params["name"]],
1114 context_names=[module.params["context"]],
1115 host=HostPatch(vlan=module.params["vlan"]),
1116 )
1117 else:
1118 res = array.patch_hosts(
1119 names=[module.params["name"]],
1120 host=HostPatch(vlan=module.params["vlan"]),
1121 )
1122 if res.status_code != 200:
1123 module.warn(
1124 "Failed to set host VLAN ID. Error: {0}".format(res.errors[0].message)
1125 )
1126
1127
1128 def _update_vlan(module, array):
1129 api_version = array.get_rest_version()
1130 changed = False
1131 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1132 host_vlan = getattr(
1133 list(
1134 array.get_hosts(
1135 names=[module.params["name"]],
1136 context_names=[module.params["context"]],
1137 ).items
1138 )[0],
1139 "vlan",
1140 None,
1141 )
1142 else:
1143 host_vlan = getattr(
1144 list(array.get_hosts(names=[module.params["name"]]).items)[0], "vlan", None
1145 )
1146 if module.params["vlan"] != host_vlan:
1147 changed = True
1148 if not module.check_mode:
1149 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1150 res = array.patch_hosts(
1151 names=[module.params["name"]],
1152 context_names=[module.params["context"]],
1153 host=HostPatch(vlan=module.params["vlan"]),
1154 )
1155 else:
1156 res = array.patch_hosts(
1157 names=[module.params["name"]],
1158 host=HostPatch(vlan=module.params["vlan"]),
1159 )
1160 if res.status_code != 200:
1161 module.fail_json(
1162 msg="Failed to update host VLAN ID. Error: {0}".format(
1163 res.errors[0].message
1164 )
1165 )
1166 return changed
1167
1168
1169 def get_multi_hosts(module, array):
1170 """Return True is all hosts exist"""
1171 api_version = array.get_rest_version()
1172 hosts = []
1173 for host_num in range(
1174 module.params["start"], module.params["count"] + module.params["start"]
1175 ):
1176 if module.params["suffix"]:
1177 hosts.append(
1178 module.params["name"]
1179 + str(host_num).zfill(module.params["digits"])
1180 + module.params["suffix"]
1181 )
1182 else:
1183 hosts.append(
1184 module.params["name"] + str(host_num).zfill(module.params["digits"])
1185 )
1186 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1187 return bool(
1188 array.get_hosts(
1189 names=hosts, context_names=[module.params["context"]]
1190 ).status_code
1191 == 200
1192 )
1193 return bool(array.get_hosts(names=hosts).status_code == 200)
1194
1195
1196 def get_host(module, array):
1197 """Return host or None"""
1198 api_version = array.get_rest_version()
1199 host = None
1200 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1201 res = array.get_hosts(
1202 names=[module.params["name"]], context_names=[module.params["context"]]
1203 )
1204 else:
1205 res = array.get_hosts(names=[module.params["name"]])
1206 if res.status_code == 200:
1207 host = list(res.items)[0]
1208 return host
1209
1210
1211 def rename_exists(module, array):
1212 """Determine if rename target already exists"""
1213 api_version = array.get_rest_version()
1214 exists = False
1215 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1216 res = array.get_hosts(
1217 names=[module.params["rename"]],
1218 context_names=[module.params["context"]],
1219 )
1220 else:
1221 res = array.get_hosts(names=[module.params["rename"]])
1222 if res.status_code == 200:
1223 exists = True
1224 return exists
1225
1226
1227 def make_multi_hosts(module, array):
1228 """Create multiple hosts"""
1229 api_version = array.get_rest_version()
1230 changed = True
1231 if not module.check_mode:
1232 hosts = []
1233 for host_num in range(
1234 module.params["start"], module.params["count"] + module.params["start"]
1235 ):
1236 if module.params["suffix"]:
1237 hosts.append(
1238 module.params["name"]
1239 + str(host_num).zfill(module.params["digits"])
1240 + module.params["suffix"]
1241 )
1242 else:
1243 hosts.append(
1244 module.params["name"] + str(host_num).zfill(module.params["digits"])
1245 )
1246 if module.params["personality"]:
1247 host = HostPost(personality=module.params["personality"])
1248 else:
1249 host = HostPost()
1250 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1251 res = array.post_hosts(
1252 names=hosts, host=host, context_names=[module.params["context"]]
1253 )
1254 else:
1255 res = array.post_hosts(names=hosts, host=host)
1256 if res.status_code != 200:
1257 module.fail_json(
1258 msg="Multi-Host {0}#{1} creation failed: {2}".format(
1259 module.params["name"],
1260 module.params["suffix"],
1261 res.errors[0].message,
1262 )
1263 )
1264 module.exit_json(changed=changed)
1265
1266
1267 def make_host(module, array):
1268 """Create a new host"""
1269 api_version = array.get_rest_version()
1270 changed = True
1271 if not module.check_mode:
1272 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1273 res = array.post_hosts(
1274 names=[module.params["name"]],
1275 host=HostPost(),
1276 context_names=[module.params["context"]],
1277 )
1278 else:
1279 res = array.post_hosts(names=[module.params["name"]], host=HostPost())
1280 if res.status_code != 200:
1281 module.fail_json(
1282 msg="Host {0} creation failed. Error: {1}".format(
1283 module.params["name"], res.errors[0].message
1284 )
1285 )
1286 if module.params["vlan"]:
1287 _set_vlan(module, array)
1288 _set_host_initiators(module, array)
1289 if module.params["personality"]:
1290 _set_host_personality(module, array)
1291 if module.params["preferred_array"]:
1292 _set_preferred_array(module, array)
1293 if module.params["host_user"] or module.params["target_user"]:
1294 _set_chap_security(module, array)
1295 if module.params["volume"]:
1296 if module.params["lun"]:
1297 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1298 res = array.post_connections(
1299 host_names=[module.params["name"]],
1300 context_names=[module.params["context"]],
1301 volume_names=[module.params["volume"]],
1302 connection=ConnectionPost(lun=module.params["lun"]),
1303 )
1304 else:
1305 res = array.post_connections(
1306 host_names=[module.params["name"]],
1307 volume_names=[module.params["volume"]],
1308 connection=ConnectionPost(lun=module.params["lun"]),
1309 )
1310 if res.status_code != 200:
1311 module.fail_json(
1312 msg="Volume connection failed. Error: {0}".format(
1313 res.errors[0].message
1314 )
1315 )
1316 else:
1317 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1318 res = array.post_connections(
1319 host_names=[module.params["name"]],
1320 context_names=[module.params["context"]],
1321 volume_names=[module.params["volume"]],
1322 )
1323 else:
1324 res = array.post_connections(
1325 host_names=[module.params["name"]],
1326 volume_names=[module.params["volume"]],
1327 )
1328 if res.status_code != 200:
1329 module.fail_json(
1330 msg="Volume connection failed. Error: {0}".format(
1331 res.errors[0].message
1332 )
1333 )
1334 module.exit_json(changed=changed)
1335
1336
1337 def update_host(module, array):
1338 """Modify a host"""
1339 changed = False
1340 renamed = False
1341 vol_changed = False
1342 vlan_changed = False
1343 api_version = array.get_rest_version()
1344 if module.params["state"] == "present":
1345 if (
1346 LooseVersion(VLAN_API_VERSION) <= LooseVersion(api_version)
1347 and module.params["vlan"]
1348 ):
1349 vlan_changed = _update_vlan(module, array)
1350 if module.params["rename"]:
1351 if not rename_exists(module, array):
1352 if not module.check_mode:
1353 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1354 res = array.patch_hosts(
1355 names=[module.params["name"]],
1356 context_names=[module.params["context"]],
1357 host=HostPatch(name=module.params["rename"]),
1358 )
1359 else:
1360 res = array.patch_hosts(
1361 names=[module.params["name"]],
1362 host=HostPatch(name=module.params["rename"]),
1363 )
1364 if res.status_code != 200:
1365 module.fail_json(
1366 msg="Rename host {0} to {1} failed. Error: {2}".format(
1367 module.params["name"],
1368 module.params["rename"],
1369 res.errors[0].message,
1370 )
1371 )
1372 module.params["name"] = module.params["rename"]
1373 renamed = True
1374 else:
1375 module.warn(
1376 "Rename failed. Target hostname {0} already exists. "
1377 "Continuing with any other changes...".format(
1378 module.params["rename"]
1379 )
1380 )
1381 init_changed = pers_changed = pref_changed = chap_changed = False
1382 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1383 volumes = list(
1384 array.get_connections(
1385 host_names=[module.params["name"]],
1386 context_names=[module.params["context"]],
1387 ).items
1388 )
1389 else:
1390 volumes = list(
1391 array.get_connections(host_names=[module.params["name"]]).items
1392 )
1393 if module.params["iqn"] or module.params["wwns"] or module.params["nqn"]:
1394 init_changed = _update_host_initiators(module, array)
1395 if module.params["volume"]:
1396 current_vols = [vol.volume.name for vol in volumes]
1397 if not module.params["volume"] in current_vols:
1398 vol_changed = _connect_new_volume(module, array)
1399 if module.params["personality"]:
1400 pers_changed = _update_host_personality(module, array)
1401 if module.params["preferred_array"]:
1402 pref_changed = _update_preferred_array(module, array)
1403 if module.params["target_user"] or module.params["host_user"]:
1404 chap_changed = _update_chap_security(module, array)
1405 changed = (
1406 init_changed
1407 or vol_changed
1408 or pers_changed
1409 or pref_changed
1410 or chap_changed
1411 or vlan_changed
1412 or renamed
1413 )
1414 else:
1415 if module.params["volume"]:
1416 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1417 volumes = list(
1418 array.get_connections(
1419 host_names=[module.params["name"]],
1420 context_names=[module.params["context"]],
1421 ).items
1422 )
1423 else:
1424 volumes = list(
1425 array.get_connections(host_names=[module.params["name"]]).items
1426 )
1427 current_vols = [vol.volume.name for vol in volumes]
1428 if module.params["volume"] in current_vols:
1429 vol_changed = _disconnect_volume(module, array)
1430 changed = vol_changed
1431 module.exit_json(changed=changed)
1432
1433
1434 def delete_host(module, array):
1435 """Delete a host"""
1436 api_version = array.get_rest_version()
1437 changed = True
1438 if not module.check_mode:
1439 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1440 has_hg = hasattr(
1441 list(
1442 array.get_hosts(
1443 names=[module.params["name"]],
1444 context_names=[module.params["context"]],
1445 ).items
1446 )[0].host_group,
1447 "name",
1448 )
1449 else:
1450 has_hg = hasattr(
1451 list(array.get_hosts(names=[module.params["name"]]).items)[
1452 0
1453 ].host_group,
1454 "name",
1455 )
1456 if has_hg:
1457 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1458 res = array.delete_host_groups_hosts(
1459 group_names=[
1460 list(array.get_hosts(names=[module.params["name"]]).items)[
1461 0
1462 ].host_group.name
1463 ],
1464 member_names=[module.params["name"]],
1465 context_names=[module.params["context"]],
1466 )
1467 else:
1468 res = array.delete_host_groups_hosts(
1469 group_names=[
1470 list(array.get_hosts(names=[module.params["name"]]).items)[
1471 0
1472 ].host_group.name
1473 ],
1474 member_names=[module.params["name"]],
1475 )
1476 if res.status_code != 200:
1477 module.fail_json(
1478 msg="Host {0} failed to remove from hostgroup. Error: {1}".format(
1479 module.params["name"], res.errors[0].message
1480 )
1481 )
1482 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1483 volumes = list(
1484 array.get_connections(
1485 host_names=[module.params["name"]],
1486 context_names=[module.params["context"]],
1487 ).items
1488 )
1489 else:
1490 volumes = list(
1491 array.get_connections(host_names=[module.params["name"]]).items
1492 )
1493 current_vols = [vol.volume.name for vol in volumes]
1494 if current_vols:
1495 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1496 res = array.delete_connections(
1497 host_names=[module.params["name"]],
1498 volume_names=current_vols,
1499 context_names=[module.params["context"]],
1500 )
1501 else:
1502 res = array.delete_connections(
1503 host_names=[module.params["name"]], volume_names=current_vols
1504 )
1505 if res.status_code != 200:
1506 module.fail_json(
1507 msg="Host {0} volume detach failed. Error: {1}".format(
1508 module.params["name"], res.errors[0].message
1509 )
1510 )
1511 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1512 res = array.delete_hosts(
1513 names=[module.params["name"]],
1514 context_names=[module.params["context"]],
1515 )
1516 else:
1517 res = array.delete_hosts(names=[module.params["name"]])
1518 if res.status_code != 200:
1519 module.fail_json(
1520 msg="Host {0} deletion failed. Error: {1}".format(
1521 module.params["name"], res.errors[0].message
1522 )
1523 )
1524 module.exit_json(changed=changed)
1525
1526
1527 def move_host(module, array):
1528 """Move host between realms and the local array"""
1529 if module.params["context"] != "":
1530 module.fail_json(msg="context is not yet supported for host move function")
1531 api_version = array.get_rest_version()
1532 local_array = list(array.get_arrays().items)[0].name
1533 # current_realm = ""
1534 if len(module.params["move"]) > 1 and len(module.params["move"]) != module.params[
1535 "move"
1536 ].count("local"):
1537 module.fail_json(msg="Cannot mix local with another realm in move target list")
1538 if "local" in module.params["move"] and "::" not in module.params["name"]:
1539 module.fail_json(msg="host must be provided with current realm name")
1540 # if "::" in module.params["name"]:
1541 # current_realm = module.params["name"].split("::")[0]
1542 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1543 current_connections = list(
1544 array.get_hosts(
1545 names=[module.params["name"]], context_names=[module.params["context"]]
1546 ).items
1547 )[0].connection_count
1548 else:
1549 current_connections = list(
1550 array.get_hosts(names=[module.params["name"]]).items
1551 )[0].connection_count
1552 if current_connections > 0:
1553 module.fail_json(msg="Hosts cannot be moved with existing volume connections.")
1554 changed = True
1555 if not module.check_mode:
1556 if "local" in module.params["move"]:
1557 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1558 res = array.patch_hosts(
1559 names=[module.params["name"]],
1560 from_member_names=[module.params["name"].split("::")[0]],
1561 to_member_names=[local_array],
1562 modify_resource_access=module.params["modify_resource_access"],
1563 host=HostPatch(),
1564 context_names=[module.params["context"]],
1565 )
1566 else:
1567 res = array.patch_hosts(
1568 names=[module.params["name"]],
1569 from_member_names=[module.params["name"].split("::")[0]],
1570 to_member_names=[local_array],
1571 modify_resource_access=module.params["modify_resource_access"],
1572 host=HostPatch(),
1573 )
1574 if res.status_code != 200:
1575 module.fail_json(
1576 msg="Failed to move host {0} to local array. Error: {1}".format(
1577 module.params["name"], res.errors[0].message
1578 )
1579 )
1580 else:
1581 realm_exists = False
1582 if LooseVersion(REALMS_CONTEXT_VERSION) <= LooseVersion(api_version):
1583 res = array.get_realms(
1584 names=module.params["move"],
1585 context_names=[module.params["context"]],
1586 )
1587 else:
1588 res = array.get_realms(names=module.params["move"])
1589 if res.status_code != 200:
1590 module.fail_json(
1591 msg="Move target(s) error: {0}".format(res.errors[0].message)
1592 )
1593 if "::" not in module.params["name"]:
1594 source_realm = local_array
1595 else:
1596 source_realm = module.params["name"].split("::")[0]
1597 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1598 res = array.patch_hosts(
1599 names=[module.params["name"]],
1600 from_member_names=[source_realm],
1601 to_member_names=module.params["move"],
1602 modify_resource_access=module.params["modify_resource_access"],
1603 host=HostPatch(),
1604 context_names=[module.params["context"]],
1605 )
1606 else:
1607 res = array.patch_hosts(
1608 names=[module.params["name"]],
1609 from_member_names=[source_realm],
1610 to_member_names=module.params["move"],
1611 modify_resource_access=module.params["modify_resource_access"],
1612 host=HostPatch(),
1613 )
1614 if res.status_code != 200:
1615 module.fail_json(
1616 msg="Failed to move host {0} to realm {1}. Error: {2}".format(
1617 module.params["name"],
1618 module.params["move"],
1619 res.errors[0].message,
1620 )
1621 )
1622 module.exit_json(changed=changed)
1623
1624
1625 def main():
1626 argument_spec = purefa_argument_spec()
1627 argument_spec.update(
1628 dict(
1629 name=dict(type="str", required=True, aliases=["host"]),
1630 state=dict(type="str", default="present", choices=["absent", "present"]),
1631 protocol=dict(
1632 type="str",
1633 choices=["fc", "iscsi", "nvme", "mixed"],
1634 removed_from_collection="1.13",
1635 removed_in_version="2.0.0",
1636 ),
1637 nqn=dict(type="list", elements="str"),
1638 iqn=dict(type="list", elements="str"),
1639 wwns=dict(type="list", elements="str"),
1640 host_password=dict(type="str", no_log=True),
1641 host_user=dict(type="str"),
1642 target_password=dict(type="str", no_log=True),
1643 target_user=dict(type="str"),
1644 volume=dict(type="str"),
1645 rename=dict(type="str"),
1646 lun=dict(type="int"),
1647 count=dict(type="int"),
1648 start=dict(type="int", default=0),
1649 digits=dict(type="int", default=1),
1650 suffix=dict(type="str"),
1651 personality=dict(
1652 type="str",
1653 default="",
1654 choices=[
1655 "hpux",
1656 "vms",
1657 "aix",
1658 "esxi",
1659 "solaris",
1660 "hitachi-vsp",
1661 "oracle-vm-server",
1662 "delete",
1663 "",
1664 ],
1665 ),
1666 preferred_array=dict(type="list", elements="str"),
1667 vlan=dict(type="str"),
1668 context=dict(type="str", default=""),
1669 move=dict(type="list", elements="str"),
1670 modify_resource_access=dict(
1671 type="str", default="none", choices=["none", "create", "delete"]
1672 ),
1673 )
1674 )
1675
1676 required_together = [
1677 ["host_password", "host_user"],
1678 ["target_password", "target_user"],
1679 ]
1680 mutually_exclusive = [
1681 ["nqn", "iqn"],
1682 ["nqn", "wwns"],
1683 ]
1684
1685 module = AnsibleModule(
1686 argument_spec,
1687 supports_check_mode=True,
1688 required_together=required_together,
1689 mutually_exclusive=mutually_exclusive,
1690 )
1691
1692 if not HAS_PURESTORAGE:
1693 module.fail_json(
1694 msg="py-pure-client sdk is required to support 'vlan' parameter"
1695 )
1696 array = get_array(module)
1697 api_version = array.get_rest_version()
1698 pattern = re.compile("^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$")
1699 if module.params["rename"]:
1700 rename = module.params["rename"]
1701 if "::" in module.params["rename"]:
1702 rename = module.params["rename"].split("::")[1]
1703 if not pattern.match(rename):
1704 module.fail_json(
1705 msg="Rename value {0} does not conform to naming convention".format(
1706 module.params["rename"]
1707 )
1708 )
1709 host_name = module.params["name"]
1710 if "::" in module.params["name"]:
1711 host_name = module.params["name"].split("::")[1]
1712 if not pattern.match(host_name):
1713 module.fail_json(
1714 msg="Host name {0} does not conform to naming convention".format(
1715 module.params["name"]
1716 )
1717 )
1718 if _is_cbs(array):
1719 if module.params["wwns"] or module.params["nqn"]:
1720 module.fail_json(msg="Cloud Block Store only supports iSCSI as a protocol")
1721 state = module.params["state"]
1722 if module.params["suffix"]:
1723 suffix_len = len(module.params["suffix"])
1724 else:
1725 suffix_len = 0
1726 if (
1727 LooseVersion(VLAN_API_VERSION) > LooseVersion(api_version)
1728 and module.params["vlan"]
1729 ):
1730 module.fail_json(
1731 msg="'vlan' parameter is not supported until Purity//FA 6.3.4 or higher"
1732 )
1733 if module.params["vlan"] and module.params["vlan"] not in ["any", "untagged"]:
1734 try:
1735 vlan = int(module.params["vlan"])
1736 if vlan not in range(1, 4094):
1737 module.fail_json(msg="VLAN must be set to a number between 1 and 4094")
1738 except Exception:
1739 module.fail_json(
1740 msg="Invalid string for VLAN. Must be 'any', 'untagged' or a number between 1 and 4094"
1741 )
1742 if module.params["count"]:
1743 if module.params["digits"] and module.params["digits"] not in range(1, 10):
1744 module.fail_json(msg="'digits' must be in the range of 1 to 10")
1745 if module.params["start"] < 0:
1746 module.fail_json(msg="'start' must be a positive number")
1747 if "::" in module.params["name"]:
1748 host_name = module.params["name"].split("::")[1]
1749 if not pattern.match(host_name):
1750 module.fail_json(
1751 msg="Host name pattern {0} does not conform to naming convention".format(
1752 module.params["name"]
1753 )
1754 )
1755 elif module.params["suffix"] and not pattern.match(module.params["suffix"]):
1756 module.fail_json(
1757 msg="Suffix pattern {0} does not conform to naming convention".format(
1758 module.params["suffix"]
1759 )
1760 )
1761 elif (
1762 len(module.params["name"])
1763 + max(
1764 len(str(module.params["count"] + module.params["start"])),
1765 module.params["digits"],
1766 )
1767 + suffix_len
1768 > 63
1769 ):
1770 module.fail_json(msg="Host name length exceeds maximum allowed")
1771 host = get_multi_hosts(module, array)
1772 if not host and state == "present":
1773 make_multi_hosts(module, array)
1774 else:
1775 host = get_host(module, array)
1776 if module.params["lun"] and not 1 <= module.params["lun"] <= 4095:
1777 module.fail_json(
1778 msg="LUN ID of {0} is out of range (1 to 4095)".format(
1779 module.params["lun"]
1780 )
1781 )
1782 if module.params["volume"]:
1783 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1784 res = array.get_volumes(
1785 names=[module.params["volume"]],
1786 context_names=[module.params["context"]],
1787 )
1788 else:
1789 res = array.get_volumes(names=[module.params["volume"]])
1790 if res.status_code != 200:
1791 module.exit_json(changed=False)
1792 if module.params["preferred_array"] and module.params["preferred_array"] != [
1793 "delete"
1794 ]:
1795 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1796 connections = array.get_array_connections(
1797 context_names=[module.params["context"]], total_item_count=True
1798 )
1799 else:
1800 connections = array.get_array_connections(total_item_count=True)
1801 if connections.status_code != 200:
1802 module.fail_json(
1803 msg="Failed to get existing array connections. Error: {0}".format(
1804 connections.errors[0].message
1805 )
1806 )
1807 if connections.total_item_count == 0:
1808 module.fail_json(
1809 msg="No target arrays connected to source array - preferred arrays not possible."
1810 )
1811 else:
1812 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1813 all_connected_arrays = list(
1814 array.get_array_connections(
1815 context_names=[module.params["context"]]
1816 ).items
1817 )
1818 else:
1819 all_connected_arrays = list(array.get_array_connections().items)
1820 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
1821 current_arrays = [
1822 list(
1823 array.get_arrays(
1824 context_names=[module.params["context"]]
1825 ).items
1826 )[0].name
1827 ]
1828 else:
1829 current_arrays = [list(array.get_arrays().items)[0].name]
1830 for current_array in all_connected_arrays:
1831 if current_array.type == "sync-replication":
1832 current_arrays.append(current_array.name)
1833 for array_to_connect in module.params["preferred_array"]:
1834 if array_to_connect not in current_arrays:
1835 module.fail_json(
1836 msg="Array {0} is not a synchronously connected array.".format(
1837 module.params["preferred_array"][array_to_connect]
1838 )
1839 )
1840
1841 if (
1842 host is None
1843 and state == "present"
1844 and not module.params["rename"]
1845 and not module.params["move"]
1846 ):
1847 make_host(module, array)
1848 elif host is None and state == "present" and module.params["rename"]:
1849 module.exit_json(changed=False)
1850 elif host and state == "present" and not module.params["move"]:
1851 update_host(module, array)
1852 elif host and state == "present" and module.params["move"]:
1853 move_host(module, array)
1854 elif host and state == "absent" and module.params["volume"] is not None:
1855 update_host(module, array)
1856 elif host and state == "absent" and not module.params["volume"]:
1857 delete_host(module, array)
1858 elif host is None and state == "absent":
1859 module.exit_json(changed=False)
1860
1861 module.exit_json(changed=False)
1862
1863
1864 if __name__ == "__main__":
1865 main()