Debian Codegraph @

ansible_collections/purestorage/flashblade/plugins/modules/purefb_policy.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2020, 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: purefb_policy
20 version_added: '1.0.0'
21 short_description: Manage FlashBlade policies
22 description:
23 - Manage policies for filesystem, file replica links and object store access.
24 - To update an existing snapshot policy rule, you must first delete the
25 original rule and then add the new rule to replace it. Purity's best-fit
26 will try to ensure that any required snapshots deleted on the deletion of
27 the first rule will be recovered as long replacement rule is added before
28 the snapshot eradication period is exceeded (usuually 24 hours).
29 author:
30 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
31 options:
32 state:
33 description:
34 - Create or delete policy.
35 - Copy is applicable only to Object Store Access Policies Rules
36 default: present
37 type: str
38 choices: [ absent, present, copy ]
39 target:
40 description:
41 - Name of policy to copy rule to
42 type: str
43 version_added: "1.9.0"
44 target_rule:
45 description:
46 - Name of the rule to copy the exisitng rule to.
47 - If not defined the existing rule name is used.
48 type: str
49 version_added: "1.9.0"
50 policy_type:
51 description:
52 - Type of policy
53 default: snapshot
54 type: str
55 choices: [ snapshot, access, nfs, smb_share, smb_client, network, worm ]
56 version_added: "1.9.0"
57 account:
58 description:
59 - Name of Object Store account policy applies to.
60 - B(Special Case) I(pure policy) is used for the system-wide S3 policies
61 type: str
62 version_added: "1.9.0"
63 rule:
64 description:
65 - Name of the rule for the Object Store Access Policy
66 - Rules in system wide policies cannot be deleted or modified
67 type: str
68 version_added: "1.9.0"
69 effect:
70 description:
71 - Allow S3 requests that match all of the I(actions) item selected.
72 Rules are additive.
73 type: str
74 default: allow
75 choices: [ allow, deny ]
76 version_added: "1.9.0"
77 actions:
78 description:
79 - List of permissions to grant.
80 - System-wide policy rules cannot be deleted or modified
81 type: list
82 elements: str
83 choices:
84 - s3:*
85 - s3:AbortMultipartUpload
86 - s3:BypassGovernanceRetention
87 - s3:CreateBucket
88 - s3:DeleteBucket
89 - s3:DeleteObject
90 - s3:DeleteObjectVersion
91 - s3:ExtendSafemodeRetentionPeriod
92 - s3:GetBucketAcl
93 - s3:GetBucketLocation
94 - s3:GetBucketVersioning
95 - s3:GetLifecycleConfiguration
96 - s3:GetObject
97 - s3:GetObjectAcl
98 - s3:GetObjectLegalHold
99 - s3:GetObjectLockConfiguration
100 - s3:GetObjectRetention
101 - s3:GetObjectTagging
102 - s3:GetObjectVersion
103 - s3:GetObjectVersionTagging
104 - s3:ListAllMyBuckets
105 - s3:ListBucket
106 - s3:ListBucketMultipartUploads
107 - s3:ListBucketVersions
108 - s3:ListMultipartUploadParts
109 - s3:PutBucketVersioning
110 - s3:PutLifecycleConfiguration
111 - s3:PutObject
112 - s3:PutObjectLegalHold
113 - s3:PutObjectLockConfiguration
114 - s3:PutObjectRetention
115 - s3:ResolveSafemodeConflicts
116 version_added: "1.9.0"
117 object_resources:
118 description:
119 - List of bucket names and object paths, with a wildcard (*) to
120 specify objects in a bucket; e.g., bucket1, bucket1/*, bucket2,
121 bucket2/*.
122 - System-wide policy rules cannot be deleted or modified
123 type: list
124 elements: str
125 version_added: "1.9.0"
126 source_ips:
127 description:
128 - List of IPs and subnets from which this rule should allow requests;
129 e.g., 10.20.30.40, 10.20.30.0/24, 2001:DB8:1234:5678::/64.
130 - System-wide policy rules cannot be deleted or modified
131 type: list
132 elements: str
133 version_added: "1.9.0"
134 s3_prefixes:
135 description:
136 - List of 'folders' (object key prefixes) for which object listings
137 may be requested.
138 - System-wide policy rules cannot be deleted or modified
139 type: list
140 elements: str
141 version_added: "1.9.0"
142 s3_delimiters:
143 description:
144 - List of delimiter characters allowed in object list requests.
145 - Grants permissions to list 'folder names' (prefixes ending in a
146 delimiter) instead of object keys.
147 - System-wide policy rules cannot be deleted or modified
148 type: list
149 elements: str
150 version_added: "1.9.0"
151 ignore_enforcement:
152 description:
153 - Certain combinations of actions and other rule elements are inherently
154 ignored if specified together in a rule.
155 - If set to true, operations which attempt to set these combinations will fail.
156 - If set to false, such operations will instead be allowed.
157 type: bool
158 default: true
159 version_added: "1.9.0"
160 user:
161 description:
162 - User in the I(account) that the policy is granted to.
163 type: str
164 version_added: "1.9.0"
165 force_delete:
166 description:
167 - Force the deletion of a Object Store Access Policy is this
168 has attached users.
169 - WARNING This can have undesired side-effects.
170 - System-wide policies cannot be deleted
171 type: bool
172 default: false
173 version_added: "1.9.0"
174 name:
175 description:
176 - Name of the policy
177 type: str
178 enabled:
179 description:
180 - State of policy
181 type: bool
182 default: true
183 every:
184 description:
185 - Interval between snapshots in seconds
186 - Range available 300 - 31536000 (equates to 5m to 365d)
187 type: int
188 keep_for:
189 description:
190 - How long to keep snapshots for
191 - Range available 300 - 31536000 (equates to 5m to 365d)
192 - Must not be set less than I(every)
193 type: int
194 at:
195 description:
196 - Provide a time in 12-hour AM/PM format, eg. 11AM
197 type: str
198 timezone:
199 description:
200 - Time Zone used for the I(at) parameter
201 - If not provided, the module will attempt to get the current local timezone from the server
202 type: str
203 filesystem:
204 description:
205 - List of filesystems to add to a policy on creation
206 - To amend policy members use the I(purestorage.flashblade.purefb_fs) module
207 type: list
208 elements: str
209 replica_link:
210 description:
211 - List of filesystem replica links to add to a policy on creation
212 - To amend policy members use the I(purestorage.flashblade.purefb_fs_replica) module
213 type: list
214 elements: str
215 access:
216 description:
217 - Specifies access control for the export policy rule
218 type: str
219 choices: [ root-squash, all-squash, no-squash ]
220 default: root-squash
221 version_added: "1.9.0"
222 anonuid:
223 description:
224 - Any user whose UID is affected by an I(access) of `root_squash` or `all_squash`
225 will have their UID mapped to anonuid.
226 The default is null, which means 65534.
227 Use "" to clear.
228 type: str
229 version_added: "1.9.0"
230 anongid:
231 description:
232 - Any user whose GID is affected by an I(access) of `root_squash` or `all_squash`
233 will have their GID mapped to anongid.
234 The default anongid is null, which means 65534.
235 Use "" to clear.
236 type: str
237 version_added: "1.9.0"
238 atime:
239 description:
240 - After a read operation has occurred, the inode access time is updated only if any
241 of the following conditions is true; the previous access time is less than the
242 inode modify time, the previous access time is less than the inode change time,
243 or the previous access time is more than 24 hours ago.
244 - If set to false, disables the update of inode access times after read operations.
245 type: bool
246 default: true
247 version_added: "1.9.0"
248 client:
249 description:
250 - Specifies the clients that will be permitted to access the export.
251 - Accepted notation is a single IP address, subnet in CIDR notation, netgroup, or
252 anonymous (*).
253 type: str
254 version_added: "1.9.0"
255 fileid_32bit:
256 description:
257 - Whether the file id is 32 bits or not.
258 type: bool
259 default: false
260 version_added: "1.9.0"
261 permission:
262 description:
263 - Specifies which read-write client access permissions are allowed for the export.
264 type: str
265 choices: [ rw, ro ]
266 default: ro
267 version_added: "1.9.0"
268 secure:
269 description:
270 - If true, this prevents NFS access to client connections coming from non-reserved ports.
271 - If false, allows NFS access to client connections coming from non-reserved ports.
272 - Applies to NFSv3, NFSv4.1, and auxiliary protocols MOUNT and NLM.
273 type: bool
274 default: false
275 version_added: "1.9.0"
276 security:
277 description:
278 - The security flavors to use for accessing files on this mount point.
279 - If the server does not support the requested flavor, the mount operation fails.
280 - I(sys) trusts the client to specify users identity.
281 - I(krb) provides cryptographic proof of a users identity in each RPC request.
282 - I(krb5i) adds integrity checking to krb5, to ensure the data has not been tampered with.
283 - I(krb5p) adds integrity checking and encryption to krb5.
284 type: list
285 elements: str
286 choices: [ sys, krb5, krb5i, krb5p ]
287 default: sys
288 version_added: "1.9.0"
289 before_rule:
290 description:
291 - The index of the client rule to insert or move a client rule before.
292 type: int
293 version_added: "1.9.0"
294 rename:
295 description:
296 - New name for policy
297 - Only applies to NFS and SMB policies
298 type: str
299 version_added: "1.10.0"
300 destroy_snapshots:
301 description:
302 - This parameter must be set to true in order to modify a policy such that local or remote snapshots would be destroyed.
303 type: bool
304 version_added: '1.11.0'
305 default: false
306 principal:
307 description:
308 - The user or group who is the subject of this rule, and their domain
309 type: str
310 version_added: '1.12.0'
311 change:
312 description:
313 - The state of the SMB share principals Change access permission.
314 - Setting to "" will clear the current setting
315 type: str
316 choices: [ allow, deny, "" ]
317 version_added: '1.12.0'
318 read:
319 description:
320 - The state of the SMB share principals Read access permission.
321 - Setting to "" will clear the current setting
322 type: str
323 choices: [ allow, deny, "" ]
324 version_added: '1.12.0'
325 full_control:
326 description:
327 - The state of the SMB share principals Full Control access permission.
328 - Setting to "" will clear the current setting
329 type: str
330 choices: [ allow, deny, "" ]
331 version_added: '1.12.0'
332 smb_encryption:
333 description:
334 - The status of SMB encryption in a client policy rule
335 type: str
336 choices: [ disabled, optional, required ]
337 default: optional
338 version_added: '1.12.0'
339 desc:
340 description:
341 - A description of an object store policy,
342 optionally specified when the policy is created.
343 - Cannot be modified for an existing policy.
344 type: str
345 default: ""
346 version_added: '1.14.0'
347 interfaces:
348 description:
349 - Specifies which product interfaces the network access policy rule
350 applies to, whether it is permitting or denying access.
351 type: list
352 elements: str
353 choices: [ "management-ssh", "management-rest-api", "management-web-ui", "snmp", "local-network-superuser-password-access" ]
354 version_added: '1.17.0'
355 max_retention:
356 description:
357 - The maximum retention period of the WORM file system.
358 - Between 1 second and 100 years.
359 - Cannot be less than the I(min_retention).
360 - Valid values are weeks (w), days(d), hours(h), minutes(m) and seconds(s).
361 type: str
362 version_added: '1.19.0'
363 min_retention:
364 description:
365 - The minimum retention period of the WORM file system.
366 - Between 1 second and 100 years.
367 - Cannot be greater than the I(max_retention).
368 - Valid values are weeks (w), days(d), hours(h), minutes(m) and seconds(s).
369 type: str
370 version_added: '1.19.0'
371 default_retention:
372 description:
373 - The retention period used for committing files to WORM status.
374 Will be applied if no access time is provided, or the access time is less than the current server time.
375 Between I(min_retention) and I(max_retention) periods.
376 - Valid values are weeks (w), days(d), hours(h), minutes(m) and seconds(s).
377 type: str
378 version_added: '1.19.0'
379 retention_lock:
380 description:
381 - State of policy attributes after creation.
382 - If set to I(locked) then values of the policy attributes are not allowed to change.
383 - If set to I(locked) then values of the policy attributes can be changed.
384 - Changing from I(unlocked) to I(locked) is allowed, but to change from I(locked) to I(unlocked)
385 will require support from Pure Storage Technical Services.
386 type: str
387 choices: [ locked, unlocked ]
388 version_added: '1.19.0'
389 context:
390 description:
391 - Name of fleet member on which to perform the operation.
392 - This requires the array receiving the request is a member of a fleet
393 and the context name to be a member of the same fleet.
394 type: str
395 default: ""
396 version_added: "1.22.0"
397 extends_documentation_fragment:
398 - purestorage.flashblade.purestorage.fb
399 """
400
401 EXAMPLES = r"""
402 - name: Create a simple snapshot policy with no rules
403 purestorage.flashblade.purefb_policy:
404 name: test_policy
405 policy_type: snapshot
406 fb_url: 10.10.10.2
407 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
408 - name: Create a snapshot policy and connect to existing filesystems and filesystem replica links
409 purestorage.flashblade.purefb_policy:
410 name: test_policy_with_members
411 policy_type: snapshot
412 filesystem:
413 - fs1
414 - fs2
415 replica_link:
416 - rl1
417 - rl2
418 fb_url: 10.10.10.2
419 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
420 - name: Create a snapshot policy with rules
421 purestorage.flashblade.purefb_policy:
422 name: test_policy2
423 policy_type: snapshot
424 at: 11AM
425 keep_for: 86400
426 every: 86400
427 timezone: Asia/Shanghai
428 fb_url: 10.10.10.2
429 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
430 - name: Delete filesystem foo from snapshot policy
431 purestorage.flashblade.purefb_policy:
432 name: test_policy
433 policy_type: snapshot
434 filesystem: foo
435 state: absent
436 fb_url: 10.10.10.2
437 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
438 - name: Delete a snapshot policy
439 purestorage.flashblade.purefb_policy:
440 name: test_policy
441 policy_type: snapshot
442 state: absent
443 fb_url: 10.10.10.2
444 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
445 - name: Create an empty object store access policy
446 purestorage.flashblade.purefb_policy:
447 name: test_os_policy
448 account: test
449 policy_type: access
450 fb_url: 10.10.10.2
451 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
452 - name: Create an empty object store access policy and assign user
453 purestorage.flashblade.purefb_policy:
454 name: test_os_policy
455 account: test
456 policy_type: access
457 user: fred
458 fb_url: 10.10.10.2
459 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
460 - name: Create a object store access policy with simple rule
461 purestorage.flashblade.purefb_policy:
462 name: test_os_policy_rule
463 policy_type: access
464 account: test
465 rule: rule1
466 actions: "s3:*"
467 object_resources: "*"
468 fb_url: 10.10.10.2
469 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
470 - name: Create an empty SMB client policy
471 purestorage.flashblade.purefb_policy:
472 name: test_smb_client
473 policy_type: smb_client
474 fb_url: 10.10.10.2
475 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
476 - name: Create an SMB client policy with a client rule
477 purestorage.flashblade.purefb_policy:
478 name: test_smb_client
479 policy_type: smb_client
480 client: "10.0.1.0/24"
481 permission: rw
482 fb_url: 10.10.10.2
483 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
484 - name: Create an empty NFS export policy
485 purestorage.flashblade.purefb_policy:
486 name: test_nfs_export
487 policy_type: nfs
488 fb_url: 10.10.10.2
489 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
490 - name: Create an NFS export policy with a client rule
491 purestorage.flashblade.purefb_policy:
492 name: test_nfs_export
493 policy_type: nfs
494 atime: true
495 client: "10.0.1.0/24"
496 secure: true
497 security: [sys, krb5]
498 permission: rw
499 fb_url: 10.10.10.2
500 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
501 - name: Create a new rule for an existing NFS export policy
502 purestorage.flashblade.purefb_policy:
503 name: test_nfs_export
504 policy_type: nfs
505 atime: true
506 client: "10.0.2.0/24"
507 security: sys
508 permission: ro
509 fb_url: 10.10.10.2
510 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
511 - name: Delete a client rule from an NFS export policy
512 purestorage.flashblade.purefb_policy:
513 name: test_nfs_export
514 client: "10.0.1.0/24"
515 policy_type: nfs
516 state: absent
517 fb_url: 10.10.10.2
518 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
519 - name: Delete an NFS export policy and all associated rules
520 purestorage.flashblade.purefb_policy:
521 name: test_nfs_export
522 state: absent
523 policy_type: nfs
524 fb_url: 10.10.10.2
525 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
526 - name: Delete a rule from an object store access policy
527 purestorage.flashblade.purefb_policy:
528 name: test_os_policy_rule
529 account: test
530 policy_type: access
531 rule: rule1
532 state: absent
533 fb_url: 10.10.10.2
534 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
535 - name: Delete a user from an object store access policy
536 purestorage.flashblade.purefb_policy:
537 name: test_os_policy_rule
538 account: test
539 user: fred
540 policy_type: access
541 state: absent
542 fb_url: 10.10.10.2
543 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
544 - name: Delete an object store access policy with attached users (USE WITH CAUTION)
545 purestorage.flashblade.purefb_policy:
546 name: test_os_policy_rule
547 account: test
548 policy_type: access
549 force_delete: true
550 state: absent
551 fb_url: 10.10.10.2
552 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
553 - name: Delete an object store access policy with no attached users
554 purestorage.flashblade.purefb_policy:
555 name: test_os_policy_rule
556 account: test
557 policy_type: access
558 state: absent
559 fb_url: 10.10.10.2
560 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
561 - name: Copy an object store access policy rule to another exisitng policy
562 purestorage.flashblade.purefb_policy:
563 name: test_os_policy_rule
564 policy_type: access
565 account: test
566 target: "account2/anotherpolicy"
567 target_rule: new_rule1
568 state: copy
569 fb_url: 10.10.10.2
570 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
571 - name: Rename an NFS Export Policy
572 purestorage.flashblade.purefb_policy:
573 name: old_name
574 policy_type: nfs
575 rename: new_name
576 fb_url: 10.10.10.2
577 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
578 - name: Create a WORM Data Policy
579 purestorage.flashblade.purefb_policy:
580 name: worm1
581 policy_type: worm
582 default_retention: 5d
583 min_rentetion: 20h
584 max_retention: 1y
585 fb_url: 10.10.10.2
586 api_token: T-9f276a18-50ab-446e-8a0c-666a3529a1b6
587 """
588
589 RETURN = r"""
590 """
591
592 HAS_PYPURECLIENT = True
593 try:
594 from pypureclient.flashblade import (
595 PolicyRuleObjectAccessCondition,
596 PolicyRuleObjectAccessPost,
597 PolicyRuleObjectAccess,
598 NfsExportPolicy,
599 NfsExportPolicyRule,
600 Policy,
601 PolicyPatch,
602 PolicyRule,
603 SmbSharePolicyRule,
604 SmbSharePolicy,
605 SmbClientPolicyRule,
606 SmbClientPolicy,
607 ObjectStoreAccessPolicyPost,
608 NetworkAccessPolicy,
609 NetworkAccessPolicyRule,
610 WormDataPolicy,
611 )
612 except ImportError:
613 HAS_PYPURECLIENT = False
614
615 HAS_PYTZ = True
616 try:
617 import pytz
618 except ImportError:
619 HAS_PYTX = False
620
621 import os
622 import re
623 import platform
624
625 from ansible.module_utils.common.process import get_bin_path
626 from ansible.module_utils.facts.utils import get_file_content
627 from ansible.module_utils.basic import AnsibleModule
628 from ansible_collections.purestorage.flashblade.plugins.module_utils.purefb import (
629 get_system,
630 purefb_argument_spec,
631 )
632 from ansible_collections.purestorage.flashblade.plugins.module_utils.common import (
633 convert_time_to_millisecs,
634 )
635
636 NFS_POLICY_API_VERSION = "2.3"
637 NFS_RENAME_API_VERSION = "2.4"
638 SMB_POLICY_API_VERSION = "2.10"
639 SMB_ENCRYPT_API_VERSION = "2.11"
640 NET_POLICY_API_VERSION = "2.13"
641 WORM_POLICY_API_VERSION = "2.15"
642 CONTEXT_API_VERSION = "2.17"
643
644
645 def _convert_to_millisecs(hour_str: str) -> int:
646 """Convert a 12-hour formatted time string (e.g., '02AM', '12PM') to milliseconds since midnight."""
647 time_part = int(hour_str[:-2])
648 period = hour_str[-2:]
649
650 if period == "AM":
651 return 0 if time_part == 12 else time_part * 3600000
652 else: # PM
653 return 12 * 3600000 if time_part == 12 else (time_part + 12) * 3600000
654
655
656 def _findstr(text, match):
657 for line in text.splitlines():
658 if match in line:
659 found = line
660 return found
661
662
663 def _get_local_tz(module, timezone="UTC"):
664 """
665 We will attempt to get the local timezone of the server running the module and use that.
666 If we can't get the timezone then we will set the default to be UTC
667
668 Linnux has been tested and other opersting systems should be OK.
669 Failures cause assumption of UTC
670
671 Windows is not supported and will assume UTC
672 """
673 if platform.system() == "Linux":
674 timedatectl = get_bin_path("timedatectl")
675 if timedatectl is not None:
676 rcode, stdout, stderr = module.run_command(timedatectl)
677 if rcode == 0 and stdout:
678 line = _findstr(stdout, "Time zone")
679 full_tz = line.split(":", 1)[1].rstrip()
680 timezone = full_tz.split()[0]
681 return timezone
682 else:
683 module.warn("Incorrect timedatectl output. Timezone will be set to UTC")
684 else:
685 if os.path.exists("/etc/timezone"):
686 timezone = get_file_content("/etc/timezone")
687 else:
688 module.warn("Could not find /etc/timezone. Assuming UTC")
689
690 elif platform.system() == "SunOS":
691 if os.path.exists("/etc/default/init"):
692 for line in get_file_content("/etc/default/init", "").splitlines():
693 if line.startswith("TZ="):
694 timezone = line.split("=", 1)[1]
695 return timezone
696 else:
697 module.warn("Could not find /etc/default/init. Assuming UTC")
698
699 elif re.match("^Darwin", platform.platform()):
700 systemsetup = get_bin_path("systemsetup")
701 if systemsetup is not None:
702 rcode, stdout, stderr = module.execute(systemsetup, "-gettimezone")
703 if rcode == 0 and stdout:
704 timezone = stdout.split(":", 1)[1].lstrip()
705 else:
706 module.warn("Could not run systemsetup. Assuming UTC")
707 else:
708 module.warn("Could not find systemsetup. Assuming UTC")
709
710 elif re.match("^(Free|Net|Open)BSD", platform.platform()):
711 if os.path.exists("/etc/timezone"):
712 timezone = get_file_content("/etc/timezone")
713 else:
714 module.warn("Could not find /etc/timezone. Assuming UTC")
715
716 elif platform.system() == "AIX":
717 aix_oslevel = int(platform.version() + platform.release())
718 if aix_oslevel >= 61:
719 if os.path.exists("/etc/environment"):
720 for line in get_file_content("/etc/environment", "").splitlines():
721 if line.startswith("TZ="):
722 timezone = line.split("=", 1)[1]
723 return timezone
724 else:
725 module.warn("Could not find /etc/environment. Assuming UTC")
726 else:
727 module.warn(
728 "Cannot determine timezone when AIX os level < 61. Assuming UTC"
729 )
730
731 else:
732 module.warn("Could not find /etc/timezone. Assuming UTC")
733
734 return timezone
735
736
737 def delete_smb_share_policy(module, blade):
738 """Delete SMB Share Policy, or Rule
739
740 If principal is provided then delete the principal rule if it exists.
741 """
742
743 changed = False
744 versions = list(blade.get_versions().items)
745 policy_delete = True
746 if module.params["principal"]:
747 policy_delete = False
748 if CONTEXT_API_VERSION in versions:
749 prin_rule = blade.get_smb_share_policies_rules(
750 policy_names=[module.params["name"]],
751 filter="principal='" + module.params["principal"] + "'",
752 context_names=[module.params["context"]],
753 )
754 else:
755 prin_rule = blade.get_smb_share_policies_rules(
756 policy_names=[module.params["name"]],
757 filter="principal='" + module.params["principal"] + "'",
758 )
759 if prin_rule.status_code == 200:
760 rule = list(prin_rule.items)[0]
761 changed = True
762 if not module.check_mode:
763 if CONTEXT_API_VERSION in versions:
764 res = blade.delete_smb_share_policies_rules(
765 names=[rule.name], context_names=[module.params["context"]]
766 )
767 else:
768 res = blade.delete_smb_share_policies_rules(names=[rule.name])
769 if res.status_code != 200:
770 module.fail_json(
771 msg="Failed to delete rule for principal {0} in policy {1}. "
772 "Error: {2}".format(
773 module.params["principal"],
774 module.params["name"],
775 res.errors[0].message,
776 )
777 )
778 if policy_delete:
779 changed = True
780 if not module.check_mode:
781 if CONTEXT_API_VERSION in versions:
782 res = blade.delete_smb_share_policies(
783 names=[module.params["name"]],
784 context_names=[module.params["context"]],
785 )
786 else:
787 res = blade.delete_smb_share_policies(names=[module.params["name"]])
788 if res.status_code != 200:
789 module.fail_json(
790 msg="Failed to delete SMB share policy {0}. Error: {1}".format(
791 module.params["name"], res.errors[0].message
792 )
793 )
794 module.exit_json(changed=changed)
795
796
797 def rename_smb_share_policy(module, blade):
798 """Rename SMB Share Policy"""
799
800 changed = True
801 versions = list(blade.get_versions().items)
802 if not module.check_mode:
803 if CONTEXT_API_VERSION in versions:
804 res = blade.patch_smb_share_policies(
805 names=[module.params["name"]],
806 policy=SmbSharePolicy(name=module.params["rename"]),
807 context_names=[module.params["context"]],
808 )
809 else:
810 res = blade.patch_smb_share_policies(
811 names=[module.params["name"]],
812 policy=SmbSharePolicy(name=module.params["rename"]),
813 )
814 if res.status_code != 200:
815 module.fail_json(
816 msg="Failed to rename SMB share policy {0} to {1}. Error: {2}".format(
817 module.params["name"],
818 module.params["rename"],
819 res.errors[0].message,
820 )
821 )
822 module.exit_json(changed=changed)
823
824
825 def create_smb_share_policy(module, blade):
826 """Create SMB Share Policy"""
827 changed = True
828 versions = list(blade.get_versions().items)
829 if not module.check_mode:
830 if CONTEXT_API_VERSION in versions:
831 res = blade.post_smb_share_policies(
832 names=[module.params["name"]], context_names=[module.params["context"]]
833 )
834 else:
835 res = blade.post_smb_share_policies(names=[module.params["name"]])
836 if res.status_code != 200:
837 module.fail_json(
838 msg="Failed to create SMB share policy {0}.Error: {1}".format(
839 module.params["name"], res.errors[0].message
840 )
841 )
842 if not module.params["enabled"]:
843 if CONTEXT_API_VERSION in versions:
844 res = blade.patch_smb_share_policies(
845 policy=SmbSharePolicy(enabled=False),
846 names=[module.params["name"]],
847 context_names=[module.params["context"]],
848 )
849 else:
850 res = blade.patch_smb_share_policies(
851 policy=SmbSharePolicy(enabled=False), names=[module.params["name"]]
852 )
853 if res.status_code != 200:
854 if CONTEXT_API_VERSION in versions:
855 blade.delete_smb_share_policies(
856 names=[module.params["name"]],
857 context_names=[module.params["context"]],
858 )
859 else:
860 blade.delete_smb_share_policies(names=[module.params["name"]])
861 module.fail_json(
862 msg="Failed to create SMB share policy {0}.Error: {1}".format(
863 module.params["name"], res.errors[0].message
864 )
865 )
866 if not module.params["principal"]:
867 module.fail_json(msg="principal is required to create a new rule")
868 else:
869 rule = SmbSharePolicyRule(
870 principal=module.params["principal"],
871 change=module.params["change"],
872 read=module.params["read"],
873 full_control=module.params["full_control"],
874 )
875 if CONTEXT_API_VERSION in versions:
876 res = blade.post_smb_share_policies_rules(
877 policy_names=[module.params["name"]],
878 rule=rule,
879 context_names=[module.params["context"]],
880 )
881 else:
882 res = blade.post_smb_share_policies_rules(
883 policy_names=[module.params["name"]],
884 rule=rule,
885 )
886 if res.status_code != 200:
887 module.fail_json(
888 msg="Failed to create rule for policy {0}. Error: {1}".format(
889 module.params["name"],
890 res.errors[0].message,
891 )
892 )
893 module.exit_json(changed=changed)
894
895
896 def update_smb_share_policy(module, blade):
897 """Update SMB Share Policy Rule"""
898
899 changed = False
900 versions = list(blade.get_versions().items)
901 if module.params["principal"]:
902 if CONTEXT_API_VERSION in versions:
903 current_policy_rule = blade.get_smb_share_policies_rules(
904 policy_names=[module.params["name"]],
905 filter="principal='" + module.params["principal"] + "'",
906 context_names=[module.params["context"]],
907 )
908 else:
909 current_policy_rule = blade.get_smb_share_policies_rules(
910 policy_names=[module.params["name"]],
911 filter="principal='" + module.params["principal"] + "'",
912 )
913 if (
914 current_policy_rule.status_code == 200
915 and current_policy_rule.total_item_count == 0
916 ):
917 rule = SmbSharePolicyRule(
918 principal=module.params["principal"],
919 change=module.params["change"],
920 read=module.params["read"],
921 full_control=module.params["full_control"],
922 )
923 changed = True
924 if not module.check_mode:
925 if module.params["before_rule"]:
926 before_name = (
927 module.params["name"] + "." + str(module.params["before_rule"])
928 )
929 if CONTEXT_API_VERSION in versions:
930 res = blade.post_smb_share_policies_rules(
931 policy_names=[module.params["name"]],
932 rule=rule,
933 before_rule_name=before_name,
934 context_names=[module.params["context"]],
935 )
936 else:
937 res = blade.post_smb_share_policies_rules(
938 policy_names=[module.params["name"]],
939 rule=rule,
940 before_rule_name=before_name,
941 )
942 else:
943 if CONTEXT_API_VERSION in versions:
944 res = blade.post_smb_share_policies_rules(
945 policy_names=[module.params["name"]],
946 rule=rule,
947 context_names=[module.params["context"]],
948 )
949 else:
950 res = blade.post_smb_share_policies_rules(
951 policy_names=[module.params["name"]],
952 rule=rule,
953 )
954 if res.status_code != 200:
955 module.fail_json(
956 msg="Failed to create rule for principal {0} "
957 "in policy {1}. Error: {2}".format(
958 module.params["principal"],
959 module.params["name"],
960 res.errors[0].message,
961 )
962 )
963 else:
964 rules = list(current_policy_rule.items)
965 old_policy_rule = rules[0]
966 current_rule = {
967 "principal": sorted(old_policy_rule.principal),
968 "read": sorted(old_policy_rule.read),
969 "change": sorted(old_policy_rule.change),
970 "full_control": sorted(old_policy_rule.full_control),
971 }
972 if module.params["read"]:
973 if module.params["read"] == "":
974 new_read = ""
975 else:
976 new_read = module.params["read"]
977 else:
978 new_read = current_rule["read"]
979 if module.params["full_control"]:
980 if module.params["full_control"] == "":
981 new_full_control = ""
982 else:
983 new_full_control = module.params["full_control"]
984 else:
985 new_full_control = current_rule["full_control"]
986 if module.params["change"]:
987 if module.params["change"] == "":
988 new_change = ""
989 else:
990 new_change = module.params["change"]
991 else:
992 new_change = current_rule["change"]
993 if module.params["principal"]:
994 new_principal = module.params["principal"]
995 else:
996 new_principal = current_rule["principal"]
997 new_rule = {
998 "principal": new_principal,
999 "read": new_read,
1000 "change": new_change,
1001 "full_control": new_full_control,
1002 }
1003 if current_rule != new_rule:
1004 changed = True
1005 if not module.check_mode:
1006 rule = SmbSharePolicyRule(
1007 principal=module.params["principal"],
1008 change=module.params["change"],
1009 read=module.params["read"],
1010 full_control=module.params["full_control"],
1011 )
1012 if CONTEXT_API_VERSION in versions:
1013 res = blade.patch_smb_share_policies_rules(
1014 names=[
1015 module.params["name"] + "." + str(old_policy_rule.index)
1016 ],
1017 rule=rule,
1018 context_names=[module.params["context"]],
1019 )
1020 else:
1021 res = blade.patch_smb_share_policies_rules(
1022 names=[
1023 module.params["name"] + "." + str(old_policy_rule.index)
1024 ],
1025 rule=rule,
1026 )
1027 if res.status_code != 200:
1028 module.fail_json(
1029 msg="Failed to update SMB share rule {0}. Error: {1}".format(
1030 module.params["name"]
1031 + "."
1032 + str(old_policy_rule.index),
1033 res.errors[0].message,
1034 )
1035 )
1036 if (
1037 module.params["before_rule"]
1038 and module.params["before_rule"] != old_policy_rule.index
1039 ):
1040 changed = True
1041 if not module.check_mode:
1042 before_name = (
1043 module.params["name"] + "." + str(module.params["before_rule"])
1044 )
1045 if CONTEXT_API_VERSION in versions:
1046 res = blade.patch_smb_share_policies_rules(
1047 names=[
1048 module.params["name"] + "." + str(old_policy_rule.index)
1049 ],
1050 rule=SmbSharePolicyRule(),
1051 before_rule_name=before_name,
1052 context_names=[module.params["context"]],
1053 )
1054 else:
1055 res = blade.patch_smb_share_policies_rules(
1056 names=[
1057 module.params["name"] + "." + str(old_policy_rule.index)
1058 ],
1059 rule=SmbSharePolicyRule(),
1060 before_rule_name=before_name,
1061 )
1062 if res.status_code != 200:
1063 module.fail_json(
1064 msg="Failed to move SMB share rule {0}. Error: {1}".format(
1065 module.params["name"]
1066 + "."
1067 + str(old_policy_rule.index),
1068 res.errors[0].message,
1069 )
1070 )
1071 if CONTEXT_API_VERSION in versions:
1072 current_policy = list(
1073 blade.get_smb_share_policies(names=[module.params["name"]]).items,
1074 context_names=[module.params["context"]],
1075 )[0]
1076 else:
1077 current_policy = list(
1078 blade.get_smb_share_policies(names=[module.params["name"]]).items
1079 )[0]
1080 if current_policy.enabled != module.params["enabled"]:
1081 changed = True
1082 if not module.check_mode:
1083 if CONTEXT_API_VERSION in versions:
1084 res = blade.patch_smb_share_policies(
1085 policy=SmbSharePolicy(enabled=module.params["enabled"]),
1086 names=[module.params["name"]],
1087 context_names=[module.params["context"]],
1088 )
1089 else:
1090 res = blade.patch_smb_share_policies(
1091 policy=SmbSharePolicy(enabled=module.params["enabled"]),
1092 names=[module.params["name"]],
1093 )
1094 if res.status_code != 200:
1095 module.fail_json(
1096 msg="Failed to change state of SMB share policy {0}.Error: {1}".format(
1097 module.params["name"], res.errors[0].message
1098 )
1099 )
1100 module.exit_json(changed=changed)
1101
1102
1103 def delete_smb_client_policy(module, blade):
1104 """Delete SMB CLient Policy, or Rule
1105
1106 If client is provided then delete the client rule if it exists.
1107 """
1108
1109 changed = False
1110 versions = list(blade.get_versions().items)
1111 policy_delete = True
1112 if module.params["client"]:
1113 policy_delete = False
1114 if CONTEXT_API_VERSION in versions:
1115 res = blade.get_smb_client_policies_rules(
1116 policy_names=[module.params["name"]],
1117 filter="client='" + module.params["client"] + "'",
1118 context_names=[module.params["context"]],
1119 )
1120 else:
1121 res = blade.get_smb_client_policies_rules(
1122 policy_names=[module.params["name"]],
1123 filter="client='" + module.params["client"] + "'",
1124 )
1125 if res.status_code == 200:
1126 if res.total_item_count == 0:
1127 pass
1128 elif res.total_item_count == 1:
1129 rule = list(res.items)[0]
1130 if module.params["client"] == rule.client:
1131 changed = True
1132 if not module.check_mode:
1133 if CONTEXT_API_VERSION in versions:
1134 res = blade.delete_smb_client_policies_rules(
1135 names=[rule.name],
1136 context_names=[module.params["context"]],
1137 )
1138 else:
1139 res = blade.delete_smb_client_policies_rules(
1140 names=[rule.name]
1141 )
1142 if res.status_code != 200:
1143 module.fail_json(
1144 msg="Failed to delete rule for client {0} in policy {1}. "
1145 "Error: {2}".format(
1146 module.params["client"],
1147 module.params["name"],
1148 res.errors[0].message,
1149 )
1150 )
1151 else:
1152 rules = list(res.items)
1153 for cli in range(len(rules)):
1154 if rules[cli].client == "*":
1155 changed = True
1156 if not module.check_mode:
1157 if CONTEXT_API_VERSION in versions:
1158 res = blade.delete_smb_client_policies_rules(
1159 names=[rules[cli].name],
1160 context_names=[module.params["context"]],
1161 )
1162 else:
1163 res = blade.delete_smb_client_policies_rules(
1164 names=[rules[cli].name]
1165 )
1166 if res.status_code != 200:
1167 module.fail_json(
1168 msg="Failed to delete rule for client {0} in policy {1}. "
1169 "Error: {2}".format(
1170 module.params["client"],
1171 module.params["name"],
1172 res.errors[0].message,
1173 )
1174 )
1175 if policy_delete:
1176 changed = True
1177 if not module.check_mode:
1178 if CONTEXT_API_VERSION in versions:
1179 res = blade.delete_smb_client_policies(
1180 names=[module.params["name"]],
1181 context_names=[module.params["context"]],
1182 )
1183 else:
1184 res = blade.delete_smb_client_policies(names=[module.params["name"]])
1185 if res.status_code != 200:
1186 module.fail_json(
1187 msg="Failed to delete SMB client policy {0}. Error: {1}".format(
1188 module.params["name"], res.errors[0].message
1189 )
1190 )
1191 module.exit_json(changed=changed)
1192
1193
1194 def rename_smb_client_policy(module, blade):
1195 """Rename SMB Client Policy"""
1196
1197 changed = True
1198 versions = list(blade.get_versions().items)
1199 if not module.check_mode:
1200 if CONTEXT_API_VERSION in versions:
1201 res = blade.patch_smb_client_policies(
1202 names=[module.params["name"]],
1203 policy=SmbClientPolicy(name=module.params["rename"]),
1204 context_names=[module.params["context"]],
1205 )
1206 else:
1207 res = blade.patch_smb_client_policies(
1208 names=[module.params["name"]],
1209 policy=SmbClientPolicy(name=module.params["rename"]),
1210 )
1211 if res.status_code != 200:
1212 module.fail_json(
1213 msg="Failed to rename SMB client policy {0} to {1}. Error: {2}".format(
1214 module.params["name"],
1215 module.params["rename"],
1216 res.errors[0].message,
1217 )
1218 )
1219 module.exit_json(changed=changed)
1220
1221
1222 def create_smb_client_policy(module, blade):
1223 """Create SMB Client Policy"""
1224 changed = True
1225 versions = list(blade.get_versions().items)
1226 if not module.check_mode:
1227 if CONTEXT_API_VERSION in versions:
1228 res = blade.post_smb_client_policies(
1229 names=[module.params["name"]], context_names=[module.params["context"]]
1230 )
1231 else:
1232 res = blade.post_smb_client_policies(names=[module.params["name"]])
1233 if res.status_code != 200:
1234 module.fail_json(
1235 msg="Failed to create SMB client policy {0}.Error: {1}".format(
1236 module.params["name"], res.errors[0].message
1237 )
1238 )
1239 if not module.params["enabled"]:
1240 if CONTEXT_API_VERSION in versions:
1241 res = blade.patch_smb_client_policies(
1242 policy=SmbClientPolicy(enabled=False),
1243 names=[module.params["name"]],
1244 context_names=[module.params["context"]],
1245 )
1246 else:
1247 res = blade.patch_smb_client_policies(
1248 policy=SmbClientPolicy(enabled=False), names=[module.params["name"]]
1249 )
1250 if res.status_code != 200:
1251 if CONTEXT_API_VERSION in versions:
1252 blade.delete_smb_client_policies(
1253 names=[module.params["name"]],
1254 context_names=[module.params["context"]],
1255 )
1256 else:
1257 blade.delete_smb_client_policies(names=[module.params["name"]])
1258 module.fail_json(
1259 msg="Failed to create SMB client policy {0}.Error: {1}".format(
1260 module.params["name"], res.errors[0].message
1261 )
1262 )
1263 if not module.params["client"]:
1264 module.fail_json(msg="client is required to create a new rule")
1265 else:
1266 if SMB_ENCRYPT_API_VERSION in versions:
1267 rule = SmbClientPolicyRule(
1268 client=module.params["client"],
1269 permission=module.params["permission"],
1270 access=module.params["access"],
1271 encryption=module.params["smb_encryption"],
1272 )
1273 else:
1274 rule = SmbClientPolicyRule(
1275 client=module.params["client"],
1276 access=module.params["access"],
1277 permission=module.params["permission"],
1278 )
1279 if CONTEXT_API_VERSION in versions:
1280 res = blade.post_smb_client_policies_rules(
1281 policy_names=[module.params["name"]],
1282 rule=rule,
1283 context_names=[module.params["context"]],
1284 )
1285 else:
1286 res = blade.post_smb_client_policies_rules(
1287 policy_names=[module.params["name"]],
1288 rule=rule,
1289 )
1290 if res.status_code != 200:
1291 module.fail_json(
1292 msg="Failed to rule for policy {0}. Error: {1}".format(
1293 module.params["name"],
1294 res.errors[0].message,
1295 )
1296 )
1297 module.exit_json(changed=changed)
1298
1299
1300 def create_network_access_policy(module, blade):
1301 """Create Network Access Policy"""
1302 changed = True
1303 versions = list(blade.get_versions().items)
1304 if not module.check_mode:
1305 if CONTEXT_API_VERSION in versions:
1306 res = blade.post_network_access_policies(
1307 names=[module.params["name"]], context_names=[module.params["context"]]
1308 )
1309 else:
1310 res = blade.post_network_access_policies(names=[module.params["name"]])
1311 if res.status_code != 200:
1312 module.fail_json(
1313 msg="Failed to create network access policy {0}.Error: {1}".format(
1314 module.params["name"], res.errors[0].message
1315 )
1316 )
1317 if not module.params["enabled"]:
1318 if CONTEXT_API_VERSION in versions:
1319 res = blade.patch_network_access_policies(
1320 policy=SmbClientPolicy(enabled=False),
1321 names=[module.params["name"]],
1322 context_names=[module.params["context"]],
1323 )
1324 else:
1325 res = blade.patch_network_access_policies(
1326 policy=SmbClientPolicy(enabled=False), names=[module.params["name"]]
1327 )
1328 if res.status_code != 200:
1329 if CONTEXT_API_VERSION in versions:
1330 blade.delete_network_access_policies(
1331 names=[module.params["name"]],
1332 context_names=[module.params["context"]],
1333 )
1334 else:
1335 blade.delete_network_access_policies(names=[module.params["name"]])
1336 module.fail_json(
1337 msg="Failed to create network access policy {0}.Error: {1}".format(
1338 module.params["name"], res.errors[0].message
1339 )
1340 )
1341 if not module.params["client"]:
1342 module.fail_json(msg="client is required to create a new rule")
1343 else:
1344 rule = NetworkAccessPolicyRule(
1345 client=module.params["client"],
1346 effect=module.params["effect"],
1347 interfaces=module.params["interfaces"],
1348 )
1349 if CONTEXT_API_VERSION in versions:
1350 res = blade.post_network_access_policies_rules(
1351 policy_names=[module.params["name"]],
1352 rule=rule,
1353 context_names=[module.params["context"]],
1354 )
1355 else:
1356 res = blade.post_network_access_policies_rules(
1357 policy_names=[module.params["name"]],
1358 rule=rule,
1359 )
1360 if res.status_code != 200:
1361 module.fail_json(
1362 msg="Failed to rule for policy {0}. Error: {1}".format(
1363 module.params["name"],
1364 res.errors[0].message,
1365 )
1366 )
1367 module.exit_json(changed=changed)
1368
1369
1370 def create_worm_data_policy(module, blade):
1371 """Create WORM Data Policy"""
1372 changed = True
1373 versions = list(blade.get_versions().items)
1374 if not module.check_mode:
1375 min_retention = convert_time_to_millisecs(module.params["min_retention"])
1376 max_retention = convert_time_to_millisecs(module.params["max_retention"])
1377 default_retention = convert_time_to_millisecs(
1378 module.params["default_retention"]
1379 )
1380 if CONTEXT_API_VERSION in versions:
1381 res = blade.post_worm_data_policies(
1382 policy=WormDataPolicy(
1383 enabled=module.params["enabled"],
1384 mode="compliance",
1385 min_retention=min_retention,
1386 max_retention=max_retention,
1387 default_retention=default_retention,
1388 retention_lock=module.params["retention_lock"],
1389 ),
1390 names=[module.params["name"]],
1391 context_names=[module.params["context"]],
1392 )
1393 else:
1394 res = blade.post_worm_data_policies(
1395 policy=WormDataPolicy(
1396 enabled=module.params["enabled"],
1397 mode="compliance",
1398 min_retention=min_retention,
1399 max_retention=max_retention,
1400 default_retention=default_retention,
1401 retention_lock=module.params["retention_lock"],
1402 ),
1403 names=[module.params["name"]],
1404 )
1405 if res.status_code != 200:
1406 if CONTEXT_API_VERSION in versions:
1407 blade.delete_worm_data_policies(
1408 names=[module.params["name"]],
1409 context_names=[module.params["context"]],
1410 )
1411 else:
1412 blade.delete_worm_data_policies(names=[module.params["name"]])
1413 module.fail_json(
1414 msg="Failed to create WORM data policy {0}.Error: {1}".format(
1415 module.params["name"], res.errors[0].message
1416 )
1417 )
1418 module.exit_json(changed=changed)
1419
1420
1421 def update_smb_client_policy(module, blade):
1422 """Update SMB Client Policy Rule"""
1423
1424 changed = False
1425 versions = list(blade.get_versions().items)
1426 if module.params["client"]:
1427 if CONTEXT_API_VERSION in versions:
1428 current_policy_rule = blade.get_smb_client_policies_rules(
1429 policy_names=[module.params["name"]],
1430 filter="client='" + module.params["client"] + "'",
1431 context_names=[module.params["context"]],
1432 )
1433 else:
1434 current_policy_rule = blade.get_smb_client_policies_rules(
1435 policy_names=[module.params["name"]],
1436 filter="client='" + module.params["client"] + "'",
1437 )
1438 if (
1439 current_policy_rule.status_code == 200
1440 and current_policy_rule.total_item_count == 0
1441 ):
1442 if SMB_ENCRYPT_API_VERSION in versions:
1443 rule = SmbClientPolicyRule(
1444 client=module.params["client"],
1445 permission=module.params["permission"],
1446 access=module.params["access"],
1447 encryption=module.params["smb_encryption"],
1448 )
1449 else:
1450 rule = SmbClientPolicyRule(
1451 client=module.params["client"],
1452 permission=module.params["permission"],
1453 access=module.params["access"],
1454 )
1455 changed = True
1456 if not module.check_mode:
1457 if module.params["before_rule"]:
1458 before_name = (
1459 module.params["name"] + "." + str(module.params["before_rule"])
1460 )
1461 if CONTEXT_API_VERSION in versions:
1462 res = blade.post_smb_client_policies_rules(
1463 policy_names=[module.params["name"]],
1464 rule=rule,
1465 before_rule_name=before_name,
1466 context_names=[module.params["context"]],
1467 )
1468 else:
1469 res = blade.post_smb_client_policies_rules(
1470 policy_names=[module.params["name"]],
1471 rule=rule,
1472 before_rule_name=before_name,
1473 )
1474 else:
1475 if CONTEXT_API_VERSION in versions:
1476 res = blade.post_smb_client_policies_rules(
1477 policy_names=[module.params["name"]],
1478 rule=rule,
1479 context_names=[module.params["context"]],
1480 )
1481 else:
1482 res = blade.post_smb_client_policies_rules(
1483 policy_names=[module.params["name"]],
1484 rule=rule,
1485 )
1486 if res.status_code != 200:
1487 module.fail_json(
1488 msg="Failed to create rule for client {0} "
1489 "in policy {1}. Error: {2}".format(
1490 module.params["client"],
1491 module.params["name"],
1492 res.errors[0].message,
1493 )
1494 )
1495 else:
1496 rules = list(current_policy_rule.items)
1497 cli_count = None
1498 done = False
1499 if module.params["client"] == "*":
1500 for cli in range(len(rules)):
1501 if rules[cli].client == "*":
1502 cli_count = cli
1503 if not cli_count:
1504 if SMB_ENCRYPT_API_VERSION in versions:
1505 rule = SmbClientPolicyRule(
1506 client=module.params["client"],
1507 permission=module.params["permission"],
1508 access=module.params["access"],
1509 encryption=module.params["smb_encryption"],
1510 )
1511 else:
1512 rule = SmbClientPolicyRule(
1513 client=module.params["client"],
1514 permission=module.params["permission"],
1515 access=module.params["access"],
1516 )
1517 done = True
1518 changed = True
1519 if not module.check_mode:
1520 if module.params["before_rule"]:
1521 if CONTEXT_API_VERSION in versions:
1522 res = blade.post_smb_client_policies_rules(
1523 policy_names=[module.params["name"]],
1524 rule=rule,
1525 before_rule_name=(
1526 module.params["name"]
1527 + "."
1528 + str(module.params["before_rule"]),
1529 ),
1530 context_names=[module.params["context"]],
1531 )
1532 else:
1533 res = blade.post_smb_client_policies_rules(
1534 policy_names=[module.params["name"]],
1535 rule=rule,
1536 before_rule_name=(
1537 module.params["name"]
1538 + "."
1539 + str(module.params["before_rule"]),
1540 ),
1541 )
1542 else:
1543 if CONTEXT_API_VERSION in versions:
1544 res = blade.post_smb_client_policies_rules(
1545 policy_names=[module.params["name"]],
1546 rule=rule,
1547 context_names=[module.params["context"]],
1548 )
1549 else:
1550 res = blade.post_smb_client_policies_rules(
1551 policy_names=[module.params["name"]],
1552 rule=rule,
1553 )
1554 if res.status_code != 200:
1555 module.fail_json(
1556 msg="Failed to create rule for "
1557 "client {0} in policy {1}. Error: {2}".format(
1558 module.params["client"],
1559 module.params["name"],
1560 res.errors[0].message,
1561 )
1562 )
1563 if not done:
1564 old_policy_rule = rules[0]
1565 if SMB_ENCRYPT_API_VERSION in versions:
1566 current_rule = {
1567 "client": sorted(old_policy_rule.client),
1568 "permission": sorted(old_policy_rule.permission),
1569 "encryption": old_policy_rule.encryption,
1570 }
1571 else:
1572 current_rule = {
1573 "client": sorted(old_policy_rule.client),
1574 "permission": sorted(old_policy_rule.permission),
1575 }
1576 if SMB_ENCRYPT_API_VERSION in versions:
1577 if module.params["smb_encryption"]:
1578 new_encryption = module.params["smb_encryption"]
1579 else:
1580 new_encryption = current_rule["encryption"]
1581 if module.params["permission"]:
1582 new_permission = sorted(module.params["permission"])
1583 else:
1584 new_permission = sorted(current_rule["permission"])
1585 if module.params["client"]:
1586 new_client = sorted(module.params["client"])
1587 else:
1588 new_client = sorted(current_rule["client"])
1589 if SMB_ENCRYPT_API_VERSION in versions:
1590 new_rule = {
1591 "client": new_client,
1592 "permission": new_permission,
1593 "encryption": new_encryption,
1594 }
1595 else:
1596 new_rule = {
1597 "client": new_client,
1598 "permission": new_permission,
1599 }
1600 if current_rule != new_rule:
1601 changed = True
1602 if not module.check_mode:
1603 if SMB_ENCRYPT_API_VERSION in versions:
1604 rule = SmbClientPolicyRule(
1605 client=module.params["client"],
1606 permission=module.params["permission"],
1607 encryption=module.params["smb_encryption"],
1608 )
1609 else:
1610 rule = SmbClientPolicyRule(
1611 client=module.params["client"],
1612 permission=module.params["permission"],
1613 )
1614 if CONTEXT_API_VERSION in versions:
1615 res = blade.patch_smb_client_policies_rules(
1616 names=[
1617 module.params["name"]
1618 + "."
1619 + str(old_policy_rule.index)
1620 ],
1621 rule=rule,
1622 context_names=[module.params["context"]],
1623 )
1624 else:
1625 res = blade.patch_smb_client_policies_rules(
1626 names=[
1627 module.params["name"]
1628 + "."
1629 + str(old_policy_rule.index)
1630 ],
1631 rule=rule,
1632 )
1633 if res.status_code != 200:
1634 module.fail_json(
1635 msg="Failed to update SMB client rule {0}. Error: {1}".format(
1636 module.params["name"]
1637 + "."
1638 + str(old_policy_rule.index),
1639 res.errors[0].message,
1640 )
1641 )
1642 if (
1643 module.params["before_rule"]
1644 and module.params["before_rule"] != old_policy_rule.index
1645 ):
1646 changed = True
1647 if not module.check_mode:
1648 before_name = (
1649 module.params["name"]
1650 + "."
1651 + str(module.params["before_rule"])
1652 )
1653 if CONTEXT_API_VERSION in versions:
1654 res = blade.patch_smb_client_policies_rules(
1655 names=[
1656 module.params["name"]
1657 + "."
1658 + str(old_policy_rule.index)
1659 ],
1660 rule=SmbClientPolicyRule(),
1661 before_rule_name=before_name,
1662 context_names=[module.params["context"]],
1663 )
1664 else:
1665 res = blade.patch_smb_client_policies_rules(
1666 names=[
1667 module.params["name"]
1668 + "."
1669 + str(old_policy_rule.index)
1670 ],
1671 rule=SmbClientPolicyRule(),
1672 before_rule_name=before_name,
1673 )
1674 if res.status_code != 200:
1675 module.fail_json(
1676 msg="Failed to move SMB client rule {0}. Error: {1}".format(
1677 module.params["name"]
1678 + "."
1679 + str(old_policy_rule.index),
1680 res.errors[0].message,
1681 )
1682 )
1683 if CONTEXT_API_VERSION in versions:
1684 current_policy = list(
1685 blade.get_smb_client_policies(
1686 names=[module.params["name"]], context_names=[module.params["context"]]
1687 ).items
1688 )[0]
1689 else:
1690 current_policy = list(
1691 blade.get_smb_client_policies(names=[module.params["name"]]).items
1692 )[0]
1693 if current_policy.enabled != module.params["enabled"]:
1694 changed = True
1695 if not module.check_mode:
1696 if CONTEXT_API_VERSION in versions:
1697 res = blade.patch_smb_client_policies(
1698 policy=SmbClientPolicy(enabled=module.params["enabled"]),
1699 names=[module.params["name"]],
1700 context_names=[module.params["context"]],
1701 )
1702 else:
1703 res = blade.patch_smb_client_policies(
1704 policy=SmbClientPolicy(enabled=module.params["enabled"]),
1705 names=[module.params["name"]],
1706 )
1707 if res.status_code != 200:
1708 module.fail_json(
1709 msg="Failed to change state of SMB client policy {0}.Error: {1}".format(
1710 module.params["name"], res.errors[0].message
1711 )
1712 )
1713 module.exit_json(changed=changed)
1714
1715
1716 def delete_nfs_policy(module, blade):
1717 """Delete NFS Export Policy, or Rule
1718
1719 If client is provided then delete the client rule if it exists.
1720 """
1721
1722 changed = False
1723 versions = list(blade.get_versions().items)
1724 policy_delete = True
1725 if module.params["client"]:
1726 policy_delete = False
1727 if CONTEXT_API_VERSION in versions:
1728 res = blade.get_nfs_export_policies_rules(
1729 policy_names=[module.params["name"]],
1730 filter="client='" + module.params["client"] + "'",
1731 context_names=[module.params["context"]],
1732 )
1733 else:
1734 res = blade.get_nfs_export_policies_rules(
1735 policy_names=[module.params["name"]],
1736 filter="client='" + module.params["client"] + "'",
1737 )
1738 if res.status_code == 200:
1739 if res.total_item_count == 0:
1740 pass
1741 elif res.total_item_count == 1:
1742 rule = list(res.items)[0]
1743 if module.params["client"] == rule.client:
1744 changed = True
1745 if not module.check_mode:
1746 if CONTEXT_API_VERSION in versions:
1747 res = blade.delete_nfs_export_policies_rules(
1748 names=[rule.name],
1749 context_names=[module.params["context"]],
1750 )
1751 else:
1752 res = blade.delete_nfs_export_policies_rules(
1753 names=[rule.name]
1754 )
1755 if res.status_code != 200:
1756 module.fail_json(
1757 msg="Failed to delete rule for client {0} in policy {1}. "
1758 "Error: {2}".format(
1759 module.params["client"],
1760 module.params["name"],
1761 res.errors[0].message,
1762 )
1763 )
1764 else:
1765 rules = list(res.items)
1766 for cli in range(len(rules)):
1767 if rules[cli].client == "*":
1768 changed = True
1769 if not module.check_mode:
1770 if CONTEXT_API_VERSION in versions:
1771 res = blade.delete_nfs_export_policies_rules(
1772 names=[rules[cli].name],
1773 context_names=[module.params["context"]],
1774 )
1775 else:
1776 res = blade.delete_nfs_export_policies_rules(
1777 names=[rules[cli].name]
1778 )
1779 if res.status_code != 200:
1780 module.fail_json(
1781 msg="Failed to delete rule for client {0} in policy {1}. "
1782 "Error: {2}".format(
1783 module.params["client"],
1784 module.params["name"],
1785 res.errors[0].message,
1786 )
1787 )
1788 if policy_delete:
1789 changed = True
1790 if not module.check_mode:
1791 if CONTEXT_API_VERSION in versions:
1792 res = blade.delete_nfs_export_policies(
1793 names=[module.params["name"]],
1794 context_names=[module.params["context"]],
1795 )
1796 else:
1797 res = blade.delete_nfs_export_policies(names=[module.params["name"]])
1798 if res.status_code != 200:
1799 module.fail_json(
1800 msg="Failed to delete export policy {0}. Error: {1}".format(
1801 module.params["name"], res.errors[0].message
1802 )
1803 )
1804 module.exit_json(changed=changed)
1805
1806
1807 def update_network_access_policy(module, blade):
1808 """Update Networkk Access Policy Rule"""
1809
1810 changed = False
1811 versions = list(blade.get_versions().items)
1812 if module.params["client"]:
1813 if CONTEXT_API_VERSION in versions:
1814 current_policy_rule = blade.get_network_access_policies_rules(
1815 policy_names=[module.params["name"]],
1816 filter="client='" + module.params["client"] + "'",
1817 context_names=[module.params["context"]],
1818 )
1819 else:
1820 current_policy_rule = blade.get_network_access_policies_rules(
1821 policy_names=[module.params["name"]],
1822 filter="client='" + module.params["client"] + "'",
1823 )
1824 if (
1825 current_policy_rule.status_code == 200
1826 and current_policy_rule.total_item_count == 0
1827 ):
1828 rule = NetworkAccessPolicyRule(
1829 client=module.params["client"],
1830 effect=module.params["effect"],
1831 interfaces=module.params["interfaces"],
1832 )
1833 changed = True
1834 if not module.check_mode:
1835 if module.params["before_rule"]:
1836 before_name = (
1837 module.params["name"] + "." + str(module.params["before_rule"])
1838 )
1839 if CONTEXT_API_VERSION in versions:
1840 res = blade.post_network_access_policies_rules(
1841 policy_names=[module.params["name"]],
1842 rule=rule,
1843 before_rule_name=before_name,
1844 context_names=[module.params["context"]],
1845 )
1846 else:
1847 res = blade.post_network_access_policies_rules(
1848 policy_names=[module.params["name"]],
1849 rule=rule,
1850 before_rule_name=before_name,
1851 )
1852 else:
1853 if CONTEXT_API_VERSION in versions:
1854 res = blade.post_network_access_policies_rules(
1855 policy_names=[module.params["name"]],
1856 rule=rule,
1857 context_names=[module.params["context"]],
1858 )
1859 else:
1860 res = blade.post_network_access_policies_rules(
1861 policy_names=[module.params["name"]],
1862 rule=rule,
1863 )
1864 if res.status_code != 200:
1865 module.fail_json(
1866 msg="Failed to create rule for client {0} "
1867 "in policy {1}. Error: {2}".format(
1868 module.params["client"],
1869 module.params["name"],
1870 res.errors[0].message,
1871 )
1872 )
1873 else:
1874 rules = list(current_policy_rule.items)
1875 cli_count = None
1876 done = False
1877 if module.params["client"] == "*":
1878 for cli in range(len(rules)):
1879 if rules[cli].client == "*":
1880 cli_count = cli
1881 if not cli_count:
1882 rule = NetworkAccessPolicyRule(
1883 client=module.params["client"],
1884 effect=module.params["effect"],
1885 interfaces=module.params["interfaces"],
1886 )
1887 done = True
1888 changed = True
1889 if not module.check_mode:
1890 if module.params["before_rule"]:
1891 if CONTEXT_API_VERSION in versions:
1892 res = blade.post_network_access_policies_rules(
1893 policy_names=[module.params["name"]],
1894 rule=rule,
1895 before_rule_name=(
1896 module.params["name"]
1897 + "."
1898 + str(module.params["before_rule"]),
1899 ),
1900 context_names=[module.params["context"]],
1901 )
1902 else:
1903 res = blade.post_network_access_policies_rules(
1904 policy_names=[module.params["name"]],
1905 rule=rule,
1906 before_rule_name=(
1907 module.params["name"]
1908 + "."
1909 + str(module.params["before_rule"]),
1910 ),
1911 )
1912 else:
1913 if CONTEXT_API_VERSION in versions:
1914 res = blade.post_network_access_policies_rules(
1915 policy_names=[module.params["name"]],
1916 rule=rule,
1917 context_names=[module.params["context"]],
1918 )
1919 else:
1920 res = blade.post_network_access_policies_rules(
1921 policy_names=[module.params["name"]],
1922 rule=rule,
1923 )
1924 if res.status_code != 200:
1925 module.fail_json(
1926 msg="Failed to create rule for "
1927 "client {0} in policy {1}. Error: {2}".format(
1928 module.params["client"],
1929 module.params["name"],
1930 res.errors[0].message,
1931 )
1932 )
1933 if not done:
1934 old_policy_rule = rules[0]
1935 current_rule = {
1936 "client": sorted(old_policy_rule.client),
1937 "effect": old_policy_rule.effect,
1938 "interfaces": old_policy_rule.interfaces,
1939 }
1940 if module.params["interfaces"]:
1941 new_interfaces = module.params["interfaces"]
1942 else:
1943 new_interfaces = current_rule["interfaces"]
1944 if module.params["effect"]:
1945 new_effect = module.params["effect"]
1946 else:
1947 new_effect = current_rule["effect"]
1948 if module.params["client"]:
1949 new_client = sorted(module.params["client"])
1950 else:
1951 new_client = sorted(current_rule["client"])
1952 new_rule = {
1953 "client": new_client,
1954 "effect": new_effect,
1955 "interfaces": new_interfaces,
1956 }
1957 if current_rule != new_rule:
1958 changed = True
1959 if not module.check_mode:
1960 rule = NetworkAccessPolicyRule(
1961 client=module.params["client"],
1962 effect=module.params["effect"],
1963 interfaces=module.params["interfaces"],
1964 )
1965 if CONTEXT_API_VERSION in versions:
1966 res = blade.patch_network_access_policies_rules(
1967 names=[
1968 module.params["name"]
1969 + "."
1970 + str(old_policy_rule.index)
1971 ],
1972 rule=rule,
1973 context_names=[module.params["context"]],
1974 )
1975 else:
1976 res = blade.patch_network_access_policies_rules(
1977 names=[
1978 module.params["name"]
1979 + "."
1980 + str(old_policy_rule.index)
1981 ],
1982 rule=rule,
1983 )
1984 if res.status_code != 200:
1985 module.fail_json(
1986 msg="Failed to update network access client rule {0}. Error: {1}".format(
1987 module.params["name"]
1988 + "."
1989 + str(old_policy_rule.index),
1990 res.errors[0].message,
1991 )
1992 )
1993 if (
1994 module.params["before_rule"]
1995 and module.params["before_rule"] != old_policy_rule.index
1996 ):
1997 changed = True
1998 if not module.check_mode:
1999 before_name = (
2000 module.params["name"]
2001 + "."
2002 + str(module.params["before_rule"])
2003 )
2004 if CONTEXT_API_VERSION in versions:
2005 res = blade.patch_network_access_policies_rules(
2006 names=[
2007 module.params["name"]
2008 + "."
2009 + str(old_policy_rule.index)
2010 ],
2011 rule=NetworkAccessPolicyRule(),
2012 before_rule_name=before_name,
2013 context_names=[module.params["context"]],
2014 )
2015 else:
2016 res = blade.patch_network_access_policies_rules(
2017 names=[
2018 module.params["name"]
2019 + "."
2020 + str(old_policy_rule.index)
2021 ],
2022 rule=NetworkAccessPolicyRule(),
2023 before_rule_name=before_name,
2024 )
2025 if res.status_code != 200:
2026 module.fail_json(
2027 msg="Failed to move network access client rule {0}. Error: {1}".format(
2028 module.params["name"]
2029 + "."
2030 + str(old_policy_rule.index),
2031 res.errors[0].message,
2032 )
2033 )
2034 if CONTEXT_API_VERSION in versions:
2035 current_policy = list(
2036 blade.get_network_access_policies(
2037 names=[module.params["name"]], context_names=[module.params["context"]]
2038 ).items
2039 )[0]
2040 else:
2041 current_policy = list(
2042 blade.get_network_access_policies(names=[module.params["name"]]).items
2043 )[0]
2044 if current_policy.enabled != module.params["enabled"]:
2045 changed = True
2046 if not module.check_mode:
2047 if CONTEXT_API_VERSION in versions:
2048 res = blade.patch_network_access_policies(
2049 policy=NetworkAccessPolicy(enabled=module.params["enabled"]),
2050 names=[module.params["name"]],
2051 context_names=[module.params["context"]],
2052 )
2053 else:
2054 res = blade.patch_network_access_policies(
2055 policy=NetworkAccessPolicy(enabled=module.params["enabled"]),
2056 names=[module.params["name"]],
2057 )
2058 if res.status_code != 200:
2059 module.fail_json(
2060 msg="Failed to change state of network access policy {0}.Error: {1}".format(
2061 module.params["name"], res.errors[0].message
2062 )
2063 )
2064 module.exit_json(changed=changed)
2065
2066
2067 def delete_network_access_policy(module, blade):
2068 """Delete Network Access Policy, or Rule
2069
2070 If client is provided then delete the client rule if it exists.
2071 """
2072
2073 changed = False
2074 versions = list(blade.get_versions().items)
2075 policy_delete = True
2076 if module.params["client"]:
2077 policy_delete = False
2078 if CONTEXT_API_VERSION in versions:
2079 res = blade.get_network_access_policies_rules(
2080 policy_names=[module.params["name"]],
2081 filter="client='" + module.params["client"] + "'",
2082 context_names=[module.params["context"]],
2083 )
2084 else:
2085 res = blade.get_network_access_policies_rules(
2086 policy_names=[module.params["name"]],
2087 filter="client='" + module.params["client"] + "'",
2088 )
2089 if res.status_code == 200:
2090 if res.total_item_count == 0:
2091 pass
2092 elif res.total_item_count == 1:
2093 rule = list(res.items)[0]
2094 if module.params["client"] == rule.client:
2095 changed = True
2096 if not module.check_mode:
2097 if CONTEXT_API_VERSION in versions:
2098 res = blade.delete_network_access_policies_rules(
2099 names=[rule.name],
2100 context_names=[module.params["context"]],
2101 )
2102 else:
2103 res = blade.delete_network_access_policies_rules(
2104 names=[rule.name]
2105 )
2106 if res.status_code != 200:
2107 module.fail_json(
2108 msg="Failed to delete rule for client {0} in policy {1}. "
2109 "Error: {2}".format(
2110 module.params["client"],
2111 module.params["name"],
2112 res.errors[0].message,
2113 )
2114 )
2115 else:
2116 rules = list(res.items)
2117 for cli in range(len(rules)):
2118 if rules[cli].client == "*":
2119 changed = True
2120 if not module.check_mode:
2121 if CONTEXT_API_VERSION in versions:
2122 res = blade.delete_network_access_policies_rules(
2123 names=[rules[cli].name],
2124 context_names=[module.params["context"]],
2125 )
2126 else:
2127 res = blade.delete_network_access_policies_rules(
2128 names=[rules[cli].name]
2129 )
2130 if res.status_code != 200:
2131 module.fail_json(
2132 msg="Failed to delete rule for client {0} in policy {1}. "
2133 "Error: {2}".format(
2134 module.params["client"],
2135 module.params["name"],
2136 res.errors[0].message,
2137 )
2138 )
2139 if policy_delete:
2140 changed = True
2141 if not module.check_mode:
2142 if CONTEXT_API_VERSION in versions:
2143 res = blade.delete_network_Access_policies(
2144 names=[module.params["name"]],
2145 context_names=[module.params["context"]],
2146 )
2147 else:
2148 res = blade.delete_network_Access_policies(
2149 names=[module.params["name"]]
2150 )
2151 if res.status_code != 200:
2152 module.fail_json(
2153 msg="Failed to delete network access policy {0}. Error: {1}".format(
2154 module.params["name"], res.errors[0].message
2155 )
2156 )
2157 module.exit_json(changed=changed)
2158
2159
2160 def delete_worm_data_policy(module, blade):
2161 """Delete WORM data Policy"""
2162
2163 changed = True
2164 versions = list(blade.get_versions().items)
2165 if not module.check_mode:
2166 if CONTEXT_API_VERSION in versions:
2167 res = blade.delete_worm_data_policies(
2168 names=[module.params["name"]], context_names=[module.params["context"]]
2169 )
2170 else:
2171 res = blade.delete_worm_data_policies(names=[module.params["name"]])
2172 if res.status_code != 200:
2173 module.fail_json(
2174 msg="Failed to delete WORM data policy {0}. Error: {1}".format(
2175 module.params["name"], res.errors[0].message
2176 )
2177 )
2178 module.exit_json(changed=changed)
2179
2180
2181 def rename_worm_data_policy(module):
2182 """Rename WORM Data Policy"""
2183
2184 changed = False
2185 module.warn("Renaming of WORM Data policies is not supported")
2186 module.exit_json(changed=changed)
2187
2188
2189 def rename_network_access_policy(module, blade):
2190 """Rename Network Access Policy"""
2191
2192 changed = True
2193 versions = list(blade.get_versions().items)
2194 if not module.check_mode:
2195 if CONTEXT_API_VERSION in versions:
2196 res = blade.patch_network_access_policies(
2197 names=[module.params["name"]],
2198 policy=NfsExportPolicy(name=module.params["rename"]),
2199 context_names=[module.params["context"]],
2200 )
2201 else:
2202 res = blade.patch_network_access_policies(
2203 names=[module.params["name"]],
2204 policy=NfsExportPolicy(name=module.params["rename"]),
2205 )
2206 if res.status_code != 200:
2207 module.fail_json(
2208 msg="Failed to rename network access policy {0} to {1}. Error: {2}".format(
2209 module.params["name"],
2210 module.params["rename"],
2211 res.errors[0].message,
2212 )
2213 )
2214 module.exit_json(changed=changed)
2215
2216
2217 def rename_nfs_policy(module, blade):
2218 """Rename NFS Export Policy"""
2219
2220 changed = True
2221 versions = list(blade.get_versions().items)
2222 if not module.check_mode:
2223 if CONTEXT_API_VERSION in versions:
2224 res = blade.patch_nfs_export_policies(
2225 names=[module.params["name"]],
2226 policy=NfsExportPolicy(name=module.params["rename"]),
2227 context_names=[module.params["context"]],
2228 )
2229 else:
2230 res = blade.patch_nfs_export_policies(
2231 names=[module.params["name"]],
2232 policy=NfsExportPolicy(name=module.params["rename"]),
2233 )
2234 if res.status_code != 200:
2235 module.fail_json(
2236 msg="Failed to rename NFS export policy {0} to {1}. Error: {2}".format(
2237 module.params["name"],
2238 module.params["rename"],
2239 res.errors[0].message,
2240 )
2241 )
2242 module.exit_json(changed=changed)
2243
2244
2245 def update_worm_data_policy(module, blade):
2246 """Update WORM data policy"""
2247
2248 changed = False
2249 versions = list(blade.get_versions().items)
2250 if CONTEXT_API_VERSION in versions:
2251 current_policy_config = list(
2252 blade.get_worm_data_policies(
2253 names=[module.params["name"]], context_names=[module.params["context"]]
2254 ).items
2255 )[0]
2256 else:
2257 current_policy_config = list(
2258 blade.get_worm_data_policies(names=[module.params["name"]]).items
2259 )[0]
2260 current_policy = {
2261 "default_retention": current_policy_config.default_retention,
2262 "enabled": current_policy_config.enabled,
2263 "max_retention": current_policy_config.max_retention,
2264 "min_retention": current_policy_config.min_retention,
2265 "retention_lock": current_policy_config.retention_lock,
2266 }
2267 new_policy = {
2268 "default_retention": current_policy_config.default_retention,
2269 "enabled": current_policy_config.enabled,
2270 "max_retention": current_policy_config.max_retention,
2271 "min_retention": current_policy_config.min_retention,
2272 "retention_lock": current_policy_config.retention_lock,
2273 }
2274 if module.params["enabled"] != current_policy["enabled"]:
2275 new_policy["enabled"] = module.params["enabled"]
2276 if (
2277 module.params["retention_lock"]
2278 and module.params["retention_lock"] != current_policy["retention_lock"]
2279 ):
2280 new_policy["retention_lock"] = module.params["retention_lock"]
2281 if (
2282 module.params["default_retention"]
2283 and convert_time_to_millisecs(module.params["default_retention"])
2284 != current_policy["default_retention"]
2285 ):
2286 new_policy["default_retention"] = convert_time_to_millisecs(
2287 module.params["default_retention"]
2288 )
2289 if (
2290 module.params["max_retention"]
2291 and convert_time_to_millisecs(module.params["max_retention"])
2292 != current_policy["max_retention"]
2293 ):
2294 new_policy["max_retention"] = convert_time_to_millisecs(
2295 module.params["max_retention"]
2296 )
2297 if (
2298 module.params["min_retention"]
2299 and convert_time_to_millisecs(module.params["min_retention"])
2300 != current_policy["min_retention"]
2301 ):
2302 new_policy["min_retention"] = convert_time_to_millisecs(
2303 module.params["min_retention"]
2304 )
2305 if new_policy != current_policy:
2306 changed = True
2307 if not module.check_mode:
2308 worm_policy = WormDataPolicy(
2309 enabled=new_policy["enabled"],
2310 retention_lock=new_policy["retention_lock"],
2311 min_retention=new_policy["min_retention"],
2312 max_retention=new_policy["max_retention"],
2313 default_retention=new_policy["default_retention"],
2314 )
2315 if CONTEXT_API_VERSION in versions:
2316 res = blade.patch_worm_data_policies(
2317 names=[module.params["name"]],
2318 policy=worm_policy,
2319 context_names=[module.params["context"]],
2320 )
2321 else:
2322 res = blade.patch_worm_data_policies(
2323 names=[module.params["name"]], policy=worm_policy
2324 )
2325 if res.status_code != 200:
2326 module.fail_json(
2327 msg="Failed to update WORM data policy {0}. Error: {1}".format(
2328 module.params["name"],
2329 res.errors[0].message,
2330 )
2331 )
2332 module.exit_json(changed=changed)
2333
2334
2335 def update_nfs_policy(module, blade):
2336 """Update NFS Export Policy Rule"""
2337
2338 changed = False
2339 versions = list(blade.get_versions().items)
2340 if module.params["client"]:
2341 if CONTEXT_API_VERSION in versions:
2342 current_policy_rule = blade.get_nfs_export_policies_rules(
2343 policy_names=[module.params["name"]],
2344 filter="client='" + module.params["client"] + "'",
2345 context_names=[module.params["context"]],
2346 )
2347 else:
2348 current_policy_rule = blade.get_nfs_export_policies_rules(
2349 policy_names=[module.params["name"]],
2350 filter="client='" + module.params["client"] + "'",
2351 )
2352 if (
2353 current_policy_rule.status_code == 200
2354 and current_policy_rule.total_item_count == 0
2355 ):
2356 rule = NfsExportPolicyRule(
2357 client=module.params["client"],
2358 permission=module.params["permission"],
2359 access=module.params["access"],
2360 anonuid=module.params["anonuid"],
2361 anongid=module.params["anongid"],
2362 fileid_32bit=module.params["fileid_32bit"],
2363 atime=module.params["atime"],
2364 secure=module.params["secure"],
2365 security=module.params["security"],
2366 )
2367 changed = True
2368 if not module.check_mode:
2369 if module.params["before_rule"]:
2370 before_name = (
2371 module.params["name"] + "." + str(module.params["before_rule"])
2372 )
2373 if CONTEXT_API_VERSION in versions:
2374 res = blade.post_nfs_export_policies_rules(
2375 policy_names=[module.params["name"]],
2376 rule=rule,
2377 before_rule_name=before_name,
2378 context_names=[module.params["context"]],
2379 )
2380 else:
2381 res = blade.post_nfs_export_policies_rules(
2382 policy_names=[module.params["name"]],
2383 rule=rule,
2384 before_rule_name=before_name,
2385 )
2386 else:
2387 if CONTEXT_API_VERSION in versions:
2388 res = blade.post_nfs_export_policies_rules(
2389 policy_names=[module.params["name"]],
2390 rule=rule,
2391 context_names=[module.params["context"]],
2392 )
2393 else:
2394 res = blade.post_nfs_export_policies_rules(
2395 policy_names=[module.params["name"]],
2396 rule=rule,
2397 )
2398 if res.status_code != 200:
2399 module.fail_json(
2400 msg="Failed to create rule for client {0} "
2401 "in export policy {1}. Error: {2}".format(
2402 module.params["client"],
2403 module.params["name"],
2404 res.errors[0].message,
2405 )
2406 )
2407 else:
2408 rules = list(current_policy_rule.items)
2409 cli_count = None
2410 done = False
2411 if module.params["client"] == "*":
2412 for cli in range(len(rules)):
2413 if rules[cli].client == "*":
2414 cli_count = cli
2415 if not cli_count:
2416 rule = NfsExportPolicyRule(
2417 client=module.params["client"],
2418 permission=module.params["permission"],
2419 access=module.params["access"],
2420 anonuid=module.params["anonuid"],
2421 anongid=module.params["anongid"],
2422 fileid_32bit=module.params["fileid_32bit"],
2423 atime=module.params["atime"],
2424 secure=module.params["secure"],
2425 security=module.params["security"],
2426 )
2427 done = True
2428 changed = True
2429 if not module.check_mode:
2430 if module.params["before_rule"]:
2431 if CONTEXT_API_VERSION in versions:
2432 res = blade.post_nfs_export_policies_rules(
2433 policy_names=[module.params["name"]],
2434 rule=rule,
2435 before_rule_name=(
2436 module.params["name"]
2437 + "."
2438 + str(module.params["before_rule"]),
2439 ),
2440 context_names=[module.params["context"]],
2441 )
2442 else:
2443 res = blade.post_nfs_export_policies_rules(
2444 policy_names=[module.params["name"]],
2445 rule=rule,
2446 before_rule_name=(
2447 module.params["name"]
2448 + "."
2449 + str(module.params["before_rule"]),
2450 ),
2451 )
2452 else:
2453 if CONTEXT_API_VERSION in versions:
2454 res = blade.post_nfs_export_policies_rules(
2455 policy_names=[module.params["name"]],
2456 rule=rule,
2457 context_names=[module.params["context"]],
2458 )
2459 else:
2460 res = blade.post_nfs_export_policies_rules(
2461 policy_names=[module.params["name"]],
2462 rule=rule,
2463 )
2464 if res.status_code != 200:
2465 module.fail_json(
2466 msg="Failed to create rule for "
2467 "client {0} in export policy {1}. Error: {2}".format(
2468 module.params["client"],
2469 module.params["name"],
2470 res.errors[0].message,
2471 )
2472 )
2473 if not done:
2474 old_policy_rule = rules[0]
2475 current_rule = {
2476 "anongid": getattr(old_policy_rule, "anongid", None),
2477 "anonuid": getattr(old_policy_rule, "anonuid", None),
2478 "atime": old_policy_rule.atime,
2479 "client": sorted(old_policy_rule.client),
2480 "fileid_32bit": old_policy_rule.fileid_32bit,
2481 "permission": sorted(old_policy_rule.permission),
2482 "secure": old_policy_rule.secure,
2483 "security": sorted(old_policy_rule.security),
2484 }
2485 if module.params["permission"]:
2486 new_permission = sorted(module.params["permission"])
2487 else:
2488 new_permission = sorted(current_rule["permission"])
2489 if module.params["client"]:
2490 new_client = sorted(module.params["client"])
2491 else:
2492 new_client = sorted(current_rule["client"])
2493 if module.params["security"]:
2494 new_security = sorted(module.params["security"])
2495 else:
2496 new_security = sorted(current_rule["security"])
2497 if module.params["anongid"]:
2498 new_anongid = module.params["anongid"]
2499 else:
2500 new_anongid = current_rule["anongid"]
2501 if module.params["anonuid"]:
2502 new_anonuid = module.params["anonuid"]
2503 else:
2504 new_anonuid = current_rule["anonuid"]
2505 if module.params["atime"] != current_rule["atime"]:
2506 new_atime = module.params["atime"]
2507 else:
2508 new_atime = current_rule["atime"]
2509 if module.params["secure"] != current_rule["secure"]:
2510 new_secure = module.params["secure"]
2511 else:
2512 new_secure = current_rule["secure"]
2513 if module.params["fileid_32bit"] != current_rule["fileid_32bit"]:
2514 new_fileid_32bit = module.params["fileid_32bit"]
2515 else:
2516 new_fileid_32bit = current_rule["fileid_32bit"]
2517 new_rule = {
2518 "anongid": new_anongid,
2519 "anonuid": new_anonuid,
2520 "atime": new_atime,
2521 "client": new_client,
2522 "fileid_32bit": new_fileid_32bit,
2523 "permission": new_permission,
2524 "secure": new_secure,
2525 "security": new_security,
2526 }
2527 if current_rule != new_rule:
2528 changed = True
2529 if not module.check_mode:
2530 rule = NfsExportPolicyRule(
2531 client=module.params["client"],
2532 permission=module.params["permission"],
2533 access=module.params["access"],
2534 anonuid=module.params["anonuid"],
2535 anongid=module.params["anongid"],
2536 fileid_32bit=module.params["fileid_32bit"],
2537 atime=module.params["atime"],
2538 secure=module.params["secure"],
2539 security=module.params["security"],
2540 )
2541 if CONTEXT_API_VERSION in versions:
2542 res = blade.patch_nfs_export_policies_rules(
2543 names=[
2544 module.params["name"]
2545 + "."
2546 + str(old_policy_rule.index)
2547 ],
2548 rule=rule,
2549 context_names=[module.params["context"]],
2550 )
2551 else:
2552 res = blade.patch_nfs_export_policies_rules(
2553 names=[
2554 module.params["name"]
2555 + "."
2556 + str(old_policy_rule.index)
2557 ],
2558 rule=rule,
2559 )
2560 if res.status_code != 200:
2561 module.fail_json(
2562 msg="Failed to update NFS export rule {0}. Error: {1}".format(
2563 module.params["name"]
2564 + "."
2565 + str(old_policy_rule.index),
2566 res.errors[0].message,
2567 )
2568 )
2569 if (
2570 module.params["before_rule"]
2571 and module.params["before_rule"] != old_policy_rule.index
2572 ):
2573 changed = True
2574 if not module.check_mode:
2575 before_name = (
2576 module.params["name"]
2577 + "."
2578 + str(module.params["before_rule"])
2579 )
2580 if CONTEXT_API_VERSION in versions:
2581 res = blade.patch_nfs_export_policies_rules(
2582 names=[
2583 module.params["name"]
2584 + "."
2585 + str(old_policy_rule.index)
2586 ],
2587 rule=NfsExportPolicyRule(),
2588 before_rule_name=before_name,
2589 context_names=[module.params["context"]],
2590 )
2591 else:
2592 res = blade.patch_nfs_export_policies_rules(
2593 names=[
2594 module.params["name"]
2595 + "."
2596 + str(old_policy_rule.index)
2597 ],
2598 rule=NfsExportPolicyRule(),
2599 before_rule_name=before_name,
2600 )
2601 if res.status_code != 200:
2602 module.fail_json(
2603 msg="Failed to move NFS export rule {0}. Error: {1}".format(
2604 module.params["name"]
2605 + "."
2606 + str(old_policy_rule.index),
2607 res.errors[0].message,
2608 )
2609 )
2610 if CONTEXT_API_VERSION in versions:
2611 current_policy = list(
2612 blade.get_nfs_export_policies(
2613 names=[module.params["name"]], context_names=[module.params["context"]]
2614 ).items
2615 )[0]
2616 else:
2617 current_policy = list(
2618 blade.get_nfs_export_policies(names=[module.params["name"]]).items
2619 )[0]
2620 if current_policy.enabled != module.params["enabled"]:
2621 changed = True
2622 if not module.check_mode:
2623 if CONTEXT_API_VERSION in versions:
2624 res = blade.patch_nfs_export_policies(
2625 policy=NfsExportPolicy(enabled=module.params["enabled"]),
2626 names=[module.params["name"]],
2627 context_names=[module.params["context"]],
2628 )
2629 else:
2630 res = blade.patch_nfs_export_policies(
2631 policy=NfsExportPolicy(enabled=module.params["enabled"]),
2632 names=[module.params["name"]],
2633 )
2634 if res.status_code != 200:
2635 module.fail_json(
2636 msg="Failed to change state of nfs export policy {0}.Error: {1}".format(
2637 module.params["name"], res.errors[0].message
2638 )
2639 )
2640 module.exit_json(changed=changed)
2641
2642
2643 def create_nfs_policy(module, blade):
2644 """Create NFS Export Policy"""
2645 changed = True
2646 versions = list(blade.get_versions().items)
2647 if not module.check_mode:
2648 if CONTEXT_API_VERSION in versions:
2649 res = blade.post_nfs_export_policies(
2650 names=[module.params["name"]], context_names=[module.params["context"]]
2651 )
2652 else:
2653 res = blade.post_nfs_export_policies(names=[module.params["name"]])
2654 if res.status_code != 200:
2655 module.fail_json(
2656 msg="Failed to create nfs export policy {0}.Error: {1}".format(
2657 module.params["name"], res.errors[0].message
2658 )
2659 )
2660 if not module.params["enabled"]:
2661 if CONTEXT_API_VERSION in versions:
2662 res = blade.patch_nfs_export_policies(
2663 policy=NfsExportPolicy(enabled=False),
2664 names=[module.params["name"]],
2665 context_names=[module.params["context"]],
2666 )
2667 else:
2668 res = blade.patch_nfs_export_policies(
2669 policy=NfsExportPolicy(enabled=False), names=[module.params["name"]]
2670 )
2671 if res.status_code != 200:
2672 if CONTEXT_API_VERSION in versions:
2673 blade.delete_nfs_export_policies(
2674 names=[module.params["name"]],
2675 context_names=[module.params["context"]],
2676 )
2677 else:
2678 blade.delete_nfs_export_policies(names=[module.params["name"]])
2679 module.fail_json(
2680 msg="Failed to create nfs export policy {0}.Error: {1}".format(
2681 module.params["name"], res.errors[0].message
2682 )
2683 )
2684 if module.params["client"]:
2685 rule = NfsExportPolicyRule(
2686 client=module.params["client"],
2687 permission=module.params["permission"],
2688 access=module.params["access"],
2689 anonuid=module.params["anonuid"],
2690 anongid=module.params["anongid"],
2691 fileid_32bit=module.params["fileid_32bit"],
2692 atime=module.params["atime"],
2693 secure=module.params["secure"],
2694 security=module.params["security"],
2695 )
2696 if CONTEXT_API_VERSION in versions:
2697 res = blade.post_nfs_export_policies_rules(
2698 policy_names=[module.params["name"]],
2699 rule=rule,
2700 context_names=[module.params["context"]],
2701 )
2702 else:
2703 res = blade.post_nfs_export_policies_rules(
2704 policy_names=[module.params["name"]],
2705 rule=rule,
2706 )
2707 if res.status_code != 200:
2708 module.fail_json(
2709 msg="Failed to rule for policy {0}. Error: {1}".format(
2710 module.params["name"],
2711 res.errors[0].message,
2712 )
2713 )
2714 module.exit_json(changed=changed)
2715
2716
2717 def delete_os_policy(module, blade):
2718 """Delete Object Store Access Policy, Rule, or User
2719
2720 If rule is provided then delete the rule if it exists.
2721 If user is provided then remove grant from user if granted.
2722 If no user or rule provided delete the whole policy.
2723 Cannot delete a policy with attached users, so delete all users
2724 if the force_delete option is selected.
2725 """
2726
2727 changed = False
2728 versions = list(blade.get_versions().items)
2729 policy_name = module.params["account"] + "/" + module.params["name"]
2730 policy_delete = True
2731 if module.params["rule"]:
2732 policy_delete = False
2733 if CONTEXT_API_VERSION in versions:
2734 res = blade.get_object_store_access_policies_rules(
2735 policy_names=[policy_name],
2736 names=[module.params["rule"]],
2737 context_names=[module.params["context"]],
2738 )
2739 else:
2740 res = blade.get_object_store_access_policies_rules(
2741 policy_names=[policy_name], names=[module.params["rule"]]
2742 )
2743 if res.status_code == 200 and res.total_item_count != 0:
2744 changed = True
2745 if not module.check_mode:
2746 if CONTEXT_API_VERSION in versions:
2747 res = blade.delete_object_store_access_policies_rules(
2748 policy_names=[policy_name],
2749 names=[module.params["rule"]],
2750 context_names=[module.params["context"]],
2751 )
2752 else:
2753 res = blade.delete_object_store_access_policies_rules(
2754 policy_names=[policy_name], names=[module.params["rule"]]
2755 )
2756 if res.status_code != 200:
2757 module.fail_json(
2758 msg="Failed to delete users from policy {0}. Error: {1} - {2}".format(
2759 policy_name, res.errors[0].context, res.errors[0].message
2760 )
2761 )
2762
2763 if module.params["user"]:
2764 member_name = module.params["account"] + "/" + module.params["user"]
2765 policy_delete = False
2766 if CONTEXT_API_VERSION in versions:
2767 res = blade.get_object_store_access_policies_object_store_users(
2768 policy_names=[policy_name],
2769 member_names=[member_name],
2770 context_names=[module.params["context"]],
2771 )
2772 else:
2773 res = blade.get_object_store_access_policies_object_store_users(
2774 policy_names=[policy_name], member_names=[member_name]
2775 )
2776 if res.status_code == 200 and res.total_item_count != 0:
2777 changed = True
2778 if not module.check_mode:
2779 member_name = module.params["account"] + "/" + module.params["user"]
2780 if CONTEXT_API_VERSION in versions:
2781 res = blade.delete_object_store_access_policies_object_store_users(
2782 policy_names=[policy_name],
2783 member_names=[member_name],
2784 context_names=[module.params["context"]],
2785 )
2786 else:
2787 res = blade.delete_object_store_access_policies_object_store_users(
2788 policy_names=[policy_name], member_names=[member_name]
2789 )
2790 if res.status_code != 200:
2791 module.fail_json(
2792 msg="Failed to delete users from policy {0}. Error: {1} - {2}".format(
2793 policy_name, res.errors[0].context, res.errors[0].message
2794 )
2795 )
2796
2797 if policy_delete:
2798 if module.params["account"].lower() == "pure:policy":
2799 module.fail_json(msg="System-Wide policies cannot be deleted.")
2800 if CONTEXT_API_VERSION in versions:
2801 policy_users = list(
2802 blade.get_object_store_access_policies_object_store_users(
2803 policy_names=[policy_name], context_names=[module.params["context"]]
2804 ).items
2805 )
2806 else:
2807 policy_users = list(
2808 blade.get_object_store_access_policies_object_store_users(
2809 policy_names=[policy_name]
2810 ).items
2811 )
2812 if len(policy_users) == 0:
2813 changed = True
2814 if not module.check_mode:
2815 if CONTEXT_API_VERSION in versions:
2816 res = blade.delete_object_store_access_policies(
2817 names=[policy_name], context_names=[module.params["context"]]
2818 )
2819 else:
2820 res = blade.delete_object_store_access_policies(names=[policy_name])
2821 if res.status_code != 200:
2822 module.fail_json(
2823 msg="Failed to delete policy {0}. Error: {1}".format(
2824 policy_name, res.errors[0].message
2825 )
2826 )
2827 else:
2828 if module.params["force_delete"]:
2829 changed = True
2830 if not module.check_mode:
2831 for user in range(len(policy_users)):
2832 if CONTEXT_API_VERSION in versions:
2833 res = blade.delete_object_store_access_policies_object_store_users(
2834 member_names=[policy_users[user].member.name],
2835 policy_names=[policy_name],
2836 context_names=[module.params["context"]],
2837 )
2838 else:
2839 res = blade.delete_object_store_access_policies_object_store_users(
2840 member_names=[policy_users[user].member.name],
2841 policy_names=[policy_name],
2842 )
2843 if res.status_code != 200:
2844 module.fail_json(
2845 msg="Failed to delete user {0} from policy {1}, "
2846 "Error: {2}".format(
2847 policy_users[user].member,
2848 policy_name,
2849 res.errors[0].message,
2850 )
2851 )
2852 if CONTEXT_API_VERSION in versions:
2853 res = blade.delete_object_store_access_policies(
2854 names=[policy_name],
2855 context_names=[module.params["context"]],
2856 )
2857 else:
2858 res = blade.delete_object_store_access_policies(
2859 names=[policy_name]
2860 )
2861 if res.status_code != 200:
2862 module.fail_json(
2863 msg="Failed to delete policy {0}. Error: {1}".format(
2864 policy_name, res.errors[0].message
2865 )
2866 )
2867 else:
2868 module.fail_json(
2869 msg="Policy {0} cannot be deleted with connected users".format(
2870 policy_name
2871 )
2872 )
2873 module.exit_json(changed=changed)
2874
2875
2876 def create_os_policy(module, blade):
2877 """Create Object Store Access Policy"""
2878 changed = True
2879 policy_name = module.params["account"] + "/" + module.params["name"]
2880 versions = list(blade.get_versions().items)
2881 if not module.check_mode:
2882 if CONTEXT_API_VERSION in versions:
2883 res = blade.post_object_store_access_policies(
2884 names=[policy_name],
2885 policy=ObjectStoreAccessPolicyPost(description=module.params["desc"]),
2886 context_names=[module.params["context"]],
2887 )
2888 else:
2889 res = blade.post_object_store_access_policies(
2890 names=[policy_name],
2891 policy=ObjectStoreAccessPolicyPost(description=module.params["desc"]),
2892 )
2893 if res.status_code != 200:
2894 module.fail_json(
2895 msg="Failed to create access policy {0}.".format(policy_name)
2896 )
2897 if module.params["rule"]:
2898 if not module.params["actions"] or not module.params["object_resources"]:
2899 module.fail_json(
2900 msg="Parameters `actions` and `object_resources` "
2901 "are required to create a new rule"
2902 )
2903 conditions = PolicyRuleObjectAccessCondition(
2904 source_ips=module.params["source_ips"],
2905 s3_delimiters=module.params["s3_delimiters"],
2906 s3_prefixes=module.params["s3_prefixes"],
2907 )
2908 if SMB_ENCRYPT_API_VERSION in versions:
2909 rule = PolicyRuleObjectAccessPost(
2910 actions=module.params["actions"],
2911 resources=module.params["object_resources"],
2912 conditions=conditions,
2913 effect=module.params["effect"],
2914 )
2915 else:
2916 rule = PolicyRuleObjectAccessPost(
2917 actions=module.params["actions"],
2918 resources=module.params["object_resources"],
2919 conditions=conditions,
2920 )
2921 if CONTEXT_API_VERSION in versions:
2922 res = blade.post_object_store_access_policies_rules(
2923 policy_names=policy_name,
2924 names=[module.params["rule"]],
2925 enforce_action_restrictions=module.params["ignore_enforcement"],
2926 rule=rule,
2927 context_names=[module.params["context"]],
2928 )
2929 else:
2930 res = blade.post_object_store_access_policies_rules(
2931 policy_names=policy_name,
2932 names=[module.params["rule"]],
2933 enforce_action_restrictions=module.params["ignore_enforcement"],
2934 rule=rule,
2935 )
2936 if res.status_code != 200:
2937 module.fail_json(
2938 msg="Failed to create rule {0} to policy {1}. Error: {2}".format(
2939 module.params["rule"], policy_name, res.errors[0].message
2940 )
2941 )
2942 if module.params["user"]:
2943 member_name = module.params["account"] + "/" + module.params["user"]
2944 if CONTEXT_API_VERSION in versions:
2945 res = blade.post_object_store_access_policies_object_store_users(
2946 member_names=[member_name],
2947 policy_names=[policy_name],
2948 context_names=[module.params["context"]],
2949 )
2950 else:
2951 res = blade.post_object_store_access_policies_object_store_users(
2952 member_names=[member_name], policy_names=[policy_name]
2953 )
2954 if res.status_code != 200:
2955 module.fail_json(
2956 msg="Failed to add users to policy {0}. Error: {1} - {2}".format(
2957 policy_name, res.errors[0].context, res.errors[0].message
2958 )
2959 )
2960 module.exit_json(changed=changed)
2961
2962
2963 def update_os_policy(module, blade):
2964 """Update Object Store Access Policy"""
2965 changed = False
2966 versions = list(blade.get_versions().items)
2967 policy_name = module.params["account"] + "/" + module.params["name"]
2968 if module.params["rule"]:
2969 if CONTEXT_API_VERSION in versions:
2970 current_policy_rule = blade.get_object_store_access_policies_rules(
2971 policy_names=[policy_name],
2972 names=[module.params["rule"]],
2973 context_names=[module.params["context"]],
2974 )
2975 else:
2976 current_policy_rule = blade.get_object_store_access_policies_rules(
2977 policy_names=[policy_name], names=[module.params["rule"]]
2978 )
2979 if current_policy_rule.status_code != 200:
2980 changed = True
2981 if not module.check_mode:
2982 conditions = PolicyRuleObjectAccessCondition(
2983 source_ips=module.params["source_ips"],
2984 s3_delimiters=module.params["s3_delimiters"],
2985 s3_prefixes=module.params["s3_prefixes"],
2986 )
2987 rule = PolicyRuleObjectAccessPost(
2988 actions=module.params["actions"],
2989 resources=module.params["object_resources"],
2990 conditions=conditions,
2991 )
2992 if CONTEXT_API_VERSION in versions:
2993 res = blade.post_object_store_access_policies_rules(
2994 policy_names=policy_name,
2995 names=[module.params["rule"]],
2996 enforce_action_restrictions=module.params["ignore_enforcement"],
2997 rule=rule,
2998 context_names=[module.params["context"]],
2999 )
3000 else:
3001 res = blade.post_object_store_access_policies_rules(
3002 policy_names=policy_name,
3003 names=[module.params["rule"]],
3004 enforce_action_restrictions=module.params["ignore_enforcement"],
3005 rule=rule,
3006 )
3007 if res.status_code != 200:
3008 module.fail_json(
3009 msg="Failed to create rule {0} in policy {1}. Error: {2}".format(
3010 module.params["rule"], policy_name, res.errors[0].message
3011 )
3012 )
3013 else:
3014 old_policy_rule = list(current_policy_rule.items)[0]
3015 current_rule = {
3016 "actions": old_policy_rule.actions,
3017 "resources": old_policy_rule.resources,
3018 "ips": getattr(old_policy_rule.conditions, "source_ips", None),
3019 "prefixes": getattr(old_policy_rule.conditions, "s3_prefixes", None),
3020 "delimiters": getattr(
3021 old_policy_rule.conditions, "s3_delimiters", None
3022 ),
3023 }
3024 if module.params["actions"]:
3025 new_actions = sorted(module.params["actions"])
3026 else:
3027 new_actions = sorted(current_rule["actions"])
3028 if module.params["object_resources"]:
3029 new_resources = sorted(module.params["object_resources"])
3030 else:
3031 new_resources = sorted(current_rule["resources"])
3032 if module.params["s3_prefixes"]:
3033 new_prefixes = sorted(module.params["s3_prefixes"])
3034 elif current_rule["prefixes"]:
3035 new_prefixes = sorted(current_rule["prefixes"])
3036 else:
3037 new_prefixes = None
3038 if module.params["s3_delimiters"]:
3039 new_delimiters = sorted(module.params["s3_delimiters"])
3040 elif current_rule["delimiters"]:
3041 new_delimiters = sorted(current_rule["delimiters"])
3042 else:
3043 new_delimiters = None
3044 if module.params["source_ips"]:
3045 new_ips = sorted(module.params["source_ips"])
3046 elif current_rule["ips"]:
3047 new_ips = sorted(current_rule["source_ips"])
3048 else:
3049 new_ips = None
3050 new_rule = {
3051 "actions": new_actions,
3052 "resources": new_resources,
3053 "ips": new_ips,
3054 "prefixes": new_prefixes,
3055 "delimiters": new_delimiters,
3056 }
3057 if current_rule != new_rule:
3058 changed = True
3059 if not module.check_mode:
3060 conditions = PolicyRuleObjectAccessCondition(
3061 source_ips=new_rule["ips"],
3062 s3_prefixes=new_rule["prefixes"],
3063 s3_delimiters=new_rule["delimiters"],
3064 )
3065 rule = PolicyRuleObjectAccess(
3066 actions=new_rule["actions"],
3067 resources=new_rule["resources"],
3068 conditions=conditions,
3069 )
3070 if CONTEXT_API_VERSION in versions:
3071 res = blade.patch_object_store_access_policies_rules(
3072 policy_names=[policy_name],
3073 names=[module.params["rule"]],
3074 rule=rule,
3075 enforce_action_restrictions=module.params[
3076 "ignore_enforcement"
3077 ],
3078 context_names=[module.params["context"]],
3079 )
3080 else:
3081 res = blade.patch_object_store_access_policies_rules(
3082 policy_names=[policy_name],
3083 names=[module.params["rule"]],
3084 rule=rule,
3085 enforce_action_restrictions=module.params[
3086 "ignore_enforcement"
3087 ],
3088 )
3089 if res.status_code != 200:
3090 module.fail_json(
3091 msg="Failed to update rule {0} in policy {1}. Error: {2}".format(
3092 module.params["rule"],
3093 policy_name,
3094 res.errors[0].message,
3095 )
3096 )
3097 if module.params["user"]:
3098 member_name = module.params["account"] + "/" + module.params["user"]
3099 if CONTEXT_API_VERSION in versions:
3100 res = blade.get_object_store_access_policies_object_store_users(
3101 policy_names=[policy_name],
3102 member_names=[member_name],
3103 context_names=[module.params["context"]],
3104 )
3105 else:
3106 res = blade.get_object_store_access_policies_object_store_users(
3107 policy_names=[policy_name], member_names=[member_name]
3108 )
3109 if res.status_code != 200 or (
3110 res.status_code == 200 and res.total_item_count == 0
3111 ):
3112 changed = True
3113 if not module.check_mode:
3114 if CONTEXT_API_VERSION in versions:
3115 res = blade.post_object_store_access_policies_object_store_users(
3116 member_names=[member_name],
3117 policy_names=[policy_name],
3118 context_names=[module.params["context"]],
3119 )
3120 else:
3121 res = blade.post_object_store_access_policies_object_store_users(
3122 member_names=[member_name], policy_names=[policy_name]
3123 )
3124 if res.status_code != 200:
3125 module.fail_json(
3126 msg="Failed to add user {0} to policy {1}. Error: {2}".format(
3127 member_name, policy_name, res.errors[0].message
3128 )
3129 )
3130 module.exit_json(changed=changed)
3131
3132
3133 def copy_os_policy_rule(module, blade):
3134 """Copy an existing policy rule to a new policy"""
3135 changed = True
3136 versions = list(blade.get_versions().items)
3137 policy_name = module.params["account"] + "/" + module.params["name"]
3138 if not module.params["target_rule"]:
3139 module.params["target_rule"] = module.params["rule"]
3140 if CONTEXT_API_VERSION in versions:
3141 res = blade.get_object_store_access_policies_rules(
3142 policy_names=[module.params["target"]],
3143 names=[module.params["target_rule"]],
3144 context_names=[module.params["context"]],
3145 )
3146 else:
3147 res = blade.get_object_store_access_policies_rules(
3148 policy_names=[module.params["target"]], names=[module.params["target_rule"]]
3149 )
3150 if res.status_code == 200:
3151 module.fail_json(
3152 msg="Target rule {0} already exists in policy {1}".format(
3153 module.params["target_rule"], policy_name
3154 )
3155 )
3156 if CONTEXT_API_VERSION in versions:
3157 current_rule = list(
3158 blade.get_object_store_access_policies_rules(
3159 policy_names=[policy_name],
3160 names=[module.params["rule"]],
3161 context_names=[module.params["context"]],
3162 ).items
3163 )[0]
3164 else:
3165 current_rule = list(
3166 blade.get_object_store_access_policies_rules(
3167 policy_names=[policy_name], names=[module.params["rule"]]
3168 ).items
3169 )[0]
3170 if not module.check_mode:
3171 conditions = PolicyRuleObjectAccessCondition(
3172 source_ips=current_rule.conditions.source_ips,
3173 s3_delimiters=current_rule.conditions.s3_delimiters,
3174 s3_prefixes=current_rule.conditions.s3_prefixes,
3175 )
3176 rule = PolicyRuleObjectAccessPost(
3177 actions=current_rule.actions,
3178 resources=current_rule.resources,
3179 conditions=conditions,
3180 )
3181 if CONTEXT_API_VERSION in versions:
3182 res = blade.post_object_store_access_policies_rules(
3183 policy_names=module.params["target"],
3184 names=[module.params["target_rule"]],
3185 enforce_action_restrictions=module.params["ignore_enforcement"],
3186 rule=rule,
3187 context_names=[module.params["context"]],
3188 )
3189 else:
3190 res = blade.post_object_store_access_policies_rules(
3191 policy_names=module.params["target"],
3192 names=[module.params["target_rule"]],
3193 enforce_action_restrictions=module.params["ignore_enforcement"],
3194 rule=rule,
3195 )
3196 if res.status_code != 200:
3197 module.fail_json(
3198 msg="Failed to copy rule {0} from policy {1} to policy {2}. "
3199 "Error: {3}".format(
3200 module.params["rule"],
3201 policy_name,
3202 module.params["target"],
3203 res.errors[0].message,
3204 )
3205 )
3206 module.exit_json(changed=changed)
3207
3208
3209 def delete_snap_policy(module, blade):
3210 """Delete snapshot policy
3211
3212 If any rule parameters are provided then delete any rules that match
3213 all of the parameters provided.
3214 If no rule parameters are provided delete the entire policy
3215 """
3216
3217 changed = False
3218 versions = list(blade.get_versions().items)
3219 rule_delete = False
3220 if (
3221 module.params["at"]
3222 or module.params["every"]
3223 or module.params["timezone"]
3224 or module.params["keep_for"]
3225 ):
3226 rule_delete = True
3227 if rule_delete:
3228 if CONTEXT_API_VERSION in versions:
3229 current_rules = list(
3230 blade.get_policies(
3231 names=[module.params["name"]],
3232 context_names=[module.params["context"]],
3233 ).items
3234 )[0].rules
3235 else:
3236 current_rules = list(
3237 blade.get_policies(names=[module.params["name"]]).items
3238 )[0].rules
3239 for rule in range(len(current_rules)):
3240 current_rule = {
3241 "at": current_rules[rule].at,
3242 "every": current_rules[rule].every,
3243 "keep_for": current_rules[rule].keep_for,
3244 "time_zone": current_rules[rule].time_zone,
3245 }
3246 if not module.params["at"]:
3247 delete_at = current_rules[rule].at
3248 else:
3249 delete_at = _convert_to_millisecs(module.params["at"])
3250 if module.params["keep_for"]:
3251 delete_keep_for = module.params["keep_for"]
3252 else:
3253 delete_keep_for = int(current_rules[rule].keep_for / 1000)
3254 if module.params["every"]:
3255 delete_every = module.params["every"]
3256 else:
3257 delete_every = int(current_rules[rule].every / 1000)
3258 if not module.params["timezone"]:
3259 delete_tz = current_rules[rule].time_zone
3260 else:
3261 delete_tz = module.params["timezone"]
3262 delete_rule = {
3263 "at": delete_at,
3264 "every": delete_every * 1000,
3265 "keep_for": delete_keep_for * 1000,
3266 "time_zone": delete_tz,
3267 }
3268 if current_rule == delete_rule:
3269 changed = True
3270 attr = PolicyPatch(remove_rules=[delete_rule])
3271 if not module.check_mode:
3272 if CONTEXT_API_VERSION in versions:
3273 res = blade.patch_policies(
3274 destroy_snapshots=module.params["destroy_snapshots"],
3275 names=[module.params["name"]],
3276 policy=attr,
3277 context_names=[module.params["context"]],
3278 )
3279 else:
3280 res = blade.patch_policies(
3281 destroy_snapshots=module.params["destroy_snapshots"],
3282 names=[module.params["name"]],
3283 policy=attr,
3284 )
3285 if res.status_code != 200:
3286 module.fail_json(
3287 msg="Failed to delete policy rule {0}. Error: {1}".format(
3288 module.params["name"], res.errors[0].message
3289 )
3290 )
3291 else:
3292 changed = True
3293 if not module.check_mode:
3294 if CONTEXT_API_VERSION in versions:
3295 res = blade.delete_policies(
3296 names=[module.params["name"]],
3297 context_names=[module.params["context"]],
3298 )
3299 else:
3300 res = blade.delete_policies(names=[module.params["name"]])
3301 if res.status_code != 200:
3302 module.fail_json(
3303 msg="Failed to delete policy {0}. Error: {1}".format(
3304 module.params["name"], res.errors[0].message
3305 )
3306 )
3307 module.exit_json(changed=changed)
3308
3309
3310 def create_snap_policy(module, blade):
3311 """Create snapshot policy"""
3312 changed = True
3313 versions = list(blade.get_versions().items)
3314 if (
3315 module.params["keep_for"]
3316 and not module.params["every"]
3317 or module.params["every"]
3318 and not module.params["keep_for"]
3319 ):
3320 module.fail_json(msg="`keep_for` and `every` are required.")
3321 if module.params["timezone"] and not module.params["at"]:
3322 module.fail_json(msg="`timezone` requires `at` to be provided.")
3323 if module.params["at"] and not module.params["every"]:
3324 module.fail_json(msg="`at` requires `every` to be provided.")
3325
3326 if not module.check_mode:
3327 if module.params["at"] and module.params["every"]:
3328 if not module.params["every"] % 86400 == 0:
3329 module.fail_json(
3330 msg="At time can only be set if every value is a multiple of 86400"
3331 )
3332 if not module.params["timezone"]:
3333 module.params["timezone"] = _get_local_tz(module)
3334 if module.params["timezone"] not in pytz.all_timezones_set:
3335 module.fail_json(
3336 msg="Timezone {0} is not valid".format(
3337 module.params["timezone"]
3338 )
3339 )
3340 if not module.params["keep_for"]:
3341 module.params["keep_for"] = 0
3342 if not module.params["every"]:
3343 module.params["every"] = 0
3344 if module.params["keep_for"] < module.params["every"]:
3345 module.fail_json(
3346 msg="Retention period cannot be less than snapshot interval."
3347 )
3348 if module.params["at"] and not module.params["timezone"]:
3349 module.params["timezone"] = _get_local_tz(module)
3350 if module.params["timezone"] not in set(pytz.all_timezones_set):
3351 module.fail_json(
3352 msg="Timezone {0} is not valid".format(module.params["timezone"])
3353 )
3354
3355 if module.params["keep_for"]:
3356 if not 300 <= module.params["keep_for"] <= 34560000:
3357 module.fail_json(
3358 msg="keep_for parameter is out of range (300 to 34560000)"
3359 )
3360 if not 300 <= module.params["every"] <= 34560000:
3361 module.fail_json(
3362 msg="every parameter is out of range (300 to 34560000)"
3363 )
3364 if module.params["at"]:
3365 attr = Policy(
3366 enabled=module.params["enabled"],
3367 rules=[
3368 PolicyRule(
3369 keep_for=module.params["keep_for"] * 1000,
3370 every=module.params["every"] * 1000,
3371 at=_convert_to_millisecs(module.params["at"]),
3372 time_zone=module.params["timezone"],
3373 )
3374 ],
3375 )
3376 else:
3377 attr = Policy(
3378 enabled=module.params["enabled"],
3379 rules=[
3380 PolicyRule(
3381 keep_for=module.params["keep_for"] * 1000,
3382 every=module.params["every"] * 1000,
3383 )
3384 ],
3385 )
3386 else:
3387 attr = Policy(enabled=module.params["enabled"])
3388 if CONTEXT_API_VERSION in versions:
3389 res = blade.post_policies(
3390 names=[module.params["name"]],
3391 policy=attr,
3392 context_names=[module.params["context"]],
3393 )
3394 else:
3395 res = blade.post_policies(names=[module.params["name"]], policy=attr)
3396 if res.status_code != 200:
3397 module.fail_json(
3398 msg="Failed to create snapshot policy {0}. Error: {1}".format(
3399 module.params["name"], res.errors[0].message
3400 )
3401 )
3402 if module.params["filesystem"]:
3403 for filesystem in module.params["filesystem"]:
3404 if CONTEXT_API_VERSION in versions:
3405 res = blade.get_file_systems(
3406 names=[filesystem],
3407 destroyed=False,
3408 context_names=[module.params["context"]],
3409 )
3410 else:
3411 res = blade.get_file_systems(names=[filesystem], destroyed=False)
3412 if res.status_code != 200:
3413 module.fail_json(
3414 msg="Filesystems to assign to {0} does not "
3415 "exist, or is deleted.".format(module.params["name"])
3416 )
3417 if CONTEXT_API_VERSION in versions:
3418 res = blade.post_policies_file_systems(
3419 policy_names=[module.params["name"]],
3420 member_names=[filesystem],
3421 context_names=[module.params["context"]],
3422 )
3423 else:
3424 res = blade.post_policies_file_systems(
3425 policy_names=[module.params["name"]],
3426 member_names=[filesystem],
3427 )
3428 if res.status_code != 200:
3429 module.fail_json(
3430 msg="Failed to add filesystem {0} to "
3431 "policy {1}. Error: {2}.".format(
3432 filesystem, module.params["name"], res.errors[0].message
3433 )
3434 )
3435 if module.params["replica_link"]:
3436 repl_link = []
3437 for link in module.params["replica_link"]:
3438 if CONTEXT_API_VERSION in versions:
3439 res = blade.get_file_system_replica_links(
3440 local_file_system_names=[link],
3441 context_names=[module.params["context"]],
3442 )
3443 else:
3444 res = blade.get_file_system_replica_links(
3445 local_file_system_names=[link]
3446 )
3447 if res.status_code != 200:
3448 module.fail_json(
3449 msg="Replica Link {0} does not exist.".format(link)
3450 )
3451 else:
3452 repl_link = list(res.items)[0]
3453 if CONTEXT_API_VERSION in versions:
3454 res = blade.post_policies_file_system_replica_links(
3455 policy_names=[module.params["name"]],
3456 local_file_system_names=[link],
3457 remote_names=[repl_link.remote.name],
3458 context_names=[module.params["context"]],
3459 )
3460 else:
3461 res = blade.post_policies_file_system_replica_links(
3462 policy_names=[module.params["name"]],
3463 local_file_system_names=[link],
3464 remote_names=[repl_link.remote.name],
3465 )
3466 if res.status_code != 200:
3467 module.fail_json(
3468 msg="Failed to connect filesystem replicsa link {0} to policy {1}. "
3469 "Error: {2}".format(
3470 link, module.params["name"], res.errors[0].message
3471 )
3472 )
3473 module.exit_json(changed=changed)
3474
3475
3476 def update_snap_policy(module, blade):
3477 """Update snapshot policy
3478
3479 Add new rules to the policy using this function.
3480 Should it be necessary to modify an existing rule these are the rules:
3481
3482 Due to the 'best fit' nature of Purity we only add new rulkes in this function.
3483 If you trying to update an existing rule, then this should be done by deleting
3484 the current rule and then adding the new rule.
3485
3486 Purity may recover some snapshots as long as the add happens before the eradication delay
3487 (typically 24h) causes the snapshots to be eradicated.
3488 """
3489
3490 changed = False
3491 versions = list(blade.get_versions().items)
3492 if (
3493 module.params["keep_for"]
3494 and not module.params["every"]
3495 or module.params["every"]
3496 and not module.params["keep_for"]
3497 ):
3498 module.fail_json(msg="`keep_for` and `every` are required.")
3499 if module.params["timezone"] and not module.params["at"]:
3500 module.fail_json(msg="`timezone` requires `at` to be provided.")
3501 if module.params["at"] and not module.params["every"]:
3502 module.fail_json(msg="`at` requires `every` to be provided.")
3503 if CONTEXT_API_VERSION in versions:
3504 current_rules = list(
3505 blade.get_policies(
3506 names=[module.params["name"]], context_names=[module.params["context"]]
3507 ).items
3508 )[0].rules
3509 else:
3510 current_rules = list(blade.get_policies(names=[module.params["name"]]).items)[
3511 0
3512 ].rules
3513 create_new = False
3514 for rule in range(len(current_rules)):
3515 current_rule = {
3516 "at": current_rules[rule].at,
3517 "every": current_rules[rule].every,
3518 "keep_for": current_rules[rule].keep_for,
3519 "time_zone": current_rules[rule].time_zone,
3520 }
3521 if not module.params["at"]:
3522 new_at = current_rules[rule].at
3523 else:
3524 new_at = _convert_to_millisecs(module.params["at"])
3525 if module.params["keep_for"]:
3526 new_keep_for = module.params["keep_for"]
3527 else:
3528 new_keep_for = int(current_rules[rule].keep_for / 1000)
3529 if module.params["every"]:
3530 new_every = module.params["every"]
3531 else:
3532 new_every = int(current_rules[rule].every / 1000)
3533 if not module.params["timezone"]:
3534 new_tz = current_rules[rule].time_zone
3535 else:
3536 new_tz = module.params["timezone"]
3537 new_rule = {
3538 "at": new_at,
3539 "every": new_every * 1000,
3540 "keep_for": new_keep_for * 1000,
3541 "time_zone": new_tz,
3542 }
3543 if current_rule != new_rule:
3544 create_new = True
3545
3546 if create_new:
3547 changed = True
3548 if not module.check_mode:
3549 if module.params["at"] and module.params["every"]:
3550 if not module.params["every"] % 86400 == 0:
3551 module.fail_json(
3552 msg="At time can only be set if every value is a multiple of 86400"
3553 )
3554 if not module.params["timezone"]:
3555 module.params["timezone"] = _get_local_tz(module)
3556 if module.params["timezone"] not in pytz.all_timezones_set:
3557 module.fail_json(
3558 msg="Timezone {0} is not valid".format(
3559 module.params["timezone"]
3560 )
3561 )
3562 if not module.params["keep_for"]:
3563 module.params["keep_for"] = 0
3564 if not module.params["every"]:
3565 module.params["every"] = 0
3566 if module.params["keep_for"] < module.params["every"]:
3567 module.fail_json(
3568 msg="Retention period cannot be less than snapshot interval."
3569 )
3570 if module.params["at"] and not module.params["timezone"]:
3571 module.params["timezone"] = _get_local_tz(module)
3572 if module.params["timezone"] not in set(pytz.all_timezones_set):
3573 module.fail_json(
3574 msg="Timezone {0} is not valid".format(
3575 module.params["timezone"]
3576 )
3577 )
3578
3579 if module.params["keep_for"]:
3580 if not 300 <= module.params["keep_for"] <= 34560000:
3581 module.fail_json(
3582 msg="keep_for parameter is out of range (300 to 34560000)"
3583 )
3584 if not 300 <= module.params["every"] <= 34560000:
3585 module.fail_json(
3586 msg="every parameter is out of range (300 to 34560000)"
3587 )
3588 if module.params["at"]:
3589 attr = PolicyPatch(
3590 enabled=module.params["enabled"],
3591 add_rules=[
3592 PolicyRule(
3593 keep_for=module.params["keep_for"] * 1000,
3594 every=module.params["every"] * 1000,
3595 at=_convert_to_millisecs(module.params["at"]),
3596 time_zone=module.params["timezone"],
3597 )
3598 ],
3599 )
3600 else:
3601 attr = PolicyPatch(
3602 enabled=module.params["enabled"],
3603 add_rules=[
3604 PolicyRule(
3605 keep_for=module.params["keep_for"] * 1000,
3606 every=module.params["every"] * 1000,
3607 )
3608 ],
3609 )
3610 else:
3611 attr = PolicyPatch(enabled=module.params["enabled"])
3612 if CONTEXT_API_VERSION in versions:
3613 res = blade.patch_policies(
3614 names=[module.params["name"]],
3615 policy=attr,
3616 context_names=[module.params["context"]],
3617 )
3618 else:
3619 res = blade.patch_policies(
3620 names=[module.params["name"]],
3621 policy=attr,
3622 )
3623 if res.status_code != 200:
3624 module.fail_json(
3625 msg="Failed to update snapshot policy {0}. Error: {1}".format(
3626 module.params["name"], res.errors[0].message
3627 )
3628 )
3629
3630 if module.params["filesystem"]:
3631 current_filesystems = []
3632 if CONTEXT_API_VERSION in versions:
3633 policy_fs_details = list(
3634 blade.get_policies_file_systems(
3635 policy_names=[module.params["name"]],
3636 context_names=[module.params["context"]],
3637 ).items
3638 )
3639 else:
3640 policy_fs_details = list(
3641 blade.get_policies_file_systems(
3642 policy_names=[module.params["name"]]
3643 ).items
3644 )
3645 for member in range(len(policy_fs_details)):
3646 current_filesystems.append(policy_fs_details[member].member.name)
3647 if module.params["state"] == "present":
3648 difference_set = [
3649 item
3650 for item in module.params["filesystem"]
3651 if item not in current_filesystems
3652 ]
3653 for new_fs in difference_set:
3654 changed = True
3655 if CONTEXT_API_VERSION in versions:
3656 res = blade.get_file_systems(
3657 names=[new_fs],
3658 destroyed=False,
3659 context_names=[module.params["context"]],
3660 )
3661 else:
3662 res = blade.get_file_systems(names=[new_fs], destroyed=False)
3663 if res.status_code != 200:
3664 module.fail_json(
3665 msg="Filesystem {0} to assign to {1} does not "
3666 "exist, or is deleted.".format(new_fs, module.params["name"])
3667 )
3668 if CONTEXT_API_VERSION in versions:
3669 res = blade.post_policies_file_systems(
3670 policy_names=[module.params["name"]],
3671 member_names=[new_fs],
3672 context_names=[module.params["context"]],
3673 )
3674 else:
3675 res = blade.post_policies_file_systems(
3676 policy_names=[module.params["name"]],
3677 member_names=[new_fs],
3678 )
3679 if res.status_code != 200:
3680 module.fail_json(
3681 msg="Failed to add filesystem {0} to "
3682 "policy {1}. Error: {2}.".format(
3683 new_fs, module.params["name"], res.errors[0].message
3684 )
3685 )
3686 else:
3687 for old_fs in module.params["filesystem"]:
3688 if old_fs in current_filesystems:
3689 changed = True
3690 if CONTEXT_API_VERSION in versions:
3691 res = blade.delete_policies_file_systems(
3692 policy_names=[module.params["name"]],
3693 member_names=[old_fs],
3694 context_names=[module.params["context"]],
3695 )
3696 else:
3697 res = blade.delete_policies_file_systems(
3698 policy_names=[module.params["name"]],
3699 member_names=[old_fs],
3700 )
3701 if res.status_code != 200:
3702 module.fail_json(
3703 msg="Failed to remove filesystem {0} from "
3704 "policy {1}. Error: {2}.".format(
3705 old_fs, module.params["name"], res.errors[0].message
3706 )
3707 )
3708 if module.params["replica_link"]:
3709 current_rls = []
3710 if CONTEXT_API_VERSION in versions:
3711 policy_rl_details = list(
3712 blade.get_policies_file_system_replica_links(
3713 policy_names=[module.params["name"]],
3714 context_names=[module.params["context"]],
3715 ).items
3716 )
3717 else:
3718 policy_rl_details = list(
3719 blade.get_policies_file_system_replica_links(
3720 policy_names=[module.params["name"]]
3721 ).items
3722 )
3723 for member in range(len(policy_rl_details)):
3724 current_rls.append(policy_rl_details[member].member.name)
3725 if module.params["state"] == "present":
3726 difference_set = [
3727 item
3728 for item in module.params["replica_link"]
3729 if item not in current_rls
3730 ]
3731 for new_rl in difference_set:
3732 changed = True
3733 if CONTEXT_API_VERSION in versions:
3734 res = blade.get_file_systems_replica_links(
3735 names=[new_rl], context_names=[module.params["context"]]
3736 )
3737 else:
3738 res = blade.get_file_systems_replica_links(names=[new_rl])
3739 if res.status_code != 200:
3740 module.fail_json(
3741 msg="Replica link {0} to assign to {1} does not "
3742 "exist, or is deleted.".format(new_rl, module.params["name"])
3743 )
3744 if CONTEXT_API_VERSION in versions:
3745 res = blade.post_policies_file_system_replica_links(
3746 policy_names=[module.params["name"]],
3747 member_names=[new_rl],
3748 context_names=[module.params["context"]],
3749 )
3750 else:
3751 res = blade.post_policies_file_system_replica_links(
3752 policy_names=[module.params["name"]],
3753 member_names=[new_rl],
3754 )
3755 if res.status_code != 200:
3756 module.fail_json(
3757 msg="Failed to add replica link {0} to "
3758 "policy {1}. Error: {2}.".format(
3759 new_rl, module.params["name"], res.errors[0].message
3760 )
3761 )
3762 else:
3763 for old_rl in module.params["replica_link"]:
3764 if old_rl in current_rls:
3765 changed = True
3766 if CONTEXT_API_VERSION in versions:
3767 res = blade.delete_policies_file_system_replica_links(
3768 policy_names=[module.params["name"]],
3769 member_names=[old_rl],
3770 context_names=[module.params["context"]],
3771 )
3772 else:
3773 res = blade.delete_policies_file_system_replica_links(
3774 policy_names=[module.params["name"]],
3775 member_names=[old_rl],
3776 )
3777 if res.status_code != 200:
3778 module.fail_json(
3779 msg="Failed to remove replica link {0} from "
3780 "policy {1}. Error: {2}.".format(
3781 old_rl, module.params["name"], res.errors[0].message
3782 )
3783 )
3784
3785 module.exit_json(changed=changed)
3786
3787
3788 def main():
3789 argument_spec = purefb_argument_spec()
3790 argument_spec.update(
3791 dict(
3792 state=dict(
3793 type="str", default="present", choices=["absent", "present", "copy"]
3794 ),
3795 policy_type=dict(
3796 type="str",
3797 default="snapshot",
3798 choices=[
3799 "snapshot",
3800 "access",
3801 "nfs",
3802 "smb_share",
3803 "smb_client",
3804 "network",
3805 "worm",
3806 ],
3807 ),
3808 enabled=dict(type="bool", default=True),
3809 timezone=dict(type="str"),
3810 name=dict(type="str"),
3811 at=dict(type="str"),
3812 every=dict(type="int"),
3813 keep_for=dict(type="int"),
3814 filesystem=dict(type="list", elements="str"),
3815 replica_link=dict(type="list", elements="str"),
3816 account=dict(type="str"),
3817 target=dict(type="str"),
3818 target_rule=dict(type="str"),
3819 rename=dict(type="str"),
3820 rule=dict(type="str"),
3821 user=dict(type="str"),
3822 effect=dict(type="str", default="allow", choices=["allow", "deny"]),
3823 actions=dict(
3824 type="list",
3825 elements="str",
3826 choices=[
3827 "s3:*",
3828 "s3:AbortMultipartUpload",
3829 "s3:BypassGovernanceRetention",
3830 "s3:CreateBucket",
3831 "s3:DeleteBucket",
3832 "s3:DeleteObject",
3833 "s3:DeleteObjectVersion",
3834 "s3:ExtendSafemodeRetentionPeriod",
3835 "s3:GetBucketAcl",
3836 "s3:GetBucketLocation",
3837 "s3:GetBucketVersioning",
3838 "s3:GetLifecycleConfiguration",
3839 "s3:GetObject",
3840 "s3:GetObjectAcl",
3841 "s3:GetObjectLegalHold",
3842 "s3:GetObjectLockConfiguration",
3843 "s3:GetObjectRetention",
3844 "s3:GetObjectTagging",
3845 "s3:GetObjectVersion",
3846 "s3:GetObjectVersionTagging",
3847 "s3:ListAllMyBuckets",
3848 "s3:ListBucket",
3849 "s3:ListBucketMultipartUploads",
3850 "s3:ListBucketVersions",
3851 "s3:ListMultipartUploadParts",
3852 "s3:PutBucketVersioning",
3853 "s3:PutLifecycleConfiguration",
3854 "s3:PutObject",
3855 "s3:PutObjectLegalHold",
3856 "s3:PutObjectLockConfiguration",
3857 "s3:PutObjectRetention",
3858 "s3:ResolveSafemodeConflicts",
3859 ],
3860 ),
3861 object_resources=dict(type="list", elements="str"),
3862 source_ips=dict(type="list", elements="str"),
3863 s3_prefixes=dict(type="list", elements="str"),
3864 s3_delimiters=dict(type="list", elements="str"),
3865 ignore_enforcement=dict(type="bool", default=True),
3866 force_delete=dict(type="bool", default=False),
3867 access=dict(
3868 type="str",
3869 choices=["root-squash", "all-squash", "no-squash"],
3870 default="root-squash",
3871 ),
3872 anonuid=dict(type="str"),
3873 anongid=dict(type="str"),
3874 atime=dict(type="bool", default=True),
3875 client=dict(type="str"),
3876 fileid_32bit=dict(type="bool", default=False),
3877 permission=dict(type="str", choices=["rw", "ro"], default="ro"),
3878 secure=dict(type="bool", default=False),
3879 destroy_snapshots=dict(type="bool", default=False),
3880 security=dict(
3881 type="list",
3882 elements="str",
3883 choices=["sys", "krb5", "krb5i", "krb5p"],
3884 default=["sys"],
3885 ),
3886 before_rule=dict(type="int"),
3887 principal=dict(type="str"),
3888 change=dict(type="str", choices=["deny", "allow", ""]),
3889 read=dict(type="str", choices=["deny", "allow", ""]),
3890 full_control=dict(type="str", choices=["deny", "allow", ""]),
3891 smb_encryption=dict(
3892 type="str",
3893 default="optional",
3894 choices=["disabled", "optional", "required"],
3895 ),
3896 desc=dict(type="str", default=""),
3897 interfaces=dict(
3898 type="list",
3899 elements="str",
3900 choices=[
3901 "management-ssh",
3902 "management-rest-api",
3903 "management-web-ui",
3904 "snmp",
3905 "local-network-superuser-password-access",
3906 ],
3907 ),
3908 default_retention=dict(type="str"),
3909 min_retention=dict(type="str"),
3910 max_retention=dict(type="str"),
3911 retention_lock=dict(type="str", choices=["locked", "unlocked"]),
3912 context=dict(type="str", default=""),
3913 )
3914 )
3915
3916 required_together = [["keep_for", "every"]]
3917 required_if = [
3918 ["policy_type", "access", ["account", "name"]],
3919 ["policy_type", "nfs", ["name"]],
3920 ["policy_type", "smb_client", ["name"]],
3921 ["policy_type", "smb_share", ["name"]],
3922 ["policy_type", "network", ["interfaces"]],
3923 ]
3924
3925 module = AnsibleModule(
3926 argument_spec,
3927 required_together=required_together,
3928 required_if=required_if,
3929 supports_check_mode=True,
3930 )
3931
3932 if not HAS_PYTZ:
3933 module.fail_json(msg="pytz is required for this module")
3934
3935 state = module.params["state"]
3936 blade = get_system(module)
3937 versions = list(blade.get_versions().items)
3938 if module.params["policy_type"] == "access":
3939 if not HAS_PYPURECLIENT:
3940 module.fail_json(msg="py-pure-client sdk is required for this module")
3941 blade = get_system(module)
3942 try:
3943 policy = list(
3944 blade.get_object_store_access_policies(
3945 names=[module.params["account"] + "/" + module.params["name"]]
3946 ).items
3947 )[0]
3948 except AttributeError:
3949 policy = None
3950 if module.params["user"]:
3951 member_name = module.params["account"] + "/" + module.params["user"]
3952 res = blade.get_object_store_users(names=[member_name])
3953 if res.status_code != 200:
3954 module.fail_json(
3955 msg="User {0} does not exist in account {1}. Error: {2}".format(
3956 module.params["user"],
3957 module.params["account"],
3958 res.errors[0].message,
3959 )
3960 )
3961 if policy and state == "present":
3962 update_os_policy(module, blade)
3963 elif state == "present" and not policy:
3964 create_os_policy(module, blade)
3965 elif state == "absent" and policy:
3966 delete_os_policy(module, blade)
3967 elif state == "copy" and module.params["target"] and module.params["rule"]:
3968 if "/" not in module.params["target"]:
3969 module.fail_json(
3970 msg='Incorrect format for target policy. Must be "<account>/<name>"'
3971 )
3972 if (
3973 blade.get_object_store_access_policies(
3974 names=[module.params["target"]]
3975 ).status_code
3976 != 200
3977 ):
3978 module.fail_json(
3979 msg="Target policy {0} does not exist".format(
3980 module.params["target"]
3981 )
3982 )
3983 copy_os_policy_rule(module, blade)
3984 elif module.params["policy_type"] == "nfs":
3985 new_policy = None
3986 if NFS_POLICY_API_VERSION not in versions:
3987 module.fail_json(
3988 msg=(
3989 "Minimum FlashBlade REST version required: {0}".format(
3990 NFS_POLICY_API_VERSION
3991 )
3992 )
3993 )
3994 if not HAS_PYPURECLIENT:
3995 module.fail_json(msg="py-pure-client sdk is required for this module")
3996 blade = get_system(module)
3997 try:
3998 policy = list(
3999 blade.get_nfs_export_policies(names=[module.params["name"]]).items
4000 )[0]
4001 except AttributeError:
4002 policy = None
4003 if module.params["rename"]:
4004 try:
4005 new_policy = list(
4006 blade.get_nfs_export_policies(names=[module.params["rename"]]).items
4007 )[0]
4008 except AttributeError:
4009 new_policy = None
4010 if policy and state == "present" and not module.params["rename"]:
4011 if module.params["before_rule"]:
4012 res = blade.get_nfs_export_policies_rules(
4013 policy_names=[module.params["name"]],
4014 names=[
4015 module.params["name"] + "." + str(module.params["before_rule"])
4016 ],
4017 )
4018 if res.status_code != 200:
4019 module.fail_json(
4020 msg="Rule index {0} does not exist.".format(
4021 module.params["before_rule"]
4022 )
4023 )
4024 update_nfs_policy(module, blade)
4025 elif (
4026 state == "present" and module.params["rename"] and policy and not new_policy
4027 ):
4028 rename_nfs_policy(module, blade)
4029 elif state == "present" and not policy and not module.params["rename"]:
4030 create_nfs_policy(module, blade)
4031 elif state == "absent" and policy:
4032 delete_nfs_policy(module, blade)
4033 elif module.params["policy_type"] == "smb_client":
4034 if SMB_POLICY_API_VERSION not in versions:
4035 module.fail_json(
4036 msg=(
4037 "Minimum FlashBlade REST version required: {0}".format(
4038 SMB_POLICY_API_VERSION
4039 )
4040 )
4041 )
4042 if not HAS_PYPURECLIENT:
4043 module.fail_json(msg="py-pure-client sdk is required for this module")
4044 blade = get_system(module)
4045 try:
4046 policy = list(
4047 blade.get_smb_client_policies(names=[module.params["name"]]).items
4048 )[0]
4049 except AttributeError:
4050 policy = None
4051 if module.params["rename"]:
4052 try:
4053 new_policy = list(
4054 blade.get_smb_client_policies(names=[module.params["rename"]]).items
4055 )[0]
4056 except AttributeError:
4057 new_policy = None
4058 if policy and state == "present" and not module.params["rename"]:
4059 if module.params["before_rule"]:
4060 res = blade.get_smb_client_policies_rules(
4061 policy_names=[module.params["name"]],
4062 names=[
4063 module.params["name"] + "." + str(module.params["before_rule"])
4064 ],
4065 )
4066 if res.status_code != 200:
4067 module.fail_json(
4068 msg="Rule index {0} does not exist.".format(
4069 module.params["before_rule"]
4070 )
4071 )
4072 update_smb_client_policy(module, blade)
4073 elif (
4074 state == "present" and module.params["rename"] and policy and not new_policy
4075 ):
4076 rename_smb_client_policy(module, blade)
4077 elif state == "present" and not policy and not module.params["rename"]:
4078 create_smb_client_policy(module, blade)
4079 elif state == "absent" and policy:
4080 delete_smb_client_policy(module, blade)
4081 elif module.params["policy_type"] == "smb_share":
4082 if SMB_POLICY_API_VERSION not in versions:
4083 module.fail_json(
4084 msg=(
4085 "Minimum FlashBlade REST version required: {0}".format(
4086 SMB_POLICY_API_VERSION
4087 )
4088 )
4089 )
4090 if not HAS_PYPURECLIENT:
4091 module.fail_json(msg="py-pure-client sdk is required for this module")
4092 blade = get_system(module)
4093 try:
4094 policy = list(
4095 blade.get_smb_share_policies(names=[module.params["name"]]).items
4096 )[0]
4097 except AttributeError:
4098 policy = None
4099 if module.params["rename"]:
4100 try:
4101 new_policy = list(
4102 blade.get_smb_share_policies(names=[module.params["rename"]]).items
4103 )[0]
4104 except AttributeError:
4105 new_policy = None
4106 if policy and state == "present" and not module.params["rename"]:
4107 if module.params["before_rule"]:
4108 res = blade.get_smb_share_policies_rules(
4109 policy_names=[module.params["name"]],
4110 names=[
4111 module.params["name"] + "." + str(module.params["before_rule"])
4112 ],
4113 )
4114 if res.status_code != 200:
4115 module.fail_json(
4116 msg="Rule index {0} does not exist.".format(
4117 module.params["before_rule"]
4118 )
4119 )
4120 update_smb_share_policy(module, blade)
4121 elif (
4122 state == "present" and module.params["rename"] and policy and not new_policy
4123 ):
4124 rename_smb_share_policy(module, blade)
4125 elif state == "present" and not policy and not module.params["rename"]:
4126 create_smb_share_policy(module, blade)
4127 elif state == "absent" and policy:
4128 delete_smb_share_policy(module, blade)
4129 elif module.params["policy_type"] == "network":
4130 if NET_POLICY_API_VERSION not in versions:
4131 module.fail_json(
4132 msg=(
4133 "Minimum FlashBlade REST version required: {0}".format(
4134 NET_POLICY_API_VERSION
4135 )
4136 )
4137 )
4138 if not HAS_PYPURECLIENT:
4139 module.fail_json(msg="py-pure-client sdk is required for this module")
4140 blade = get_system(module)
4141 try:
4142 policy = list(
4143 blade.get_network_access_policies(names=[module.params["name"]]).items
4144 )[0]
4145 except AttributeError:
4146 policy = None
4147 if module.params["rename"]:
4148 try:
4149 new_policy = list(
4150 blade.get_network_access_policies(
4151 names=[module.params["rename"]]
4152 ).items
4153 )[0]
4154 except AttributeError:
4155 new_policy = None
4156 if policy and state == "present" and not module.params["rename"]:
4157 if module.params["before_rule"]:
4158 res = blade.get_network_access_policies_rules(
4159 policy_names=[module.params["name"]],
4160 names=[
4161 module.params["name"] + "." + str(module.params["before_rule"])
4162 ],
4163 )
4164 if res.status_code != 200:
4165 module.fail_json(
4166 msg="Rule index {0} does not exist.".format(
4167 module.params["before_rule"]
4168 )
4169 )
4170 update_network_access_policy(module, blade)
4171 elif (
4172 state == "present" and module.params["rename"] and policy and not new_policy
4173 ):
4174 rename_network_access_policy(module, blade)
4175 elif state == "present" and not policy and not module.params["rename"]:
4176 create_network_access_policy(module, blade)
4177 elif state == "absent" and policy:
4178 delete_network_access_policy(module, blade)
4179 elif module.params["policy_type"] == "worm":
4180 if WORM_POLICY_API_VERSION not in versions:
4181 module.fail_json(
4182 msg=(
4183 "Minimum FlashBlade REST version required: {0}".format(
4184 WORM_POLICY_API_VERSION
4185 )
4186 )
4187 )
4188 if not HAS_PYPURECLIENT:
4189 module.fail_json(msg="py-pure-client sdk is required for this module")
4190 blade = get_system(module)
4191 try:
4192 policy = list(
4193 blade.get_worm_data_policies(names=[module.params["name"]]).items
4194 )[0]
4195 except AttributeError:
4196 policy = None
4197 if module.params["rename"]:
4198 try:
4199 new_policy = list(
4200 blade.get_worm_data_policies(names=[module.params["rename"]]).items
4201 )[0]
4202 except AttributeError:
4203 new_policy = None
4204 if policy and state == "present" and not module.params["rename"]:
4205 if module.params["before_rule"]:
4206 res = blade.get_worm_data_policies_rules(
4207 policy_names=[module.params["name"]],
4208 names=[
4209 module.params["name"] + "." + str(module.params["before_rule"])
4210 ],
4211 )
4212 if res.status_code != 200:
4213 module.fail_json(
4214 msg="Rule index {0} does not exist.".format(
4215 module.params["before_rule"]
4216 )
4217 )
4218 update_worm_data_policy(module, blade)
4219 elif (
4220 state == "present" and module.params["rename"] and policy and not new_policy
4221 ):
4222 rename_worm_data_policy(blade)
4223 elif state == "present" and not policy and not module.params["rename"]:
4224 create_worm_data_policy(module, blade)
4225 elif state == "absent" and policy:
4226 delete_worm_data_policy(module, blade)
4227 else:
4228 if not HAS_PYPURECLIENT:
4229 module.fail_json(msg="py-pure-client sdk is required for this module")
4230 blade = get_system(module)
4231 try:
4232 policy = list(blade.get_policies(names=[module.params["name"]]).items)[0]
4233 except AttributeError:
4234 policy = None
4235 if not policy and state == "present":
4236 create_snap_policy(module, blade)
4237 elif policy and state == "present":
4238 update_snap_policy(module, blade)
4239 elif policy and state == "absent":
4240 if module.params["filesystem"] or module.params["replica_link"]:
4241 update_snap_policy(module, blade)
4242 else:
4243 delete_snap_policy(module, blade)
4244
4245 module.exit_json(changed=False)
4246
4247
4248 if __name__ == "__main__":
4249 main()