Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (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_pgsnap
20 version_added: '1.0.0'
21 short_description: Manage protection group snapshots on Pure Storage FlashArrays
22 description:
23 - Create or delete protection group snapshots on Pure Storage FlashArray.
24 - Recovery of replicated snapshots on the replica target array is enabled.
25 - Support for ActiveCluster and Volume Group protection groups is supported.
26 author:
27 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
28 options:
29 name:
30 description:
31 - The name of the source protection group.
32 type: str
33 required: true
34 suffix:
35 description:
36 - Suffix of snapshot name.
37 - Special case. If I(latest) the module will select the latest snapshot created in the group
38 type: str
39 state:
40 description:
41 - Define whether the protection group snapshot should exist or not.
42 Copy (added in 2.7) will create a full read/write clone of the
43 snapshot.
44 type: str
45 choices: [ absent, present, copy, rename ]
46 default: present
47 eradicate:
48 description:
49 - Define whether to eradicate the snapshot on delete or leave in trash.
50 type: bool
51 default: false
52 restore:
53 description:
54 - Restore a specific volume from a protection group snapshot.
55 - The protection group name is not required. Only provide the name of the
56 volume to be restored.
57 type: str
58 overwrite:
59 description:
60 - Define whether to overwrite the target volume if it already exists.
61 type: bool
62 default: false
63 target:
64 description:
65 - Volume to restore a specified volume to.
66 - If not supplied this will default to the volume defined in I(restore)
67 - Name of new snapshot suffix if renaming a snapshot
68 type: str
69 offload:
70 description:
71 - Name of offload target on which the snapshot exists.
72 - This is only applicable for deletion and erasure of snapshots
73 type: str
74 now:
75 description:
76 - Whether to initiate a snapshot of the protection group immediately
77 type: bool
78 default: false
79 apply_retention:
80 description:
81 - Apply retention schedule settings to the snapshot
82 type: bool
83 default: false
84 remote:
85 description:
86 - Force immediate snapshot to remote targets
87 type: bool
88 default: false
89 throttle:
90 description:
91 - If set to true, allows snapshot to fail if array health is not optimal.
92 type: bool
93 default: false
94 version_added: '1.21.0'
95 with_default_protection:
96 description:
97 - Whether to add the default container protection groups to
98 those specified in I(add_to_pgs) as the initial protection
99 of a volume created from a snapshot.
100 type: bool
101 default: true
102 version_added: '1.27.0'
103 add_to_pgs:
104 description:
105 - A volume created from a snapshot will be added to the specified
106 protection groups
107 type: list
108 elements: str
109 version_added: '1.27.0'
110 context:
111 description:
112 - Name of fleet member on which to perform the operation.
113 - This requires the array receiving the request is a member of a fleet
114 and the context name to be a member of the same fleet.
115 type: str
116 default: ""
117 version_added: '1.33.0'
118 extends_documentation_fragment:
119 - purestorage.flasharray.purestorage.fa
120 """
121
122 EXAMPLES = r"""
123 - name: Create protection group snapshot foo.ansible
124 purestorage.flasharray.purefa_pgsnap:
125 name: foo
126 suffix: ansible
127 fa_url: 10.10.10.2
128 api_token: e31060a7-21fc-e277-6240-25983c6c4592
129 state: present
130
131 - name: Delete and eradicate protection group snapshot named foo.snap
132 purestorage.flasharray.purefa_pgsnap:
133 name: foo
134 suffix: snap
135 eradicate: true
136 fa_url: 10.10.10.2
137 api_token: e31060a7-21fc-e277-6240-25983c6c4592
138 state: absent
139
140 - name: Restore volume data from local protection group snapshot named foo.snap to volume data2
141 purestorage.flasharray.purefa_pgsnap:
142 name: foo
143 suffix: snap
144 restore: data
145 target: data2
146 overwrite: true
147 with_default_protection: false
148 fa_url: 10.10.10.2
149 api_token: e31060a7-21fc-e277-6240-25983c6c4592
150 state: copy
151
152 - name: Restore remote protection group snapshot arrayA:pgname.snap.data to local copy
153 purestorage.flasharray.purefa_pgsnap:
154 name: arrayA:pgname
155 suffix: snap
156 restore: data
157 fa_url: 10.10.10.2
158 api_token: e31060a7-21fc-e277-6240-25983c6c4592
159 state: copy
160
161 - name: Restore AC pod protection group snapshot pod1::pgname.snap.data to pod1::data2
162 purestorage.flasharray.purefa_pgsnap:
163 name: pod1::pgname
164 suffix: snap
165 restore: data
166 target: pod1::data2
167 fa_url: 10.10.10.2
168 api_token: e31060a7-21fc-e277-6240-25983c6c4592
169 state: copy
170
171 - name: Create snapshot of existing pgroup foo with suffix and force immediate copy to remote targets
172 purestorage.flasharray.purefa_pgsnap:
173 name: pgname
174 suffix: force
175 now: true
176 apply_retention: true
177 remote: true
178 fa_url: 10.10.10.2
179 api_token: e31060a7-21fc-e277-6240-25983c6c4592
180
181 - name: Delete and eradicate snapshot named foo.snap on offload target bar from arrayA
182 purestorage.flasharray.purefa_pgsnap:
183 name: "arrayA:foo"
184 suffix: snap
185 offload: bar
186 eradicate: true
187 fa_url: 10.10.10.2
188 api_token: e31060a7-21fc-e277-6240-25983c6c4592
189 state: absent
190
191 - name: Rename protection group snapshot foo.fred to foo.dave
192 purestorage.flasharray.purefa_pgsnap:
193 name: foo
194 suffix: fred
195 target: dave
196 fa_url: 10.10.10.2
197 api_token: e31060a7-21fc-e277-6240-25983c6c4592
198 state: rename
199 """
200
201 RETURN = r"""
202 snapshot:
203 description: Suffix of the created protection group snapshot.
204 type: str
205 returned: success
206 """
207
208 HAS_PURESTORAGE = True
209 try:
210 from pypureclient.flasharray import (
211 ProtectionGroupSnapshot,
212 ProtectionGroupSnapshotPatch,
213 VolumePost,
214 Reference,
215 FixedReference,
216 DestroyedPatchPost,
217 )
218 except ImportError:
219 HAS_PURESTORAGE = False
220
221 import re
222 from ansible.module_utils.basic import AnsibleModule
223 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
224 get_array,
225 purefa_argument_spec,
226 )
227 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
228 LooseVersion,
229 )
230
231 from datetime import datetime
232
233 THROTTLE_API = "2.25"
234 DEFAULT_API = "2.16"
235 CONTEXT_API_VERSION = "2.38"
236
237
238 def _check_offload(module, array):
239 api_version = array.get_rest_version()
240 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
241 res = array.get_offloads(
242 names=[module.params["offload"]], context_names=[module.params["context"]]
243 )
244 else:
245 res = array.get_offloads(names=[module.params["offload"]])
246 if res.status_code == 200:
247 return bool(list(res.items)[0].status == "connected")
248 return False
249
250
251 def get_pgroup(module, array):
252 """Return Protection Group"""
253 api_version = array.get_rest_version()
254 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
255 return bool(
256 array.get_protection_groups(
257 names=[module.params["name"]], context_names=[module.params["context"]]
258 ).status_code
259 == 200
260 )
261 return bool(
262 array.get_protection_groups(names=[module.params["name"]]).status_code == 200
263 )
264
265
266 def get_pgroupvolume(module, array):
267 """Return Protection Group Volume or None"""
268 api_version = array.get_rest_version()
269 try:
270 volumes = []
271 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
272 pgroup = list(
273 array.get_protection_groups(
274 names=[module.params["name"]],
275 context_names=[module.params["context"]],
276 ).items
277 )[0]
278 else:
279 pgroup = list(
280 array.get_protection_groups(names=[module.params["name"]]).items
281 )[0]
282 if pgroup.host_count > 0: # We have a host PG
283 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
284 host_dict = list(
285 array.get_protection_groups_hosts(
286 context_names=[module.params["context"]],
287 group_names=[module.params["name"]],
288 ).items
289 )
290 else:
291 host_dict = list(
292 array.get_protection_groups_hosts(
293 group_names=[module.params["name"]]
294 ).items
295 )
296 for host in host_dict:
297 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
298 hostvols = list(
299 array.get_connections(
300 context_names=[module.params["context"]],
301 host_names=[host.member["name"]],
302 ).items
303 )
304 else:
305 hostvols = list(
306 array.get_connections(host_names=[host.member["name"]]).items
307 )
308 for hvol in hostvols:
309 volumes.append(hvol.volume["name"])
310 elif pgroup.host_group_count > 0: # We have a hostgroup PG
311 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
312 hgroup_dict = list(
313 array.get_protection_groups_host_groups(
314 context_names=[module.params["context"]],
315 group_names=[module.params["name"]],
316 ).items
317 )
318 else:
319 hgroup_dict = list(
320 array.get_protection_groups_host_groups(
321 group_names=[module.params["name"]]
322 ).items
323 )
324 # First check if there are any volumes in the host groups
325 for hgentry in hgroup_dict:
326 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
327 hgvols = list(
328 array.get_connections(
329 context_names=[module.params["context"]],
330 host_group_names=[hgentry.member["name"]],
331 ).items
332 )
333 else:
334 hgvols = list(
335 array.get_connections(
336 host_group_names=[hgentry.member["name"]]
337 ).items
338 )
339 for hgvol in hgvols:
340 volumes.append(hgvol.volume["name"])
341 # Second check for host specific volumes
342 for hgroup in hgroup_dict:
343 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
344 hg_hosts = list(
345 array.get_host_groups_hosts(
346 context_names=[module.params["context"]],
347 group_names=[hgroup.member["name"]],
348 ).items
349 )
350 else:
351 hg_hosts = list(
352 array.get_host_groups_hosts(
353 group_names=[hgroup.member["name"]]
354 ).items
355 )
356 for hg_host in hg_hosts:
357 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
358 host_vols = list(
359 array.get_connections(
360 context_names=[module.params["context"]],
361 host_names=[hg_host.member["name"]],
362 ).items
363 )
364 else:
365 host_vols = list(
366 array.get_connections(
367 host_names=[hg_host.member["name"]]
368 ).items
369 )
370 for host_vol in host_vols:
371 volumes.append(host_vol.volume["name"])
372 else: # We have a volume PG
373 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
374 vol_dict = list(
375 array.get_protection_groups_volumes(
376 context_names=[module.params["context"]],
377 group_names=[module.params["name"]],
378 ).items
379 )
380 else:
381 vol_dict = list(
382 array.get_protection_groups_volumes(
383 group_names=[module.params["name"]]
384 ).items
385 )
386 for entry in vol_dict:
387 volumes.append(entry.member["name"])
388 volumes = list(set(volumes))
389 if "::" in module.params["name"]:
390 restore_volume = (
391 module.params["name"].split("::")[0] + "::" + module.params["restore"]
392 )
393 else:
394 restore_volume = module.params["restore"]
395 for volume in volumes:
396 if volume == restore_volume:
397 return volume
398 except Exception:
399 return None
400
401
402 def get_rpgsnapshot(module, array):
403 """Return Replicated Snapshot or None"""
404 api_version = array.get_rest_version()
405 snapname = (
406 module.params["name"]
407 + "."
408 + module.params["suffix"]
409 + "."
410 + module.params["restore"]
411 )
412 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
413 res = array.get_volume_snapshots(
414 names=[snapname], context_names=[module.params["context"]]
415 )
416 else:
417 res = array.get_volume_snapshots(names=[snapname])
418 if res.status_code == 200:
419 return snapname
420 return None
421
422
423 def get_pgsnapshot(module, array):
424 """Return Snapshot (active or deleted) or None"""
425 api_version = array.get_rest_version()
426 snapname = module.params["name"] + "." + module.params["suffix"]
427 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
428 res = array.get_protection_group_snapshots(
429 names=[snapname], context_names=[module.params["context"]]
430 )
431 else:
432 res = array.get_protection_group_snapshots(names=[snapname])
433 if res.status_code == 200:
434 return list(res.items)[0]
435 return None
436
437
438 def create_pgsnapshot(module, array):
439 """Create Protection Group Snapshot"""
440 api_version = array.get_rest_version()
441 snap_data = None
442 changed = True
443 if not module.check_mode:
444 suffix = ProtectionGroupSnapshot(suffix=module.params["suffix"])
445 if LooseVersion(THROTTLE_API) >= LooseVersion(api_version):
446 if (
447 list(array.get_protection_groups(names=[module.params["name"]]).items)[
448 0
449 ].target_count
450 > 0
451 ):
452 if module.params["now"]:
453 res = array.post_protection_group_snapshots(
454 source_names=[module.params["name"]],
455 apply_retention=module.params["apply_retention"],
456 replicate_now=True,
457 protection_group_snapshot=suffix,
458 )
459 else:
460 res = array.post_protection_group_snapshots(
461 source_names=[module.params["name"]],
462 apply_retention=module.params["apply_retention"],
463 protection_group_snapshot=suffix,
464 replicate=module.params["remote"],
465 )
466 else:
467 res = array.post_protection_group_snapshots(
468 source_names=[module.params["name"]],
469 apply_retention=module.params["apply_retention"],
470 protection_group_snapshot=suffix,
471 )
472 else:
473 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
474 remote_target = (
475 list(
476 array.get_protection_groups(
477 names=[module.params["name"]],
478 context_names=[module.params["context"]],
479 ).items
480 )[0].target_count
481 > 0
482 )
483 else:
484 remote_target = (
485 list(
486 array.get_protection_groups(names=[module.params["name"]]).items
487 )[0].target_count
488 > 0
489 )
490 if remote_target:
491 if module.params["now"]:
492 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
493 res = array.post_protection_group_snapshots(
494 source_names=[module.params["name"]],
495 apply_retention=module.params["apply_retention"],
496 replicate_now=True,
497 allow_throttle=module.params["throttle"],
498 protection_group_snapshot=suffix,
499 context_names=[module.params["context"]],
500 )
501 else:
502 res = array.post_protection_group_snapshots(
503 source_names=[module.params["name"]],
504 apply_retention=module.params["apply_retention"],
505 replicate_now=True,
506 allow_throttle=module.params["throttle"],
507 protection_group_snapshot=suffix,
508 )
509 else:
510 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
511 res = array.post_protection_group_snapshots(
512 source_names=[module.params["name"]],
513 apply_retention=module.params["apply_retention"],
514 allow_throttle=module.params["throttle"],
515 protection_group_snapshot=suffix,
516 replicate=module.params["remote"],
517 context_names=[module.params["context"]],
518 )
519 else:
520 res = array.post_protection_group_snapshots(
521 source_names=[module.params["name"]],
522 apply_retention=module.params["apply_retention"],
523 allow_throttle=module.params["throttle"],
524 protection_group_snapshot=suffix,
525 replicate=module.params["remote"],
526 )
527 else:
528 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
529 res = array.post_protection_group_snapshots(
530 source_names=[module.params["name"]],
531 apply_retention=module.params["apply_retention"],
532 allow_throttle=module.params["throttle"],
533 protection_group_snapshot=suffix,
534 context_names=[module.params["context"]],
535 )
536 else:
537 res = array.post_protection_group_snapshots(
538 source_names=[module.params["name"]],
539 apply_retention=module.params["apply_retention"],
540 allow_throttle=module.params["throttle"],
541 protection_group_snapshot=suffix,
542 )
543
544 if res.status_code != 200:
545 module.fail_json(
546 msg="Snapshot of pgroup {0} failed. Error: {1}".format(
547 module.params["name"], res.errors[0].message
548 )
549 )
550 else:
551 snap_data = list(res.items)[0]
552 module.exit_json(
553 changed=changed,
554 suffix=snap_data.suffix,
555 )
556
557
558 def restore_pgsnapvolume(module, array):
559 """Restore a Protection Group Snapshot Volume"""
560 api_version = array.get_rest_version()
561 changed = True
562 if module.params["suffix"] == "latest":
563 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
564 latest_snapshot = list(
565 array.get_protection_group_snapshots(
566 names=[module.params["name"]],
567 context_names=[module.params["context"]],
568 ).items
569 )[-1].suffix
570 else:
571 latest_snapshot = list(
572 array.get_protection_group_snapshots(
573 names=[module.params["name"]]
574 ).items
575 )[-1].suffix
576 module.params["suffix"] = latest_snapshot
577 if ":" in module.params["name"] and "::" not in module.params["name"]:
578 if get_rpgsnapshot(module, array) is None:
579 module.fail_json(
580 msg="Selected restore snapshot {0} does not exist in the Protection Group".format(
581 module.params["restore"]
582 )
583 )
584 else:
585 if get_pgroupvolume(module, array) is None:
586 module.fail_json(
587 msg="Selected restore volume {0} does not exist in the Protection Group".format(
588 module.params["restore"]
589 )
590 )
591 source_volume = (
592 module.params["name"]
593 + "."
594 + module.params["suffix"]
595 + "."
596 + module.params["restore"]
597 )
598 if "::" in module.params["target"]:
599 target_pod_name = module.params["target"].split(":")[0]
600 if "::" in module.params["name"]:
601 source_pod_name = module.params["name"].split(":")[0]
602 else:
603 source_pod_name = ""
604 if source_pod_name != target_pod_name:
605 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
606 if (
607 list(
608 array.get_pods(
609 names=[target_pod_name],
610 context_names=[module.params["context"]],
611 ).items
612 )[0].array_count
613 > 1
614 ):
615 module.fail_json(msg="Volume cannot be restored to a stretched pod")
616 else:
617 if (
618 list(array.get_pods(names=[target_pod_name]).items)[0].array_count
619 > 1
620 ):
621 module.fail_json(msg="Volume cannot be restored to a stretched pod")
622 if not module.check_mode:
623 if LooseVersion(DEFAULT_API) <= LooseVersion(array.get_rest_version()):
624 if module.params["add_to_pgs"]:
625 add_to_pgs = []
626 for add_pg in module.params["add_to_pgs"]:
627 add_to_pgs.append(FixedReference(name=add_pg))
628 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
629 res = array.post_volumes(
630 names=[module.params["target"]],
631 volume=VolumePost(source=Reference(name=source_volume)),
632 with_default_protection=module.params[
633 "with_default_protection"
634 ],
635 add_to_protection_groups=add_to_pgs,
636 context_names=[module.params["context"]],
637 )
638 else:
639 res = array.post_volumes(
640 names=[module.params["target"]],
641 volume=VolumePost(source=Reference(name=source_volume)),
642 with_default_protection=module.params[
643 "with_default_protection"
644 ],
645 add_to_protection_groups=add_to_pgs,
646 )
647 else:
648 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
649 if module.params["overwrite"]:
650 res = array.post_volumes(
651 names=[module.params["target"]],
652 volume=VolumePost(source=Reference(name=source_volume)),
653 overwrite=module.params["overwrite"],
654 context_names=[module.params["context"]],
655 )
656 else:
657 res = array.post_volumes(
658 names=[module.params["target"]],
659 volume=VolumePost(source=Reference(name=source_volume)),
660 overwrite=module.params["overwrite"],
661 )
662 else:
663 if module.params["overwrite"]:
664 res = array.post_volumes(
665 names=[module.params["target"]],
666 volume=VolumePost(source=Reference(name=source_volume)),
667 overwrite=module.params["overwrite"],
668 )
669 else:
670 res = array.post_volumes(
671 names=[module.params["target"]],
672 volume=VolumePost(source=Reference(name=source_volume)),
673 with_default_protection=module.params[
674 "with_default_protection"
675 ],
676 )
677 else:
678 res = array.post_volumes(
679 names=[module.params["target"]],
680 overwrite=module.params["overwrite"],
681 volume=VolumePost(source=Reference(name=source_volume)),
682 )
683 if res.status_code != 200:
684 module.fail_json(
685 msg="Failed to restore {0} from pgroup {1}. Error: {2}".format(
686 module.params["restore"],
687 module.params["name"],
688 res.errors[0].message,
689 )
690 )
691 module.exit_json(changed=changed)
692
693
694 def delete_offload_snapshot(module, array):
695 """Delete Offloaded Protection Group Snapshot"""
696 changed = False
697 api_version = array.get_rest_version()
698 snapname = module.params["name"] + "." + module.params["suffix"]
699 if ":" in module.params["name"] and module.params["offload"]:
700 if _check_offload(module, array):
701 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
702 res = array.get_remote_protection_group_snapshots(
703 names=[snapname],
704 on=module.params["offload"],
705 context_names=[module.params["context"]],
706 )
707 else:
708 res = array.get_remote_protection_group_snapshots(
709 names=[snapname], on=module.params["offload"]
710 )
711 if res.status_code != 200:
712 module.fail_json(
713 msg="Offload snapshot {0} does not exist on {1}".format(
714 snapname, module.params["offload"]
715 )
716 )
717
718 rpg_destroyed = list(res.items)[0].destroyed
719 if not module.check_mode:
720 if not rpg_destroyed:
721 changed = True
722 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
723 res = array.patch_remote_protection_group_snapshots(
724 names=[snapname],
725 on=module.params["offload"],
726 remote_protection_group_snapshot=DestroyedPatchPost(
727 destroyed=True
728 ),
729 context_names=[module.params["context"]],
730 )
731 else:
732 res = array.patch_remote_protection_group_snapshots(
733 names=[snapname],
734 on=module.params["offload"],
735 remote_protection_group_snapshot=DestroyedPatchPost(
736 destroyed=True
737 ),
738 )
739 if res.status_code != 200:
740 module.fail_json(
741 msg="Failed to delete offloaded snapshot {0} on target {1}. Error: {2}".format(
742 snapname,
743 module.params["offload"],
744 res.errors[0].message,
745 )
746 )
747 if module.params["eradicate"]:
748 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(
749 api_version
750 ):
751 res = array.delete_remote_protection_group_snapshots(
752 names=[snapname],
753 on=module.params["offload"],
754 context_names=[module.params["context"]],
755 )
756 else:
757 res = array.delete_remote_protection_group_snapshots(
758 names=[snapname], on=module.params["offload"]
759 )
760 if res.status_code != 200:
761 module.fail_json(
762 msg="Failed to eradicate offloaded snapshot {0} on target {1}. Error: {2}".format(
763 snapname,
764 module.params["offload"],
765 res.errors[0].message,
766 )
767 )
768 else:
769 if module.params["eradicate"]:
770 changed = True
771 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(
772 api_version
773 ):
774 res = array.delete_remote_protection_group_snapshots(
775 names=[snapname],
776 on=module.params["offload"],
777 context_names=[module.params["context"]],
778 )
779 else:
780 res = array.delete_remote_protection_group_snapshots(
781 names=[snapname], on=module.params["offload"]
782 )
783 if res.status_code != 200:
784 module.fail_json(
785 msg="Failed to eradicate offloaded snapshot {0} on target {1}. Error: {2}".format(
786 snapname,
787 module.params["offload"],
788 res.errors[0].message,
789 )
790 )
791 else:
792 module.fail_json(
793 msg="Offload target {0} does not exist or not connected".format(
794 module.params["offload"]
795 )
796 )
797 else:
798 module.fail_json(msg="Protection Group name not in the correct format")
799
800 module.exit_json(changed=changed)
801
802
803 def delete_pgsnapshot(module, array):
804 """Delete Protection Group Snapshot"""
805 changed = True
806 api_version = array.get_rest_version()
807 if not module.check_mode:
808 snapname = module.params["name"] + "." + module.params["suffix"]
809 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
810 res = array.patch_protection_group_snapshots(
811 names=[snapname],
812 protection_group_snapshot=ProtectionGroupSnapshotPatch(destroyed=True),
813 context_names=[module.params["context"]],
814 )
815 else:
816 res = array.patch_protection_group_snapshots(
817 names=[snapname],
818 protection_group_snapshot=ProtectionGroupSnapshotPatch(destroyed=True),
819 )
820 if res.status_code != 200:
821 module.fail_json(
822 msg="Failed to delete pgroup {0}. Error {1}".format(
823 snapname, res.errors[0].message
824 )
825 )
826 if module.params["eradicate"]:
827 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
828 res = array.delete_protection_group_snapshots(
829 names=[snapname], context_names=[module.params["context"]]
830 )
831 else:
832 res = array.delete_protection_group_snapshots(names=[snapname])
833 if res.status_code != 200:
834 module.fail_json(
835 msg="Failed to delete pgroup {0}. Error {1}".format(
836 snapname, res.errors[0].message
837 )
838 )
839 module.exit_json(changed=changed)
840
841
842 def eradicate_pgsnapshot(module, array):
843 """Eradicate Protection Group Snapshot"""
844 changed = True
845 api_version = array.get_rest_version()
846 if not module.check_mode:
847 snapname = module.params["name"] + "." + module.params["suffix"]
848 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
849 res = array.delete_protection_group_snapshots(
850 names=[snapname], context_names=[module.params["context"]]
851 )
852 else:
853 res = array.delete_protection_group_snapshots(names=[snapname])
854 if res.status_code != 200:
855 module.fail_json(
856 msg="Failed to delete pgroup {0}. Error {1}".format(
857 snapname, res.errors[0].message
858 )
859 )
860 module.exit_json(changed=changed)
861
862
863 def update_pgsnapshot(module, array):
864 """Update Protection Group Snapshot - basically just rename..."""
865 changed = True
866 api_version = array.get_rest_version()
867 if not module.check_mode:
868 current_name = module.params["name"] + "." + module.params["suffix"]
869 new_name = module.params["name"] + "." + module.params["target"]
870 if LooseVersion(CONTEXT_API_VERSION) <= LooseVersion(api_version):
871 res = array.patch_protection_group_snapshots(
872 names=[current_name],
873 protection_group_snapshot=ProtectionGroupSnapshotPatch(name=new_name),
874 context_names=[module.params["context"]],
875 )
876 else:
877 res = array.patch_protection_group_snapshots(
878 names=[current_name],
879 protection_group_snapshot=ProtectionGroupSnapshotPatch(name=new_name),
880 )
881 if res.status_code != 200:
882 module.fail_json(
883 msg="Failed to rename {0} to {1}. Error: {2}".format(
884 current_name, new_name, res.errors[0].message
885 )
886 )
887 module.exit_json(changed=changed)
888
889
890 def main():
891 argument_spec = purefa_argument_spec()
892 argument_spec.update(
893 dict(
894 name=dict(type="str", required=True),
895 suffix=dict(type="str"),
896 restore=dict(type="str"),
897 offload=dict(type="str"),
898 throttle=dict(type="bool", default=False),
899 overwrite=dict(type="bool", default=False),
900 target=dict(type="str"),
901 eradicate=dict(type="bool", default=False),
902 now=dict(type="bool", default=False),
903 apply_retention=dict(type="bool", default=False),
904 remote=dict(type="bool", default=False),
905 state=dict(
906 type="str",
907 default="present",
908 choices=["absent", "present", "copy", "rename"],
909 ),
910 with_default_protection=dict(type="bool", default=True),
911 add_to_pgs=dict(type="list", elements="str"),
912 context=dict(type="str", default=""),
913 )
914 )
915
916 required_if = [("state", "copy", ["suffix", "restore"])]
917 mutually_exclusive = [
918 ["now", "remote"],
919 ]
920
921 module = AnsibleModule(
922 argument_spec,
923 required_if=required_if,
924 mutually_exclusive=mutually_exclusive,
925 supports_check_mode=True,
926 )
927 if not HAS_PURESTORAGE:
928 module.fail_json(msg="py-pure-client sdk is not installed")
929 state = module.params["state"]
930 pattern = re.compile("^(?=.*[a-zA-Z-])[a-zA-Z0-9]([a-zA-Z0-9-]{0,63}[a-zA-Z0-9])?$")
931 if state == "present":
932 if module.params["suffix"] is None:
933 suffix = "snap-" + str(
934 (datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds()
935 )
936 module.params["suffix"] = suffix.replace(".", "")
937 else:
938 if module.params["restore"]:
939 pattern = re.compile(
940 "^[0-9]{0,63}$|^(?=.*[a-zA-Z-])[a-zA-Z0-9]([a-zA-Z0-9-]{0,63}[a-zA-Z0-9])?$"
941 )
942 if not pattern.match(module.params["suffix"]):
943 module.fail_json(
944 msg="Suffix name {0} does not conform to suffix name rules".format(
945 module.params["suffix"]
946 )
947 )
948
949 if not module.params["target"] and module.params["restore"]:
950 module.params["target"] = module.params["restore"]
951
952 if state == "rename" and module.params["target"] is not None:
953 if not pattern.match(module.params["target"]):
954 module.fail_json(
955 msg="Suffix target {0} does not conform to suffix name rules".format(
956 module.params["target"]
957 )
958 )
959 array = get_array(module)
960 pgroup = get_pgroup(module, array)
961 if not pgroup:
962 module.fail_json(
963 msg="Protection Group {0} does not exist.".format(module.params["name"])
964 )
965 pgsnap = get_pgsnapshot(module, array)
966 if pgsnap:
967 pgsnap_deleted = pgsnap.destroyed
968 if state != "absent" and module.params["offload"]:
969 module.fail_json(
970 msg="offload parameter not supported for state {0}".format(state)
971 )
972 elif state == "copy":
973 if module.params["overwrite"] and (
974 module.params["add_to_pgs"] or module.params["with_default_protection"]
975 ):
976 module.fail_json(
977 msg="overwrite and add_to_pgs or with_default_protection are incompatible"
978 )
979 restore_pgsnapvolume(module, array)
980 elif state == "present" and not pgsnap:
981 create_pgsnapshot(module, array)
982 elif state == "present" and pgsnap:
983 module.exit_json(changed=False)
984 elif (
985 state == "absent" and module.params["offload"] and get_pgsnapshot(module, array)
986 ):
987 delete_offload_snapshot(module, array)
988 elif state == "rename" and pgsnap:
989 update_pgsnapshot(module, array)
990 elif state == "absent" and pgsnap and not pgsnap_deleted:
991 delete_pgsnapshot(module, array)
992 elif state == "absent" and pgsnap and pgsnap_deleted and module.params["eradicate"]:
993 eradicate_pgsnapshot(module, array)
994 elif state == "absent" and not pgsnap:
995 module.exit_json(changed=False)
996
997 module.exit_json(changed=False)
998
999
1000 if __name__ == "__main__":
1001 main()