Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_storageaccount.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Matt Davis, <[email protected]>
4 # Chris Houseknecht, <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = '''
13 ---
14 module: azure_rm_storageaccount
15 version_added: "0.1.0"
16 short_description: Manage Azure storage accounts
17 description:
18 - Create, update or delete a storage account.
19 options:
20 auth_mode:
21 description:
22 - The mode in which to run the command. C(login) mode will directly use your login credentials for the authentication.
23 - The legacy C(key) mode will attempt to query for an account key if no authentication parameters for the account are provided.
24 - Can also be set via the environment variable C(AZURE_STORAGE_AUTH_MODE).
25 default: key
26 type: str
27 choices:
28 - key
29 - login
30 version_added: "3.10.0"
31 resource_group:
32 description:
33 - Name of the resource group to use.
34 required: true
35 type: str
36 aliases:
37 - resource_group_name
38 name:
39 description:
40 - Name of the storage account to update or create.
41 type: str
42 required: true
43 state:
44 description:
45 - State of the storage account. Use C(present) to create or update a storage account and use C(absent) to delete an account.
46 - C(failover) is used to failover the storage account to its secondary. This process can take up to a hour.
47 default: present
48 type: str
49 choices:
50 - absent
51 - present
52 - failover
53 location:
54 description:
55 - Valid Azure location. Defaults to location of the resource group.
56 type: str
57 account_type:
58 description:
59 - Type of storage account. Required when creating a storage account.
60 - C(Standard_ZRS) and C(Premium_LRS) accounts cannot be changed to other account types.
61 - Other account types cannot be changed to C(Standard_ZRS) or C(Premium_LRS).
62 type: str
63 choices:
64 - Premium_LRS
65 - Standard_GRS
66 - Standard_LRS
67 - Standard_RAGRS
68 - Standard_ZRS
69 - Premium_ZRS
70 - Standard_RAGZRS
71 - Standard_GZRS
72 aliases:
73 - type
74 custom_domain:
75 description:
76 - User domain assigned to the storage account.
77 - Must be a dictionary with I(name) and I(use_sub_domain) keys where I(name) is the CNAME source.
78 - Only one custom domain is supported per storage account at this time.
79 - To clear the existing custom domain, use an empty string for the custom domain name property.
80 - Can be added to an existing storage account. Will be ignored during storage account creation.
81 type: dict
82 aliases:
83 - custom_dns_domain_suffix
84 kind:
85 description:
86 - The kind of storage.
87 - The C(FileStorage) and (BlockBlobStorage) only used when I(account_type=Premium_LRS) or I(account_type=Premium_ZRS).
88 default: 'Storage'
89 type: str
90 choices:
91 - Storage
92 - StorageV2
93 - BlobStorage
94 - BlockBlobStorage
95 - FileStorage
96 is_hns_enabled:
97 description:
98 - Account HierarchicalNamespace enabled if sets to true.
99 - When I(is_hns_enabled=True), I(kind) cannot be C(Storage).
100 type: bool
101 enable_nfs_v3:
102 description:
103 - NFS 3.0 protocol.
104 type: bool
105 access_tier:
106 description:
107 - The access tier for this storage account. Required when I(kind=BlobStorage).
108 type: str
109 choices:
110 - Hot
111 - Cool
112 force_delete_nonempty:
113 description:
114 - Attempt deletion if resource already exists and cannot be updated.
115 type: bool
116 default: False
117 aliases:
118 - force
119 https_only:
120 description:
121 - Allows https traffic only to storage service when set to C(True).
122 - If omitted, new account creation will default to True, while existing accounts will not be change.
123 type: bool
124 minimum_tls_version:
125 description:
126 - The minimum required version of Transport Layer Security (TLS) for requests to a storage account.
127 - If omitted, new account creation will default to null which is currently interpreted to TLS1_0. Existing accounts will not be modified.
128 type: str
129 choices:
130 - TLS1_0
131 - TLS1_1
132 - TLS1_2
133 version_added: "1.0.0"
134 public_network_access:
135 description:
136 - Allow or disallow public network access to Storage Account.
137 type: str
138 choices:
139 - Enabled
140 - Disabled
141 version_added: "1.12.0"
142 allow_blob_public_access:
143 description:
144 - Allows blob containers in account to be set for anonymous public access.
145 - If set to false, no containers in this account will be able to allow anonymous public access.
146 - If omitted, new account creation will default to null which is currently interpreted to True. Existing accounts will not be modified.
147 type: bool
148 version_added: "1.1.0"
149 network_acls:
150 description:
151 - Manages the Firewall and virtual networks settings of the storage account.
152 type: dict
153 suboptions:
154 default_action:
155 description:
156 - Default firewall traffic rule.
157 - If I(default_action=Allow) no other settings have effect.
158 type: str
159 choices:
160 - Allow
161 - Deny
162 default: Allow
163 bypass:
164 description:
165 - When I(default_action=Deny) this controls which Azure components can still reach the Storage Account.
166 - The list is comma separated.
167 - It can be any combination of the example C(AzureServices), C(Logging), C(Metrics).
168 - If no Azure components are allowed, explicitly set I(bypass="").
169 default: AzureServices
170 type: str
171 virtual_network_rules:
172 description:
173 - A list of subnets and their actions.
174 type: list
175 elements: dict
176 suboptions:
177 id:
178 description:
179 - The complete path to the subnet.
180 type: str
181 required: true
182 action:
183 description:
184 - The only logical I(action=Allow) because this setting is only accessible when I(default_action=Deny).
185 default: 'Allow'
186 type: str
187 choices:
188 - Allow
189 ip_rules:
190 description:
191 - A list of IP addresses or ranges in CIDR format.
192 type: list
193 elements: dict
194 suboptions:
195 value:
196 description:
197 - The IP address or range.
198 type: str
199 required: true
200 action:
201 description:
202 - The only logical I(action=Allow) because this setting is only accessible when I(default_action=Deny).
203 default: 'Allow'
204 type: str
205 choices:
206 - Allow
207 resource_access_rules:
208 description:
209 - List of resource instance rules that allow specific Azure resources to access storage account when public network access is restricted.
210 - Supported resource types
211 U(https://learn.microsoft.com/en-us/azure/storage/common/storage-network-security-trusted-azure-services?source=recommendations)
212 - Resource instance rules only apply when I(default_action=Deny) and when I(public_network_access=Enabled).
213 type: list
214 elements: dict
215 suboptions:
216 resource_id:
217 description:
218 - The full ARM resource ID of the Azure resource instance.
219 type: str
220 required: true
221 tenant_id:
222 description:
223 - The Azure Active Directory tenant ID of the resource instance.
224 type: str
225 required: true
226 blob_cors:
227 description:
228 - Specifies CORS rules for the Blob service.
229 - You can include up to five CorsRule elements in the request.
230 - If no blob_cors elements are included in the argument list, nothing about CORS will be changed.
231 - If you want to delete all CORS rules and disable CORS for the Blob service, explicitly set I(blob_cors=[]).
232 type: list
233 elements: dict
234 suboptions:
235 allowed_origins:
236 description:
237 - A list of origin domains that will be allowed via CORS, or "*" to allow all domains.
238 type: list
239 elements: str
240 required: true
241 allowed_methods:
242 description:
243 - A list of HTTP methods that are allowed to be executed by the origin.
244 type: list
245 elements: str
246 required: true
247 max_age_in_seconds:
248 description:
249 - The number of seconds that the client/browser should cache a preflight response.
250 type: int
251 required: true
252 exposed_headers:
253 description:
254 - A list of response headers to expose to CORS clients.
255 type: list
256 elements: str
257 required: true
258 allowed_headers:
259 description:
260 - A list of headers allowed to be part of the cross-origin request.
261 type: list
262 elements: str
263 required: true
264 static_website:
265 description:
266 - Manage static website configuration for the storage account.
267 type: dict
268 version_added: "1.13.0"
269 suboptions:
270 enabled:
271 description:
272 - Indicates whether this account is hosting a static website.
273 type: bool
274 default: false
275 index_document:
276 description:
277 - The default name of the index page under each directory.
278 type: str
279 error_document404_path:
280 description:
281 - The absolute path of the custom 404 page.
282 type: str
283 large_file_shares_state:
284 description:
285 - Allow large file shares if sets to Enabled.
286 type: str
287 choices:
288 - Enabled
289 - Disabled
290 allow_cross_tenant_replication:
291 description:
292 - Allow or disallow cross AAD tenant object replication.
293 type: bool
294 allow_shared_key_access:
295 description:
296 - Indicates whether the storage account permits requests to be authorized with the account access key via Shared Key.
297 - If false, then all requests, including shared access signatures, must be authorized with Azure Active Directory (Azure AD).
298 - The default value is null, which is equivalent to true.
299 type: bool
300 default_to_o_auth_authentication:
301 description:
302 - A boolean flag which indicates whether the default authentication is OAuth or not.
303 - The default interpretation is false for this property.
304 type: bool
305 encryption:
306 description:
307 - The encryption settings on the storage account.
308 type: dict
309 suboptions:
310 services:
311 description:
312 - List of services which support encryption.
313 type: dict
314 suboptions:
315 table:
316 description:
317 - The encryption function of the table storage service.
318 type: dict
319 suboptions:
320 enabled:
321 description:
322 - Whether to encrypt the table type.
323 type: bool
324 queue:
325 description:
326 - The encryption function of the queue storage service.
327 type: dict
328 suboptions:
329 enabled:
330 description:
331 - Whether to encrypt the queue type.
332 type: bool
333 file:
334 description:
335 - The encryption function of the file storage service.
336 type: dict
337 suboptions:
338 enabled:
339 description:
340 - Whether to encrypt the file type.
341 type: bool
342 blob:
343 description:
344 - The encryption function of the blob storage service.
345 type: dict
346 suboptions:
347 enabled:
348 description:
349 - Whether to encrypt the blob type.
350 type: bool
351 key_source:
352 description:
353 - The encryption keySource (provider).
354 type: str
355 default: Microsoft.Storage
356 choices:
357 - Microsoft.Storage
358 - Microsoft.Keyvault
359 key_vault_properties:
360 description:
361 - list of Microsoft Keyvault properties needed in order to create Storage account with encryption enabled with Microsoft KeyVault for CMK.
362 type: dict
363 suboptions:
364 key_vault_uri:
365 description:
366 - The Uri of KeyVault.
367 type: str
368 required: true
369 key_name:
370 description:
371 - The name of KeyVault key.
372 type: str
373 required: true
374 key_version:
375 description:
376 - The version of KeyVault key.
377 type: str
378 encryption_identity:
379 description:
380 - The identity to be used with service-side encryption at rest.
381 type: dict
382 suboptions:
383 encryption_user_assigned_identity:
384 description:
385 - Resource identifier of the UserAssigned identity to be associated with server-side encryption on the storage account.
386 type: str
387 require_infrastructure_encryption:
388 description:
389 - A boolean indicating whether or not the service applies a secondary layer of encryption with platform managed keys for data at rest.
390 type: bool
391 immutable_storage_with_versioning:
392 description:
393 - The property is immutable and can only be set to true at the account creation time.
394 - When set to true, it enables object level immutability for all the containers in the account by default.
395 type: dict
396 suboptions:
397 enabled:
398 description:
399 - A boolean flag which enables account-level immutability.
400 - All the containers under such an account have object-level immutability enabled by default.
401 type: bool
402 immutability_policy:
403 description:
404 - Specifies the default account-level immutability policy which is inherited and
405 applied to objects that do not possess an explicit immutability policy at the object level.
406 - The object-level immutability policy has higher precedence than the container-level immutability policy,
407 which has a higher precedence than the account-level immutability policy.
408 type: dict
409 suboptions:
410 allow_protected_append_writes:
411 description:
412 - This property can only be changed for C(disabled) and C(unlocked) time-based retention policies.
413 - When C(enabled), new blocks can be written to an append blob while maintaining immutability protection and compliance.
414 - Only new blocks can be added and any existing blocks cannot be modified or deleted.
415 type: bool
416 state:
417 description:
418 - The ImmutabilityPolicy state defines the mode of the policy.
419 type: str
420 choices:
421 - Unlocked
422 - Locked
423 - Disabled
424 immutability_period_since_creation_in_days:
425 description:
426 - The immutability period for the blobs in the container since the policy creation, in days.
427 type: int
428
429 extends_documentation_fragment:
430 - azure.azcollection.azure
431 - azure.azcollection.azure_tags
432 - azure.azcollection.azure_identity_single
433
434 author:
435 - Chris Houseknecht (@chouseknecht)
436 - Matt Davis (@nitzmahone)
437 '''
438
439 EXAMPLES = '''
440 - name: remove account, if it exists
441 azure_rm_storageaccount:
442 resource_group: myResourceGroup
443 name: clh0002
444 state: absent
445
446 - name: create an account
447 azure_rm_storageaccount:
448 resource_group: myResourceGroup
449 name: clh0002
450 type: Standard_RAGRS
451 tags:
452 testing: testing
453 delete: on-exit
454
455 - name: Create an account with kind of FileStorage
456 azure_rm_storageaccount:
457 resource_group: myResourceGroup
458 name: c1h0002
459 type: Premium_LRS
460 kind: FileStorage
461 tags:
462 testing: testing
463
464 - name: Create storage account with I(enable_nfs_v3=false)
465 azure_rm_storageaccount:
466 resource_group: myResourceGroup
467 name: c1h0002
468 account_type: Premium_LRS
469 kind: FileStorage
470 enable_nfs_v3: false
471 static_website:
472 enabled: true
473
474 - name: configure firewall and virtual networks
475 azure_rm_storageaccount:
476 resource_group: myResourceGroup
477 name: clh0002
478 type: Standard_RAGRS
479 network_acls:
480 bypass: AzureServices,Metrics
481 default_action: Deny
482 virtual_network_rules:
483 - id: /subscriptions/mySubscriptionId/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet
484 action: Allow
485 ip_rules:
486 - value: 1.2.3.4
487 action: Allow
488 - value: 123.234.123.0/24
489 action: Allow
490
491 - name: create an account with blob CORS
492 azure_rm_storageaccount:
493 resource_group: myResourceGroup
494 name: clh002
495 type: Standard_RAGRS
496 blob_cors:
497 - allowed_origins:
498 - http://www.example.com/
499 allowed_methods:
500 - GET
501 - POST
502 allowed_headers:
503 - x-ms-meta-data*
504 - x-ms-meta-target*
505 - x-ms-meta-abc
506 exposed_headers:
507 - x-ms-meta-*
508 max_age_in_seconds: 200
509
510 - name: Create new storage account with (key_source=Microsoft.Keyvault)
511 azure.azcollection.azure_rm_storageaccount:
512 resource_group: "{{ resource_group }}"
513 name: "{{ storage_account_name }}"
514 account_type: Standard_RAGRS
515 kind: StorageV2
516 identity:
517 type: UserAssigned
518 user_assigned_identity: "{{ managed_identity_ids[0] }}"
519 encryption:
520 services:
521 blob:
522 enabled: true
523 file:
524 enabled: true
525 require_infrastructure_encryption: false
526 key_source: Microsoft.Keyvault
527 key_vault_properties:
528 key_vault_uri: "https://vaultestfred001.vault.azure.net/"
529 key_name: testkey
530 key_version: 0bd2556671c64fc998095603878beb12
531 encryption_identity:
532 encryption_user_assigned_identity: "{{ managed_identity_ids[0] }}"
533
534 - name: Configure resource instance rules for Backup Vault and Synapse
535 azure_rm_storageaccount:
536 resource_group: myResourceGroup
537 name: mystorageacct
538 account_type: Standard_LRS
539 kind: StorageV2
540 public_network_access: Enabled
541 network_acls:
542 default_action: Deny
543 bypass: AzureServices
544 resource_access_rules:
545 - resource_id: "/subscriptions/mySubscriptionId/resourceGroups/myResourceGroup/providers/Microsoft.DataProtection/BackupVaults/myBackupVault"
546 tenant_id: "myTenantId"
547 - resource_id: "/subscriptions/mySubscriptionId/resourceGroups/myResourceGroup/providers/Microsoft.Synapse/workspaces/mySynapseWorkspace"
548 tenant_id: "myTenantId"
549
550 - name: Remove all resource instance rules
551 azure_rm_storageaccount:
552 resource_group: myResourceGroup
553 name: mystorageacct
554 network_acls:
555 default_action: Deny
556 bypass: AzureServices
557 resource_access_rules: []
558 '''
559
560 RETURN = '''
561 state:
562 description:
563 - Current state of the storage account.
564 returned: always
565 type: complex
566 contains:
567 account_type:
568 description:
569 - Type of storage account.
570 returned: always
571 type: str
572 sample: Standard_RAGRS
573 allow_cross_tenant_replication:
574 description:
575 - Allow or disallow cross AAD tenant object replication.
576 type: bool
577 returned: always
578 sample: true
579 allow_shared_key_access:
580 description:
581 - Indicates whether the storage account permits requests to be authorized with the account access key via Shared Key.
582 type: bool
583 returned: always
584 sample: true
585 default_to_o_auth_authentication:
586 description:
587 - A boolean flag which indicates whether the default authentication is OAuth or not.
588 - The default interpretation is false for this property.
589 type: bool
590 returned: always
591 sample: true
592 custom_domain:
593 description:
594 - User domain assigned to the storage account.
595 returned: always
596 type: complex
597 contains:
598 name:
599 description:
600 - CNAME source.
601 returned: always
602 type: str
603 sample: testaccount
604 use_sub_domain:
605 description:
606 - Whether to use sub domain.
607 returned: always
608 type: bool
609 sample: true
610 encryption:
611 description:
612 - The encryption settings on the storage account.
613 type: complex
614 returned: always
615 contains:
616 key_source:
617 description:
618 - The encryption keySource (provider).
619 type: str
620 returned: always
621 sample: Microsoft.Storage
622 require_infrastructure_encryption:
623 description:
624 - A boolean indicating whether or not the service applies a secondary layer of encryption with platform managed keys for data at rest.
625 type: bool
626 returned: always
627 sample: false
628 services:
629 description:
630 - List of services which support encryption.
631 type: dict
632 returned: always
633 contains:
634 file:
635 description:
636 - The encryption function of the file storage service.
637 type: dict
638 returned: always
639 sample: {'enabled': true}
640 table:
641 description:
642 - The encryption function of the table storage service.
643 type: dict
644 returned: always
645 sample: {'enabled': true}
646 queue:
647 description:
648 - The encryption function of the queue storage service.
649 type: dict
650 returned: always
651 sample: {'enabled': true}
652 blob:
653 description:
654 - The encryption function of the blob storage service.
655 type: dict
656 returned: always
657 sample: {'enabled': true}
658 encryption_identity:
659 description:
660 - The identity to be used with service-side encryption at rest.
661 type: dict
662 returned: always
663 sample: {"encryption_user_assigned_identity": \
664 "/subscriptions/xxxx/resourcegroups/testRG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity-11"}
665 key_vault_properties:
666 description:
667 - Dict of Microsoft Keyvault properties.
668 - Create the Storage account with encryption enabled with Microsoft KeyVault for CMK.
669 type: dict
670 returned: always
671 sample: {"key_name": "testkey",
672 "key_vault_uri": "https://vxxxxxxx01.vault.azure.net/",
673 "key_version": "0bd2556671c64fc998xxxxeb12"}
674 id:
675 description:
676 - Resource ID.
677 returned: always
678 type: str
679 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/clh0003"
680 is_hns_enabled:
681 description:
682 - Account HierarchicalNamespace enabled if sets to true.
683 type: bool
684 returned: always
685 sample: true
686 immutable_storage_with_versioning:
687 description:
688 - The property is immutable and can only be set to true at the account creation time.
689 - When set to true, it enables object level immutability for all the containers in the account by default.
690 type: complex
691 returned: when-used
692 contains:
693 enabled:
694 description:
695 - A boolean flag which enables account-level immutability.
696 - All the containers under such an account have object-level immutability enabled by default.
697 type: bool
698 returned: when-used
699 sample: true
700 immutability_policy:
701 description:
702 - Specifies the default account-level immutability policy which is inherited and
703 applied to objects that do not possess an explicit immutability policy at the object level.
704 - The object-level immutability policy has higher precedence than the container-level immutability policy,
705 which has a higher precedence than the account-level immutability policy.
706 type: dict
707 returned: when-used
708 contains:
709 allow_protected_append_writes:
710 description:
711 - This property can only be changed for disabled and unlocked time-based retention policies.
712 - When enabled, new blocks can be written to an append blob while maintaining immutability protection and compliance.
713 - Only new blocks can be added and any existing blocks cannot be modified or deleted.
714 type: bool
715 returned: when-used
716 sample: true
717 state:
718 description:
719 - The ImmutabilityPolicy state defines the mode of the policy.
720 type: str
721 returned: when-used
722 sample: Unlocked
723 immutability_period_since_creation_in_days:
724 description:
725 - The immutability period for the blobs in the container since the policy creation, in days.
726 type: int
727 returned: when-used
728 sample: true
729 enable_nfs_v3:
730 description:
731 - NFS 3.0 protocol.
732 type: bool
733 returned: always
734 sample: false
735 location:
736 description:
737 - Valid Azure location. Defaults to location of the resource group.
738 returned: always
739 type: str
740 sample: eastus2
741 name:
742 description:
743 - Name of the storage account to update or create.
744 returned: always
745 type: str
746 sample: clh0003
747 network_acls:
748 description:
749 - A set of firewall and virtual network rules
750 returned: always
751 type: dict
752 sample: {
753 "bypass": "AzureServices",
754 "default_action": "Deny",
755 "virtual_network_rules": [
756 {
757 "action": "Allow",
758 "id": "/subscriptions/mySubscriptionId/resourceGroups/myResourceGroup/ \
759 providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"
760 }
761 ],
762 "ip_rules": [
763 {
764 "action": "Allow",
765 "value": "1.2.3.4"
766 },
767 {
768 "action": "Allow",
769 "value": "123.234.123.0/24"
770 }
771 ],
772 "resource_access_rules": [
773 {
774 "resource_id": "/subscriptions/mySubscriptionId/resourceGroups/myResourceGroup/ \
775 providers/Microsoft.DataProtection/BackupVaults/myBackupVault",
776 "tenant_id": "myTenantId"
777 }
778 ]
779 }
780 primary_endpoints:
781 description:
782 - The URLs to retrieve the public I(blob), I(queue), or I(table) object from the primary location.
783 returned: always
784 type: dict
785 sample: {
786 "blob": "https://clh0003.blob.core.windows.net/",
787 "queue": "https://clh0003.queue.core.windows.net/",
788 "table": "https://clh0003.table.core.windows.net/"
789 }
790 primary_location:
791 description:
792 - The location of the primary data center for the storage account.
793 returned: always
794 type: str
795 sample: eastus2
796 provisioning_state:
797 description:
798 - The status of the storage account.
799 - Possible values include C(Creating), C(ResolvingDNS), C(Succeeded).
800 returned: always
801 type: str
802 sample: Succeeded
803 failover_in_progress:
804 description:
805 - Status indicating the storage account is currently failing over to its secondary location.
806 returned: always
807 type: bool
808 sample: False
809 resource_group:
810 description:
811 - The resource group's name.
812 returned: always
813 type: str
814 sample: Testing
815 secondary_endpoints:
816 description:
817 - The URLs to retrieve the public I(blob), I(queue), or I(table) object from the secondary location.
818 returned: always
819 type: dict
820 sample: {
821 "blob": "https://clh0003-secondary.blob.core.windows.net/",
822 "queue": "https://clh0003-secondary.queue.core.windows.net/",
823 "table": "https://clh0003-secondary.table.core.windows.net/"
824 }
825 secondary_location:
826 description:
827 - The location of the geo-replicated secondary for the storage account.
828 returned: always
829 type: str
830 sample: centralus
831 status_of_primary:
832 description:
833 - The status of the primary location of the storage account; either C(available) or C(unavailable).
834 returned: always
835 type: str
836 sample: available
837 status_of_secondary:
838 description:
839 - The status of the secondary location of the storage account; either C(available) or C(unavailable).
840 returned: always
841 type: str
842 sample: available
843 https_only:
844 description:
845 - Allows https traffic only to storage service when set to C(true).
846 returned: always
847 type: bool
848 sample: false
849 minimum_tls_version:
850 description:
851 - The minimum TLS version permitted on requests to storage.
852 returned: always
853 type: str
854 sample: TLS1_2
855 public_network_access:
856 description:
857 - Public network access to Storage Account allowed or disallowed.
858 returned: always
859 type: str
860 sample: Enabled
861 allow_blob_public_access:
862 description:
863 - Public access to all blobs or containers in the storage account allowed or disallowed.
864 returned: always
865 type: bool
866 sample: true
867 tags:
868 description:
869 - Resource tags.
870 returned: always
871 type: dict
872 sample: { 'tags1': 'value1' }
873 type:
874 description:
875 - The storage account type.
876 returned: always
877 type: str
878 sample: "Microsoft.Storage/storageAccounts"
879 large_file_shares_state:
880 description:
881 - Allow large file shares if sets to Enabled.
882 type: str
883 returned: always
884 sample: Enabled
885 static_website:
886 description:
887 - Static website configuration for the storage account.
888 returned: always
889 version_added: "1.13.0"
890 type: complex
891 contains:
892 enabled:
893 description:
894 - Whether this account is hosting a static website.
895 returned: always
896 type: bool
897 sample: true
898 index_document:
899 description:
900 - The default name of the index page under each directory.
901 returned: always
902 type: str
903 sample: index.html
904 error_document404_path:
905 description:
906 - The absolute path of the custom 404 page.
907 returned: always
908 type: str
909 sample: error.html
910 '''
911
912
913 import copy
914 import time
915 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AZURE_SUCCESS_STATE
916 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
917 from ansible.module_utils._text import to_native
918 from ansible.module_utils.basic import env_fallback
919
920 try:
921 from azure.mgmt.storage.models import (Identity, UserAssignedIdentity)
922 except ImportError:
923 # This is handled in azure_rm_common
924 pass
925
926 cors_rule_spec = dict(
927 allowed_origins=dict(type='list', elements='str', required=True),
928 allowed_methods=dict(type='list', elements='str', required=True),
929 max_age_in_seconds=dict(type='int', required=True),
930 exposed_headers=dict(type='list', elements='str', required=True),
931 allowed_headers=dict(type='list', elements='str', required=True),
932 )
933
934 static_website_spec = dict(
935 enabled=dict(type='bool', default=False),
936 index_document=dict(type='str'),
937 error_document404_path=dict(type='str'),
938 )
939
940
941 file_spec = dict(
942 enabled=dict(type='bool')
943 )
944
945
946 queue_spec = dict(
947 enabled=dict(type='bool')
948 )
949
950
951 table_spec = dict(
952 enabled=dict(type='bool')
953 )
954
955
956 blob_spec = dict(
957 enabled=dict(type='bool')
958 )
959
960
961 def compare_cors(cors1, cors2):
962 if len(cors1) != len(cors2):
963 return False
964 copy2 = copy.copy(cors2)
965 for rule1 in cors1:
966 matched = False
967 for rule2 in copy2:
968 if (rule1['max_age_in_seconds'] == rule2['max_age_in_seconds']
969 and set(rule1['allowed_methods']) == set(rule2['allowed_methods'])
970 and set(rule1['allowed_origins']) == set(rule2['allowed_origins'])
971 and set(rule1['allowed_headers']) == set(rule2['allowed_headers'])
972 and set(rule1['exposed_headers']) == set(rule2['exposed_headers'])):
973 matched = True
974 copy2.remove(rule2)
975 if not matched:
976 return False
977 return True
978
979
980 class AzureRMStorageAccount(AzureRMModuleBaseExt):
981
982 def __init__(self):
983
984 self.module_arg_spec = dict(
985 auth_mode=dict(
986 type='str',
987 choices=['key', 'login'],
988 fallback=(env_fallback, ['AZURE_STORAGE_AUTH_MODE']),
989 default="key"
990 ),
991 account_type=dict(type='str',
992 choices=['Premium_LRS', 'Standard_GRS', 'Standard_LRS', 'Standard_RAGRS', 'Standard_ZRS', 'Premium_ZRS',
993 'Standard_RAGZRS', 'Standard_GZRS'],
994 aliases=['type']),
995 custom_domain=dict(type='dict', aliases=['custom_dns_domain_suffix']),
996 location=dict(type='str'),
997 name=dict(type='str', required=True),
998 resource_group=dict(required=True, type='str', aliases=['resource_group_name']),
999 state=dict(default='present', choices=['present', 'absent', 'failover']),
1000 force_delete_nonempty=dict(type='bool', default=False, aliases=['force']),
1001 tags=dict(type='dict'),
1002 kind=dict(type='str', default='Storage', choices=['Storage', 'StorageV2', 'BlobStorage', 'FileStorage', 'BlockBlobStorage']),
1003 access_tier=dict(type='str', choices=['Hot', 'Cool']),
1004 https_only=dict(type='bool'),
1005 minimum_tls_version=dict(type='str', choices=['TLS1_0', 'TLS1_1', 'TLS1_2']),
1006 public_network_access=dict(type='str', choices=['Enabled', 'Disabled']),
1007 allow_blob_public_access=dict(type='bool'),
1008 allow_shared_key_access=dict(type='bool'),
1009 allow_cross_tenant_replication=dict(type='bool'),
1010 default_to_o_auth_authentication=dict(type='bool'),
1011 network_acls=dict(
1012 type='dict',
1013 options=dict(
1014 bypass=dict(type='str', default='AzureServices', no_log=False),
1015 default_action=dict(type='str', choices=['Allow', 'Deny'], default='Allow'),
1016 virtual_network_rules=dict(
1017 type='list',
1018 elements='dict',
1019 options=dict(
1020 id=dict(type='str', required=True),
1021 action=dict(type='str', choices=['Allow'], default='Allow'),
1022 ),
1023 ),
1024 ip_rules=dict(
1025 type='list',
1026 elements='dict',
1027 options=dict(
1028 value=dict(type='str', required=True),
1029 action=dict(type='str', choices=['Allow'], default='Allow'),
1030 ),
1031 ),
1032 resource_access_rules=dict(
1033 type='list',
1034 elements='dict',
1035 options=dict(
1036 resource_id=dict(type='str', required=True),
1037 tenant_id=dict(type='str', required=True),
1038 ),
1039 ),
1040 ),
1041 ),
1042 blob_cors=dict(type='list', options=cors_rule_spec, elements='dict'),
1043 static_website=dict(type='dict', options=static_website_spec),
1044 is_hns_enabled=dict(type='bool'),
1045 large_file_shares_state=dict(type='str', choices=['Enabled', 'Disabled']),
1046 enable_nfs_v3=dict(type='bool'),
1047 encryption=dict(
1048 type='dict',
1049 options=dict(
1050 services=dict(
1051 type='dict',
1052 options=dict(
1053 blob=dict(
1054 type='dict',
1055 options=blob_spec
1056 ),
1057 table=dict(
1058 type='dict',
1059 options=table_spec
1060 ),
1061 queue=dict(
1062 type='dict',
1063 options=queue_spec
1064 ),
1065 file=dict(
1066 type='dict',
1067 options=file_spec
1068 )
1069 )
1070 ),
1071 require_infrastructure_encryption=dict(type='bool'),
1072 key_source=dict(type='str', choices=["Microsoft.Storage", "Microsoft.Keyvault"], default='Microsoft.Storage'),
1073 key_vault_properties=dict(
1074 type='dict',
1075 options=dict(
1076 key_vault_uri=dict(type='str', required=True, no_log=True),
1077 key_name=dict(type='str', required=True),
1078 key_version=dict(type='str', no_log=True)
1079 ), no_log=True
1080 ),
1081 encryption_identity=dict(
1082 type='dict',
1083 options=dict(
1084 encryption_user_assigned_identity=dict(type='str', required=False) # This will hold the resource ID of the user-assigned identity
1085 )
1086 )
1087 )
1088 ),
1089 identity=dict(
1090 type="dict",
1091 options=self.managed_identity_single_spec
1092 ),
1093 immutable_storage_with_versioning=dict(
1094 type='dict',
1095 options=dict(
1096 enabled=dict(type='bool'),
1097 immutability_policy=dict(
1098 type='dict',
1099 options=dict(
1100 immutability_period_since_creation_in_days=dict(type='int'),
1101 state=dict(type='str', choices=['Unlocked', 'Locked', 'Disabled']),
1102 allow_protected_append_writes=dict(type='bool')
1103 )
1104 )
1105 )
1106 )
1107 )
1108
1109 self.results = dict(
1110 changed=False,
1111 state=dict()
1112 )
1113
1114 self.account_dict = None
1115 self.resource_group = None
1116 self.name = None
1117 self.state = None
1118 self.location = None
1119 self.account_type = None
1120 self.custom_domain = None
1121 self.tags = None
1122 self.force_delete_nonempty = None
1123 self.kind = None
1124 self.access_tier = None
1125 self.https_only = None
1126 self.minimum_tls_version = None
1127 self.public_network_access = None
1128 self.allow_blob_public_access = None
1129 self.network_acls = None
1130 self.blob_cors = None
1131 self.static_website = None
1132 self.encryption = None
1133 self.is_hns_enabled = None
1134 self.large_file_shares_state = None
1135 self.enable_nfs_v3 = None
1136 self.allow_shared_key_access = None
1137 self.allow_cross_tenant_replication = None
1138 self.default_to_o_auth_authentication = None
1139 self._managed_identity = None
1140 self.identity = None
1141 self.update_identity = False
1142 self.immutable_storage_with_versioning = None
1143
1144 super(AzureRMStorageAccount, self).__init__(self.module_arg_spec,
1145 supports_check_mode=True)
1146
1147 @property
1148 def managed_identity(self):
1149 if not self._managed_identity:
1150 self._managed_identity = {
1151 "identity": Identity,
1152 "user_assigned": UserAssignedIdentity,
1153 }
1154 return self._managed_identity
1155
1156 def exec_module(self, **kwargs):
1157
1158 for key in list(self.module_arg_spec.keys()) + ['tags']:
1159 setattr(self, key, kwargs[key])
1160
1161 resource_group = self.get_resource_group(self.resource_group)
1162 if not self.location:
1163 # Set default location
1164 self.location = resource_group.location
1165
1166 if len(self.name) < 3 or len(self.name) > 24:
1167 self.fail("Parameter error: name length must be between 3 and 24 characters.")
1168
1169 if self.custom_domain:
1170 if self.custom_domain.get('name', None) is None:
1171 self.fail("Parameter error: expecting custom_domain to have a name attribute of type string.")
1172 if self.custom_domain.get('use_sub_domain', None) is None:
1173 self.fail("Parameter error: expecting custom_domain to have a use_sub_domain "
1174 "attribute of type boolean.")
1175
1176 if self.kind in ['FileStorage', 'BlockBlobStorage', ] and self.account_type not in ['Premium_LRS', 'Premium_ZRS']:
1177 self.fail("Parameter error: Storage account with {0} kind require account type is Premium_LRS or Premium_ZRS".format(self.kind))
1178 self.account_dict = self.get_account()
1179
1180 curr_identity = self.account_dict["identity"] if self.account_dict else None
1181
1182 if self.identity:
1183 self.update_identity, identity_result = self.update_single_managed_identity(curr_identity=curr_identity,
1184 new_identity=self.identity,
1185 patch_support=True)
1186 self.identity = identity_result.as_dict()
1187
1188 if self.state == 'present' and self.account_dict and \
1189 self.account_dict['provisioning_state'] != AZURE_SUCCESS_STATE:
1190 self.fail("Error: storage account {0} has not completed provisioning. State is {1}. Expecting state "
1191 "to be {2}.".format(self.name, self.account_dict['provisioning_state'], AZURE_SUCCESS_STATE))
1192
1193 if self.account_dict is not None:
1194 self.results['state'] = self.account_dict
1195 else:
1196 self.results['state'] = dict()
1197
1198 if self.state == 'present':
1199 if not self.account_dict:
1200 self.results['state'] = self.create_account()
1201 else:
1202 self.results['state'] = self.update_account()
1203 elif self.state == 'absent' and self.account_dict:
1204 self.delete_account()
1205 self.results['state'] = dict(Status='Deleted')
1206 elif self.state == 'failover' and self.account_dict:
1207 self.failover_account()
1208 self.results['state'] = self.get_account()
1209
1210 return self.results
1211
1212 def check_name_availability(self):
1213 self.log('Checking name availability for {0}'.format(self.name))
1214 try:
1215 account_name = self.storage_models.StorageAccountCheckNameAvailabilityParameters(name=self.name)
1216 self.storage_client.storage_accounts.check_name_availability(account_name)
1217 except Exception as e:
1218 self.log('Error attempting to validate name.')
1219 self.fail("Error checking name availability: {0}".format(str(e)))
1220
1221 def get_account(self):
1222 self.log('Get properties for account {0}'.format(self.name))
1223 account_obj = None
1224 blob_mgmt_props = None
1225 blob_client_props = None
1226 account_dict = None
1227
1228 try:
1229 account_obj = self.storage_client.storage_accounts.get_properties(self.resource_group, self.name)
1230 blob_mgmt_props = self.storage_client.blob_services.get_service_properties(self.resource_group, self.name)
1231 if self.kind != "FileStorage":
1232 blob_client_props = self.get_blob_service_client(self.resource_group, self.name, self.auth_mode).get_service_properties()
1233 except Exception:
1234 pass
1235
1236 if account_obj:
1237 account_dict = self.account_obj_to_dict(account_obj, blob_mgmt_props, blob_client_props)
1238
1239 return account_dict
1240
1241 def account_obj_to_dict(self, account_obj, blob_mgmt_props=None, blob_client_props=None):
1242 account_dict = dict(
1243 id=account_obj.id,
1244 name=account_obj.name,
1245 location=account_obj.location,
1246 failover_in_progress=(account_obj.failover_in_progress
1247 if account_obj.failover_in_progress is not None else False),
1248 resource_group=self.resource_group,
1249 type=account_obj.type,
1250 access_tier=account_obj.access_tier,
1251 sku_tier=account_obj.sku.tier,
1252 sku_name=account_obj.sku.name,
1253 provisioning_state=account_obj.provisioning_state,
1254 secondary_location=account_obj.secondary_location,
1255 status_of_primary=account_obj.status_of_primary,
1256 status_of_secondary=account_obj.status_of_secondary,
1257 primary_location=account_obj.primary_location,
1258 https_only=account_obj.enable_https_traffic_only,
1259 minimum_tls_version=account_obj.minimum_tls_version,
1260 public_network_access=account_obj.public_network_access,
1261 allow_blob_public_access=account_obj.allow_blob_public_access,
1262 default_to_o_auth_authentication=account_obj.default_to_o_auth_authentication,
1263 allow_cross_tenant_replication=account_obj.allow_cross_tenant_replication,
1264 allow_shared_key_access=account_obj.allow_shared_key_access,
1265 is_hns_enabled=account_obj.is_hns_enabled if account_obj.is_hns_enabled else False,
1266 enable_nfs_v3=account_obj.enable_nfs_v3 if hasattr(account_obj, 'enable_nfs_v3') else None,
1267 large_file_shares_state=account_obj.large_file_shares_state,
1268 static_website=dict(
1269 enabled=False,
1270 index_document=None,
1271 error_document404_path=None,
1272 ),
1273 immutable_storage_with_versioning=account_obj.immutable_storage_with_versioning.as_dict() if account_obj.immutable_storage_with_versioning else None
1274 )
1275 account_dict['custom_domain'] = None
1276 if account_obj.custom_domain:
1277 account_dict['custom_domain'] = dict(
1278 name=account_obj.custom_domain.name,
1279 use_sub_domain=account_obj.custom_domain.use_sub_domain
1280 )
1281
1282 account_dict['primary_endpoints'] = None
1283 if account_obj.primary_endpoints:
1284 account_dict['primary_endpoints'] = dict(
1285 blob=account_obj.primary_endpoints.blob,
1286 queue=account_obj.primary_endpoints.queue,
1287 table=account_obj.primary_endpoints.table
1288 )
1289 account_dict['secondary_endpoints'] = None
1290 if account_obj.secondary_endpoints:
1291 account_dict['secondary_endpoints'] = dict(
1292 blob=account_obj.secondary_endpoints.blob,
1293 queue=account_obj.secondary_endpoints.queue,
1294 table=account_obj.secondary_endpoints.table
1295 )
1296 account_dict['tags'] = None
1297 if account_obj.tags:
1298 account_dict['tags'] = account_obj.tags
1299 if blob_mgmt_props and blob_mgmt_props.cors and blob_mgmt_props.cors.cors_rules:
1300 account_dict['blob_cors'] = [dict(
1301 allowed_origins=[to_native(y) for y in x.allowed_origins],
1302 allowed_methods=[to_native(y) for y in x.allowed_methods],
1303 max_age_in_seconds=x.max_age_in_seconds,
1304 exposed_headers=[to_native(y) for y in x.exposed_headers],
1305 allowed_headers=[to_native(y) for y in x.allowed_headers]
1306 ) for x in blob_mgmt_props.cors.cors_rules]
1307
1308 if blob_client_props and blob_client_props['static_website']:
1309 static_website = blob_client_props['static_website']
1310 account_dict['static_website'] = dict(
1311 enabled=static_website.enabled,
1312 index_document=static_website.index_document,
1313 error_document404_path=static_website.error_document404_path,
1314 )
1315
1316 account_dict['network_acls'] = None
1317 if account_obj.network_rule_set:
1318 account_dict['network_acls'] = dict(
1319 bypass=account_obj.network_rule_set.bypass,
1320 default_action=account_obj.network_rule_set.default_action
1321 )
1322 account_dict['network_acls']['virtual_network_rules'] = []
1323 if account_obj.network_rule_set.virtual_network_rules:
1324 for rule in account_obj.network_rule_set.virtual_network_rules:
1325 account_dict['network_acls']['virtual_network_rules'].append(dict(id=rule.virtual_network_resource_id, action=rule.action))
1326
1327 account_dict['network_acls']['ip_rules'] = []
1328 if account_obj.network_rule_set.ip_rules:
1329 for rule in account_obj.network_rule_set.ip_rules:
1330 account_dict['network_acls']['ip_rules'].append(dict(value=rule.ip_address_or_range, action=rule.action))
1331
1332 account_dict['network_acls']['resource_access_rules'] = []
1333 if getattr(account_obj.network_rule_set, 'resource_access_rules', None):
1334 for rule in account_obj.network_rule_set.resource_access_rules:
1335 account_dict['network_acls']['resource_access_rules'].append(dict(
1336 resource_id=rule.resource_id,
1337 tenant_id=rule.tenant_id
1338 ))
1339
1340 account_dict['encryption'] = dict()
1341 if account_obj.encryption:
1342 account_dict['encryption']['require_infrastructure_encryption'] = account_obj.encryption.require_infrastructure_encryption
1343 account_dict['encryption']['key_source'] = account_obj.encryption.key_source
1344 if account_obj.encryption.services:
1345 account_dict['encryption']['services'] = dict()
1346 if account_obj.encryption.services.file:
1347 account_dict['encryption']['services']['file'] = dict(enabled=True)
1348 if account_obj.encryption.services.table:
1349 account_dict['encryption']['services']['table'] = dict(enabled=True)
1350 if account_obj.encryption.services.queue:
1351 account_dict['encryption']['services']['queue'] = dict(enabled=True)
1352 if account_obj.encryption.services.blob:
1353 account_dict['encryption']['services']['blob'] = dict(enabled=True)
1354
1355 if account_obj.encryption.encryption_identity:
1356 account_dict['encryption']['encryption_identity'] = dict(
1357 encryption_user_assigned_identity=account_obj.encryption.encryption_identity.encryption_user_assigned_identity)
1358 else:
1359 account_dict['encryption']['encryption_identity'] = None
1360 if account_obj.encryption.key_vault_properties:
1361 account_dict['encryption']['key_vault_properties'] = dict(key_vault_uri=account_obj.encryption.key_vault_properties.key_vault_uri,
1362 key_name=account_obj.encryption.key_vault_properties.key_name,
1363 key_version=account_obj.encryption.key_vault_properties.key_version)
1364 else:
1365 account_dict['encryption']['key_vault_properties'] = None
1366
1367 account_dict['identity'] = dict()
1368 if account_obj.identity:
1369 account_dict['identity'] = account_obj.identity.as_dict()
1370
1371 return account_dict
1372
1373 def failover_account(self):
1374 if str(self.account_dict['sku_name']) not in ["Standard_GZRS", "Standard_GRS", "Standard_RAGZRS", "Standard_RAGRS"]:
1375 self.fail("Storage account SKU ({0}) does not support failover to a secondary region.".format(self.account_dict['sku_name']))
1376 try:
1377 account_obj = self.storage_client.storage_accounts.get_properties(self.resource_group, self.name, expand='georeplicationstats')
1378 except Exception as exc:
1379 self.fail("Error occurred while acquiring geo-replication status. {0}".format(str(exc)))
1380
1381 if account_obj.failover_in_progress:
1382 self.fail("Storage account is already in process of failing over to secondary region.")
1383
1384 if not account_obj.geo_replication_stats.can_failover:
1385 self.fail("Storage account is unable to failover. Secondary region has status of {0}".format(account_obj.geo_replication_stats.status))
1386
1387 try:
1388 poller = self.storage_client.storage_accounts.begin_failover(self.resource_group, self.name)
1389 result = self.get_poller_result(poller)
1390 except Exception as exc:
1391 self.fail("Error occurred while attempting a failover operation. {0}".format(str(exc)))
1392
1393 self.results['changed'] = True
1394 return result
1395
1396 def update_network_rule_set(self):
1397 if not self.check_mode:
1398 try:
1399 models = self.storage_models
1400 nacls = self.network_acls or {}
1401
1402 vnet_rules = None
1403 if nacls.get('virtual_network_rules'):
1404 vnet_rules = [
1405 models.VirtualNetworkRule(
1406 virtual_network_resource_id=r.get('id'),
1407 action=r.get('action', 'Allow')
1408 ) for r in (nacls.get('virtual_network_rules') or [])
1409 ]
1410
1411 ip_rules = None
1412 if nacls.get('ip_rules'):
1413 ip_rules = [
1414 models.IPRule(
1415 ip_address_or_range=r.get('value'),
1416 action=r.get('action', 'Allow')
1417 ) for r in (nacls.get('ip_rules') or [])
1418 ]
1419
1420 resource_access_rules = None
1421 # IMPORTANT: when desired list is [], send [] (not None) to clear rules
1422 if nacls.get('resource_access_rules') is not None:
1423 resource_access_rules = [
1424 models.ResourceAccessRule(
1425 resource_id=r.get('resource_id'),
1426 tenant_id=r.get('tenant_id')
1427 ) for r in (nacls.get('resource_access_rules') or [])
1428 ]
1429 nrs = models.NetworkRuleSet(
1430 bypass=nacls.get('bypass'),
1431 default_action=nacls.get('default_action', 'Allow'),
1432 virtual_network_rules=vnet_rules,
1433 ip_rules=ip_rules,
1434 resource_access_rules=resource_access_rules
1435 )
1436
1437 parameters = self.storage_models.StorageAccountUpdateParameters(network_rule_set=nrs)
1438 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1439 except Exception as exc:
1440 self.fail("Failed to update network ACLs: {0}".format(str(exc)))
1441
1442 def update_account(self):
1443 self.log('Update storage account {0}'.format(self.name))
1444 if self.network_acls:
1445 if self.network_acls.get('default_action', 'Allow') != self.account_dict['network_acls']['default_action']:
1446 self.results['changed'] = True
1447 self.account_dict['network_acls']['default_action'] = self.network_acls['default_action']
1448 self.update_network_rule_set()
1449
1450 if self.network_acls.get('default_action', 'Allow') == 'Deny':
1451 desired_rars = self.network_acls.get('resource_access_rules', None)
1452 current_rars = self.account_dict['network_acls'].get('resource_access_rules', [])
1453 if desired_rars is not None:
1454 desired_ids = {r.get('resource_id') for r in (desired_rars or [])}
1455 current_ids = {r.get('resource_id') for r in (current_rars or [])}
1456
1457 if desired_ids != current_ids:
1458 self.results['changed'] = True
1459 # Keep local state in sync for readability
1460 self.account_dict['network_acls']['resource_access_rules'] = desired_rars
1461 self.update_network_rule_set()
1462
1463 if self.network_acls.get('bypass') != self.account_dict['network_acls'].get('bypass'):
1464 self.results['changed'] = True
1465 self.account_dict['network_acls']['bypass'] = self.network_acls['bypass']
1466 self.update_network_rule_set()
1467
1468 if self.network_acls.get('virtual_network_rules') is not None:
1469 desired_vnet_ids = {r.get('id') for r in (self.network_acls.get('virtual_network_rules') or [])}
1470 current_vnet_ids = {r.get('id') for r in (self.account_dict['network_acls'].get('virtual_network_rules') or [])}
1471
1472 if desired_vnet_ids != current_vnet_ids:
1473 self.results['changed'] = True
1474 self.account_dict['network_acls']['virtual_network_rules'] = self.network_acls.get('virtual_network_rules') or []
1475 self.update_network_rule_set()
1476
1477 if self.network_acls.get('ip_rules') is not None:
1478 desired_ip_values = {r.get('value') for r in (self.network_acls.get('ip_rules') or [])}
1479 current_ip_values = {r.get('value') for r in (self.account_dict['network_acls'].get('ip_rules') or [])}
1480
1481 if desired_ip_values != current_ip_values:
1482 self.results['changed'] = True
1483 self.account_dict['network_acls']['ip_rules'] = self.network_acls.get('ip_rules') or []
1484 self.update_network_rule_set()
1485
1486 if self.enable_nfs_v3 is not None and bool(self.enable_nfs_v3) != bool(self.account_dict.get('enable_nfs_v3')):
1487 self.results['changed'] = True
1488 self.account_dict['enable_nfs_v3'] = self.enable_nfs_v3
1489
1490 if self.is_hns_enabled is not None and bool(self.is_hns_enabled) != bool(self.account_dict.get('is_hns_enabled')):
1491 self.results['changed'] = True
1492 self.account_dict['is_hns_enabled'] = self.is_hns_enabled
1493 if not self.check_mode:
1494 self.fail("The is_hns_enabled parameter not support to update, from {0} to {1}".
1495 format(bool(self.account_dict.get('is_hns_enabled')), self.is_hns_enabled))
1496
1497 if self.https_only is not None and bool(self.https_only) != bool(self.account_dict.get('https_only')):
1498 self.results['changed'] = True
1499 self.account_dict['https_only'] = self.https_only
1500 if not self.check_mode:
1501 try:
1502 parameters = self.storage_models.StorageAccountUpdateParameters(enable_https_traffic_only=self.https_only)
1503 self.storage_client.storage_accounts.update(self.resource_group,
1504 self.name,
1505 parameters)
1506 except Exception as exc:
1507 self.fail("Failed to update https only: {0}".format(str(exc)))
1508
1509 if self.minimum_tls_version is not None and self.minimum_tls_version != self.account_dict.get('minimum_tls_version'):
1510 self.results['changed'] = True
1511 self.account_dict['minimum_tls_version'] = self.minimum_tls_version
1512 if not self.check_mode:
1513 try:
1514 parameters = self.storage_models.StorageAccountUpdateParameters(minimum_tls_version=self.minimum_tls_version)
1515 self.storage_client.storage_accounts.update(self.resource_group,
1516 self.name,
1517 parameters)
1518 except Exception as exc:
1519 self.fail("Failed to update minimum tls: {0}".format(str(exc)))
1520
1521 if self.public_network_access is not None and self.public_network_access != self.account_dict.get('public_network_access'):
1522 self.results['changed'] = True
1523 self.account_dict['public_network_access'] = self.public_network_access
1524 if not self.check_mode:
1525 try:
1526 parameters = self.storage_models.StorageAccountUpdateParameters(public_network_access=self.public_network_access)
1527 self.storage_client.storage_accounts.update(self.resource_group,
1528 self.name,
1529 parameters)
1530 except Exception as exc:
1531 self.fail("Failed to update public network access: {0}".format(str(exc)))
1532
1533 if self.allow_blob_public_access is not None and self.allow_blob_public_access != self.account_dict.get('allow_blob_public_access'):
1534 self.results['changed'] = True
1535 self.account_dict['allow_blob_public_access'] = self.allow_blob_public_access
1536 if not self.check_mode:
1537 try:
1538 parameters = self.storage_models.StorageAccountUpdateParameters(allow_blob_public_access=self.allow_blob_public_access)
1539 self.storage_client.storage_accounts.update(self.resource_group,
1540 self.name,
1541 parameters)
1542 except Exception as exc:
1543 self.fail("Failed to update allow public blob access: {0}".format(str(exc)))
1544
1545 if self.allow_shared_key_access is not None and self.allow_shared_key_access != self.account_dict.get('allow_shared_key_access'):
1546 self.results['changed'] = True
1547 self.account_dict['allow_shared_key_access'] = self.allow_shared_key_access
1548 if not self.check_mode:
1549 try:
1550 parameters = self.storage_models.StorageAccountUpdateParameters(allow_shared_key_access=self.allow_shared_key_access)
1551 self.storage_client.storage_accounts.update(self.resource_group,
1552 self.name,
1553 parameters)
1554 except Exception as exc:
1555 self.fail("Failed to update allow shared key access: {0}".format(str(exc)))
1556
1557 if self.allow_cross_tenant_replication is not None and self.allow_cross_tenant_replication != self.account_dict.get('allow_cross_tenant_replication'):
1558 self.results['changed'] = True
1559 self.account_dict['allow_cross_tenant_replication'] = self.allow_cross_tenant_replication
1560 if not self.check_mode:
1561 try:
1562 parameters = self.storage_models.StorageAccountUpdateParameters(allow_cross_tenant_replication=self.allow_cross_tenant_replication)
1563 self.storage_client.storage_accounts.update(self.resource_group,
1564 self.name,
1565 parameters)
1566 except Exception as exc:
1567 self.fail("Failed to update allow cross tenant replication: {0}".format(str(exc)))
1568
1569 if self.default_to_o_auth_authentication is not None and \
1570 self.default_to_o_auth_authentication != self.account_dict.get('default_to_o_auth_authentication'):
1571 self.results['changed'] = True
1572 self.account_dict['default_to_o_auth_authentication'] = self.default_to_o_auth_authentication
1573 if not self.check_mode:
1574 try:
1575 parameters = self.storage_models.StorageAccountUpdateParameters(default_to_o_auth_authentication=self.default_to_o_auth_authentication)
1576 self.storage_client.storage_accounts.update(self.resource_group,
1577 self.name,
1578 parameters)
1579 except Exception as exc:
1580 self.fail("Failed to update default_to_o_auth_authentication: {0}".format(str(exc)))
1581
1582 if self.account_type:
1583 if self.account_type != self.account_dict['sku_name']:
1584 # change the account type
1585 SkuName = self.storage_models.SkuName
1586 if self.account_dict['sku_name'] in [SkuName.premium_lrs, SkuName.standard_zrs]:
1587 self.fail("Storage accounts of type {0} and {1} cannot be changed.".format(
1588 SkuName.premium_lrs, SkuName.standard_zrs))
1589 if self.account_type in [SkuName.premium_lrs, SkuName.standard_zrs]:
1590 self.fail("Storage account of type {0} cannot be changed to a type of {1} or {2}.".format(
1591 self.account_dict['sku_name'], SkuName.premium_lrs, SkuName.standard_zrs))
1592
1593 self.results['changed'] = True
1594 self.account_dict['sku_name'] = self.account_type
1595
1596 if self.results['changed'] and not self.check_mode:
1597 # Perform the update. The API only allows changing one attribute per call.
1598 try:
1599 self.log("sku_name: %s" % self.account_dict['sku_name'])
1600 self.log("sku_tier: %s" % self.account_dict['sku_tier'])
1601 sku = self.storage_models.Sku(name=SkuName(self.account_dict['sku_name']))
1602 sku.tier = self.storage_models.SkuTier(self.account_dict['sku_tier'])
1603 parameters = self.storage_models.StorageAccountUpdateParameters(sku=sku)
1604 self.storage_client.storage_accounts.update(self.resource_group,
1605 self.name,
1606 parameters)
1607 except Exception as exc:
1608 self.fail("Failed to update account type: {0}".format(str(exc)))
1609
1610 if self.custom_domain:
1611 if not self.account_dict['custom_domain'] or self.account_dict['custom_domain'] != self.custom_domain:
1612 self.results['changed'] = True
1613 self.account_dict['custom_domain'] = self.custom_domain
1614
1615 if self.results['changed'] and not self.check_mode:
1616 new_domain = self.storage_models.CustomDomain(name=self.custom_domain['name'],
1617 use_sub_domain=self.custom_domain['use_sub_domain'])
1618 parameters = self.storage_models.StorageAccountUpdateParameters(custom_domain=new_domain)
1619 try:
1620 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1621 except Exception as exc:
1622 self.fail("Failed to update custom domain: {0}".format(str(exc)))
1623
1624 if self.update_identity:
1625 self.results['changed'] = True
1626 parameters = self.storage_models.StorageAccountUpdateParameters(identity=self.identity)
1627 try:
1628 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1629 except Exception as exc:
1630 self.fail("Failed to update access tier: {0}".format(str(exc)))
1631
1632 if self.access_tier:
1633 if not self.account_dict['access_tier'] or self.account_dict['access_tier'] != self.access_tier:
1634 self.results['changed'] = True
1635 self.account_dict['access_tier'] = self.access_tier
1636
1637 if self.results['changed'] and not self.check_mode:
1638 parameters = self.storage_models.StorageAccountUpdateParameters(access_tier=self.access_tier)
1639 try:
1640 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1641 except Exception as exc:
1642 self.fail("Failed to update access tier: {0}".format(str(exc)))
1643
1644 if self.large_file_shares_state is not None:
1645 if self.large_file_shares_state != self.account_dict['large_file_shares_state']:
1646 self.results['changed'] = True
1647 self.account_dict['large_file_shares_state'] = self.large_file_shares_state
1648
1649 if self.results['changed'] and not self.check_mode:
1650 if self.large_file_shares_state == 'Disabled':
1651 parameters = self.storage_models.StorageAccountUpdateParameters(large_file_shares_state=None)
1652 else:
1653 parameters = self.storage_models.StorageAccountUpdateParameters(large_file_shares_state=self.large_file_shares_state)
1654 try:
1655 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1656 except Exception as exc:
1657 self.fail("Failed to update large_file_shares_state: {0}".format(str(exc)))
1658
1659 update_tags, self.account_dict['tags'] = self.update_tags(self.account_dict['tags'])
1660 if update_tags:
1661 self.results['changed'] = True
1662 if not self.check_mode:
1663 parameters = self.storage_models.StorageAccountUpdateParameters(tags=self.account_dict['tags'])
1664 try:
1665 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1666 except Exception as exc:
1667 self.fail("Failed to update tags: {0}".format(str(exc)))
1668
1669 if not self.default_compare({}, self.immutable_storage_with_versioning, self.account_dict['immutable_storage_with_versioning'], '', dict(compare=[])):
1670 self.results['changed'] = True
1671 if not self.check_mode:
1672 parameters = self.storage_models.StorageAccountUpdateParameters(immutable_storage_with_versioning=self.immutable_storage_with_versioning)
1673 try:
1674 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1675 except Exception as exc:
1676 self.fail("Failed to update immutable_storage_with_versioning: {0}".format(str(exc)))
1677
1678 if self.blob_cors and not compare_cors(self.account_dict.get('blob_cors', []), self.blob_cors):
1679 self.results['changed'] = True
1680 if not self.check_mode:
1681 self.set_blob_cors()
1682
1683 if self.static_website and self.static_website != self.account_dict.get("static_website", dict()):
1684 self.results['changed'] = True
1685 self.account_dict['static_website'] = self.static_website
1686 self.update_static_website()
1687
1688 if self.encryption is not None:
1689 encryption_changed = False
1690 if self.encryption.get('require_infrastructure_encryption') and bool(self.encryption.get('require_infrastructure_encryption')) \
1691 != bool(self.account_dict['encryption']['require_infrastructure_encryption']):
1692 encryption_changed = True
1693
1694 if self.encryption.get('key_source') != self.account_dict['encryption']['key_source']:
1695 encryption_changed = True
1696
1697 if self.encryption.get('services') is not None:
1698 if self.encryption.get('queue') is not None and self.account_dict['encryption']['services'].get('queue') is not None:
1699 encryption_changed = True
1700 if self.encryption.get('file') is not None and self.account_dict['encryption']['services'].get('file') is not None:
1701 encryption_changed = True
1702 if self.encryption.get('table') is not None and self.account_dict['encryption']['services'].get('table') is not None:
1703 encryption_changed = True
1704 if self.encryption.get('blob') is not None and self.account_dict['encryption']['services'].get('blob') is not None:
1705 encryption_changed = True
1706 if not self.default_compare({}, self.encryption.get('key_vault_properties'),
1707 self.account_dict['encryption'].get('key_vault_properties'), '', dict(compare=[])):
1708 encryption_changed = True
1709 if not self.default_compare({}, self.encryption.get('encryption_identity'),
1710 self.account_dict['encryption'].get('encryption_identity'), '', dict(compare=[])):
1711 encryption_changed = True
1712
1713 if encryption_changed and not self.check_mode:
1714 self.fail("The encryption can't update encryption, encryption info as {0}".format(self.account_dict['encryption']))
1715 time.sleep(1)
1716 return self.get_account()
1717
1718 def create_account(self):
1719 self.log("Creating account {0}".format(self.name))
1720
1721 if not self.location:
1722 self.fail('Parameter error: location required when creating a storage account.')
1723
1724 if not self.account_type:
1725 self.fail('Parameter error: account_type required when creating a storage account.')
1726
1727 if not self.access_tier and self.kind == 'BlobStorage':
1728 self.fail('Parameter error: access_tier required when creating a storage account of type BlobStorage.')
1729
1730 self.check_name_availability()
1731 self.results['changed'] = True
1732
1733 if self.check_mode:
1734 account_dict = dict(
1735 location=self.location,
1736 account_type=self.account_type,
1737 name=self.name,
1738 resource_group=self.resource_group,
1739 enable_https_traffic_only=self.https_only,
1740 minimum_tls_version=self.minimum_tls_version,
1741 public_network_access=self.public_network_access,
1742 allow_blob_public_access=self.allow_blob_public_access,
1743 encryption=self.encryption,
1744 is_hns_enabled=self.is_hns_enabled,
1745 enable_nfs_v3=self.enable_nfs_v3,
1746 large_file_shares_state=self.large_file_shares_state,
1747 default_to_o_auth_authentication=self.default_to_o_auth_authentication,
1748 allow_cross_tenant_replication=self.allow_cross_tenant_replication,
1749 allow_shared_key_access=self.allow_shared_key_access,
1750 identity=self.identity,
1751 immutable_storage_with_versioning=self.immutable_storage_with_versioning,
1752 tags=dict()
1753 )
1754 if self.tags:
1755 account_dict['tags'] = self.tags
1756 if self.network_acls:
1757 account_dict['network_acls'] = self.network_acls
1758 if self.blob_cors:
1759 account_dict['blob_cors'] = self.blob_cors
1760 if self.static_website:
1761 account_dict['static_website'] = self.static_website
1762 return account_dict
1763 sku = self.storage_models.Sku(name=self.storage_models.SkuName(self.account_type))
1764 sku.tier = self.storage_models.SkuTier.standard if 'Standard' in self.account_type else \
1765 self.storage_models.SkuTier.premium
1766 # pylint: disable=missing-kwoa
1767 parameters = self.storage_models.StorageAccountCreateParameters(sku=sku,
1768 kind=self.kind,
1769 location=self.location,
1770 tags=self.tags,
1771 identity=self.identity,
1772 enable_https_traffic_only=self.https_only,
1773 minimum_tls_version=self.minimum_tls_version,
1774 public_network_access=self.public_network_access,
1775 allow_blob_public_access=self.allow_blob_public_access,
1776 encryption=self.encryption,
1777 is_hns_enabled=self.is_hns_enabled,
1778 enable_nfs_v3=self.enable_nfs_v3,
1779 access_tier=self.access_tier,
1780 allow_shared_key_access=self.allow_shared_key_access,
1781 default_to_o_auth_authentication=self.default_to_o_auth_authentication,
1782 allow_cross_tenant_replication=self.allow_cross_tenant_replication,
1783 immutable_storage_with_versioning=self.immutable_storage_with_versioning,
1784 large_file_shares_state=self.large_file_shares_state)
1785 self.log(str(parameters))
1786 try:
1787 poller = self.storage_client.storage_accounts.begin_create(self.resource_group, self.name, parameters)
1788 self.get_poller_result(poller)
1789 except Exception as e:
1790 self.log('Error creating storage account.')
1791 self.fail("Failed to create account: {0}".format(str(e)))
1792 if self.network_acls:
1793 self.set_network_acls()
1794 if self.blob_cors:
1795 self.set_blob_cors()
1796 if self.static_website:
1797 self.update_static_website()
1798 return self.get_account()
1799
1800 def delete_account(self):
1801 if self.account_dict['provisioning_state'] == self.storage_models.ProvisioningState.succeeded.value and \
1802 not self.force_delete_nonempty and self.account_has_blob_containers():
1803 self.fail("Account contains blob containers. Is it in use? Use the force_delete_nonempty option to attempt deletion.")
1804
1805 self.log('Delete storage account {0}'.format(self.name))
1806 self.results['changed'] = True
1807 if not self.check_mode:
1808 try:
1809 status = self.storage_client.storage_accounts.delete(self.resource_group, self.name)
1810 self.log("delete status: ")
1811 self.log(str(status))
1812 except Exception as e:
1813 self.fail("Failed to delete the account: {0}".format(str(e)))
1814 return True
1815
1816 def account_has_blob_containers(self):
1817 '''
1818 If there are blob containers, then there are likely VMs depending on this account and it should
1819 not be deleted.
1820 '''
1821 if self.kind == "FileStorage":
1822 return False
1823 self.log('Checking for existing blob containers')
1824 blob_service = self.get_blob_service_client(self.resource_group, self.name, self.auth_mode)
1825 try:
1826 response = blob_service.list_containers()
1827 except Exception:
1828 # No blob storage available?
1829 return False
1830
1831 if len(list(response)) > 0:
1832 return True
1833 return False
1834
1835 def set_blob_cors(self):
1836 try:
1837 cors_rules = self.storage_models.CorsRules(cors_rules=[self.storage_models.CorsRule(**x) for x in self.blob_cors])
1838 self.storage_client.blob_services.set_service_properties(self.resource_group,
1839 self.name,
1840 self.storage_models.BlobServiceProperties(cors=cors_rules))
1841 except Exception as exc:
1842 self.fail("Failed to set CORS rules: {0}".format(str(exc)))
1843
1844 def update_static_website(self):
1845 if self.kind == "FileStorage":
1846 return
1847 try:
1848 self.get_blob_service_client(self.resource_group, self.name, self.auth_mode).set_service_properties(static_website=self.static_website)
1849 except Exception as exc:
1850 self.fail("Failed to set static website config: {0}".format(str(exc)))
1851
1852 def set_network_acls(self):
1853 try:
1854 models = self.storage_models
1855 nacls = self.network_acls or {}
1856
1857 def build_network_rule_set(nacls_local):
1858 vnet_rules = None
1859 if nacls_local.get('virtual_network_rules'):
1860 vnet_rules = [
1861 models.VirtualNetworkRule(
1862 virtual_network_resource_id=r.get('id'),
1863 action=r.get('action', 'Allow')
1864 ) for r in (nacls_local.get('virtual_network_rules') or [])
1865 ]
1866
1867 ip_rules = None
1868 if nacls_local.get('ip_rules'):
1869 ip_rules = [
1870 models.IPRule(
1871 ip_address_or_range=r.get('value'),
1872 action=r.get('action', 'Allow')
1873 ) for r in (nacls_local.get('ip_rules') or [])
1874 ]
1875
1876 resource_access_rules = None
1877 if nacls_local.get('resource_access_rules'):
1878 resource_access_rules = [
1879 models.ResourceAccessRule(
1880 resource_id=r.get('resource_id'),
1881 tenant_id=r.get('tenant_id')
1882 ) for r in (nacls_local.get('resource_access_rules') or [])
1883 ]
1884
1885 return models.NetworkRuleSet(
1886 bypass=nacls_local.get('bypass'),
1887 default_action=nacls_local.get('default_action', 'Allow'),
1888 virtual_network_rules=vnet_rules,
1889 ip_rules=ip_rules,
1890 resource_access_rules=resource_access_rules
1891 )
1892
1893 nrs = build_network_rule_set(nacls)
1894 parameters = self.storage_models.StorageAccountUpdateParameters(network_rule_set=nrs)
1895 self.storage_client.storage_accounts.update(self.resource_group, self.name, parameters)
1896 except Exception as exc:
1897 self.fail("Failed to update network ACLs: {0}".format(str(exc)))
1898
1899
1900 def main():
1901 AzureRMStorageAccount()
1902
1903
1904 if __name__ == '__main__':
1905 main()