Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_storageblob.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_storageblob
15 short_description: Manage blob containers and blob objects
16 version_added: "0.0.1"
17 description:
18 - Create, update and delete blob containers and blob objects.
19 - Use to upload a file and store it as a blob object, or download a blob object to a file(upload and download mode)
20 - Use to upload a batch of files under a given directory(batch upload mode)
21 - Use to upload a blob directly from a web URL (source_url), enabling server-side copy from HTTP/HTTPS sources.
22 - In the batch upload mode, the existing blob object will be overwritten if a blob object with the same name is to be created.
23 - the module can work exclusively in three modes, when C(batch_upload_src) is set, it is working in batch upload mode;
24 when C(src) is set, it is working in upload mode and when C(dst) is set, it is working in dowload mode.
25 options:
26 auth_mode:
27 description:
28 - The mode in which to run the command. C(login) mode will directly use your login credentials for the authentication.
29 - The legacy C(key) mode will attempt to query for an account key if no authentication parameters for the account are provided.
30 - Can also be set via the environment variable C(AZURE_STORAGE_AUTH_MODE).
31 default: key
32 type: str
33 choices:
34 - key
35 - login
36 version_added: "1.19.0"
37 storage_account_name:
38 description:
39 - Name of the storage account to use.
40 required: true
41 type: str
42 aliases:
43 - account_name
44 - storage_account
45 blob:
46 description:
47 - Name of a blob object within the container.
48 aliases:
49 - blob_name
50 type: str
51 blob_type:
52 description:
53 - Type of blob object.
54 default: block
55 type: str
56 choices:
57 - block
58 - page
59 version_added: "0.0.1"
60 container:
61 description:
62 - Name of a blob container within the storage account.
63 required: true
64 type: str
65 aliases:
66 - container_name
67 content_type:
68 description:
69 - Set the blob content-type header. For example C(image/png).
70 type: str
71 cache_control:
72 description:
73 - Set the blob cache-control header.
74 type: str
75 content_disposition:
76 description:
77 - Set the blob content-disposition header.
78 type: str
79 content_encoding:
80 description:
81 - Set the blob encoding header.
82 type: str
83 content_language:
84 description:
85 - Set the blob content-language header.
86 type: str
87 content_md5:
88 description:
89 - Set the blob md5 hash value.
90 type: str
91 dest:
92 description:
93 - Destination file path. Use with state C(present) to download a blob.
94 aliases:
95 - destination
96 type: path
97 force:
98 description:
99 - Overwrite existing blob or file when uploading or downloading. Force deletion of a container that contains blobs.
100 type: bool
101 default: no
102 resource_group:
103 description:
104 - Name of the resource group to use.
105 required: true
106 type: str
107 aliases:
108 - resource_group_name
109 src:
110 description:
111 - Source file path. Use with state C(present) to upload a blob.
112 type: str
113 aliases:
114 - source
115 batch_upload_src:
116 description:
117 - Batch upload source directory. Use with state C(present) to upload batch of files under the directory.
118 type: path
119 batch_upload_dst:
120 description:
121 - Base directory in container when upload batch of files.
122 type: path
123 standard_blob_tier:
124 description:
125 - Specifies the blob tier to set the blob to.
126 - This is only applicable for block blobs on standard storage accounts.
127 type: str
128 choices:
129 - Archive
130 - Cool
131 - Cold
132 - Hot
133 source_url:
134 description:
135 - HTTP/HTTPS URL of the source file to copy directly into the blob.
136 - The source must be publicly accessible, or authenticated via a shared access signature (SAS) appended
137 to the URL, or via bearer token on supported Azure sources.
138 - Only supported for block blobs.
139 type: str
140 state:
141 description:
142 - State of a container or blob.
143 - Use state C(absent) with a container value only to delete a container. Include a blob value to remove
144 a specific blob. A container will not be deleted, if it contains blobs. Use the I(force) option to override,
145 deleting the container and all associated blobs.
146 - Use state C(present) to create or update a container and upload or download a blob. If the container
147 does not exist, it will be created. If it exists, it will be updated with configuration options. Provide
148 a blob name and either src or dest to upload or download. Provide a src path to upload and a dest path
149 to download. If a blob (uploading) or a file (downloading) already exists, it will not be overwritten
150 unless I(force=true).
151 default: present
152 type: str
153 choices:
154 - absent
155 - present
156 public_access:
157 description:
158 - A container's level of public access. By default containers are private.
159 - Can only be set at time of container creation.
160 - The I(public_access) parameter should not be set for private access.
161 - If I(public_access) is not configured, access level is by default private. It can not be set explicitely to private.
162 type: str
163 choices:
164 - container
165 - blob
166
167 extends_documentation_fragment:
168 - azure.azcollection.azure
169 - azure.azcollection.azure_tags
170
171 author:
172 - Chris Houseknecht (@chouseknecht)
173 - Matt Davis (@nitzmahone)
174
175 '''
176
177 EXAMPLES = '''
178 - name: Remove container foo
179 azure_rm_storageblob:
180 resource_group: myResourceGroup
181 storage_account_name: clh0002
182 container: foo
183 state: absent
184
185 - name: Create container foo and upload a file
186 azure_rm_storageblob:
187 resource_group: myResourceGroup
188 storage_account_name: clh0002
189 container: foo
190 blob: graylog.png
191 src: ./files/graylog.png
192 public_access: container
193 content_type: 'application/image'
194
195 - name: Download the file
196 azure_rm_storageblob:
197 resource_group: myResourceGroup
198 storage_account_name: clh0002
199 container: foo
200 blob: graylog.png
201 dest: ~/tmp/images/graylog.png
202
203 - name: Upload a blob directly from a web URL asynchronously (public HTTP/HTTPS)
204 azure_rm_storageblob:
205 resource_group: myResourceGroup
206 storage_account_name: clh0002
207 container: images
208 blob: graylog.png
209 source_url: https://example.com/path/to/graylog.png
210 content_type: image/png
211 cache_control: 'public, max-age=3600'
212 standard_blob_tier: Hot
213 state: present
214 async: 1800
215 poll: 0
216
217 - name: Upload a blob directly from a web URL (public HTTP/HTTPS)
218 azure_rm_storageblob:
219 resource_group: myResourceGroup
220 storage_account_name: clh0002
221 container: images
222 blob: graylog.png
223 source_url: https://example.com/path/to/graylog.png
224 content_type: image/png
225 cache_control: 'public, max-age=3600'
226 standard_blob_tier: Hot
227 state: present
228 '''
229
230 RETURN = '''
231 blob:
232 description:
233 - Facts about the current state of the blob.
234 returned: when a blob is operated on
235 type: dict
236 sample: {
237 "content_length": 136532,
238 "content_settings": {
239 "cache_control": null,
240 "content_disposition": null,
241 "content_encoding": null,
242 "content_language": null,
243 "content_md5": null,
244 "content_type": "application/image"
245 },
246 "last_modified": "09-Mar-2016 22:08:25 +0000",
247 "name": "graylog.png",
248 "tags": {},
249 "type": "BlockBlob",
250 'standard_blob_tier': 'Hot'
251 }
252 container:
253 description:
254 - Facts about the current state of the selected container.
255 returned: always
256 type: dict
257 sample: {
258 "last_modified": "09-Mar-2016 19:28:26 +0000",
259 "name": "foo",
260 "tags": {}
261 }
262 '''
263
264 import os
265 import mimetypes
266 import time
267
268 try:
269 from azure.storage.blob._models import BlobType, ContentSettings, StandardBlobTier
270 from azure.core.exceptions import ResourceNotFoundError
271 from azure.mgmt.storage.models import BlobContainer
272 except ImportError:
273 # This is handled in azure_rm_common
274 pass
275
276 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
277 from ansible.module_utils.basic import env_fallback
278
279
280 class AzureRMStorageBlob(AzureRMModuleBase):
281
282 def __init__(self):
283
284 self.module_arg_spec = dict(
285 auth_mode=dict(
286 type='str',
287 choices=['key', 'login'],
288 fallback=(env_fallback, ['AZURE_STORAGE_AUTH_MODE']),
289 default="key"
290 ),
291 storage_account_name=dict(required=True, type='str', aliases=['account_name', 'storage_account']),
292 blob=dict(type='str', aliases=['blob_name']),
293 blob_type=dict(type='str', default='block', choices=['block', 'page']),
294 standard_blob_tier=dict(type='str', choices=['Archive', 'Cool', 'Cold', 'Hot']),
295 container=dict(required=True, type='str', aliases=['container_name']),
296 dest=dict(type='path', aliases=['destination']),
297 force=dict(type='bool', default=False),
298 resource_group=dict(required=True, type='str', aliases=['resource_group_name']),
299 src=dict(type='str', aliases=['source']),
300 source_url=dict(type='str'),
301 batch_upload_src=dict(type='path'),
302 batch_upload_dst=dict(type='path'),
303 state=dict(type='str', default='present', choices=['absent', 'present']),
304 public_access=dict(type='str', choices=['container', 'blob']),
305 content_type=dict(type='str'),
306 content_encoding=dict(type='str'),
307 content_language=dict(type='str'),
308 content_disposition=dict(type='str'),
309 cache_control=dict(type='str'),
310 content_md5=dict(type='str'),
311 )
312
313 mutually_exclusive = [('src', 'dest'), ('src', 'batch_upload_src'), ('dest', 'batch_upload_src'),
314 ('source_url', 'src'), ('source_url', 'dest'), ('source_url', 'batch_upload_src')]
315
316 self.blob_service_client = None
317 self.blob_details = None
318 self.storage_account_name = None
319 self.blob = None
320 self.blob_obj = None
321 self.blob_type = None
322 self.standard_blob_tier = None
323 self.container = None
324 self.container_obj = None
325 self.dest = None
326 self.force = None
327 self.resource_group = None
328 self.src = None
329 self.source_url = None
330 self.batch_upload_src = None
331 self.batch_upload_dst = None
332 self.state = None
333 self.tags = None
334 self.public_access = None
335 self.results = dict(
336 changed=False,
337 actions=[],
338 container=dict(),
339 blob=dict()
340 )
341
342 super(AzureRMStorageBlob, self).__init__(derived_arg_spec=self.module_arg_spec,
343 supports_check_mode=True,
344 mutually_exclusive=mutually_exclusive,
345 supports_tags=True)
346
347 def exec_module(self, **kwargs):
348
349 for key in list(self.module_arg_spec.keys()) + ['tags']:
350 setattr(self, key, kwargs[key])
351
352 self.results['check_mode'] = self.check_mode
353
354 # add file path validation
355
356 if self.requires_data_plane_access():
357 # Data plane client
358 self.blob_service_client = self.get_blob_service_client(self.resource_group, self.storage_account_name, self.auth_mode)
359
360 self.container_obj = self.get_container()
361 if self.blob and self.requires_data_plane_access():
362 self.blob_obj = self.get_blob()
363
364 if self.state == 'present':
365 if not self.container_obj:
366 # create the container
367 self.create_container()
368 elif self.container_obj and not self.blob:
369 # update container attributes
370 update_tags, self.container_obj['tags'] = self.update_tags(self.container_obj.get('tags'))
371 if update_tags:
372 self.update_container_tags(self.container_obj['tags'])
373
374 if self.batch_upload_src:
375 self.batch_upload()
376 return self.results
377
378 if self.blob:
379 # create, update or download blob
380 if self.src and self.src_is_valid():
381 if self.blob_obj and not self.force:
382 self.log("Cannot upload to {0}. Blob with that name already exists. Use the force option".format(self.blob))
383 else:
384 self.upload_blob()
385 elif self.dest and self.dest_is_valid():
386 self.download_blob()
387 elif self.source_url:
388 self.upload_blob_from_url()
389
390 update_tags, self.blob_obj['tags'] = self.update_tags(self.blob_obj.get('tags'))
391 if update_tags:
392 self.update_blob_tags(self.blob_obj['tags'])
393
394 if self.results.get('copy_status') == 'pending':
395 pass
396 else:
397 if self.blob_content_settings_differ():
398 self.update_blob_content_settings()
399
400 if self.standard_blob_tier is not None and self.blob_obj.get('standard_blob_tier') is not None and \
401 self.blob_obj['standard_blob_tier'] != self.standard_blob_tier:
402 self.update_blob_tier()
403
404 elif self.state == 'absent':
405 if not self.blob:
406 # Delete Container
407 # Initialize a data-plane client if caller force=false
408 if not self.blob_service_client and not self.force:
409 try:
410 self.blob_service_client = self.get_blob_service_client(
411 self.resource_group, self.storage_account_name, self.auth_mode
412 )
413 except Exception:
414 # No data-plane permissions or connectivity. Fall back to a straight management-plane delete.
415 self.blob_service_client = None
416
417 if self.blob_service_client:
418 # Data plane
419 if self.container_has_blobs():
420 if self.force:
421 self.delete_container()
422 else:
423 self.log("Cannot delete container {0}. It contains blobs. Use the force option.".format(self.container))
424 else:
425 self.delete_container()
426 else:
427 # Management plane
428 self.delete_container()
429
430 elif self.container_obj and self.blob_obj:
431 # Delete blob
432 self.delete_blob()
433
434 # until we sort out how we want to do this globally
435 del self.results['actions']
436 return self.results
437
438 def batch_upload(self):
439
440 def _glob_files_locally(folder_path):
441
442 len_folder_path = len(folder_path) + 1
443
444 for root, v, files in os.walk(folder_path):
445 for f in files:
446 full_path = os.path.join(root, f)
447 yield full_path, full_path[len_folder_path:]
448
449 def _normalize_blob_file_path(path, name):
450 path_sep = '/'
451 if path:
452 name = path_sep.join((path, name))
453
454 return path_sep.join(os.path.normpath(name).split(os.path.sep)).strip(path_sep)
455
456 def _guess_content_type(file_path, original):
457 if original.content_encoding or original.content_type:
458 return original
459
460 mimetypes.add_type('application/json', '.json')
461 mimetypes.add_type('application/javascript', '.js')
462 mimetypes.add_type('application/wasm', '.wasm')
463
464 content_type, v = mimetypes.guess_type(file_path)
465 return ContentSettings(content_type=content_type,
466 content_disposition=original.content_disposition,
467 content_language=original.content_language,
468 content_md5=original.content_md5,
469 cache_control=original.cache_control)
470
471 if not os.path.exists(self.batch_upload_src):
472 self.fail("batch upload source source directory {0} does not exist".format(self.batch_upload_src))
473
474 if not os.path.isdir(self.batch_upload_src):
475 self.fail("incorrect usage: {0} is not a directory".format(self.batch_upload_src))
476
477 source_dir = os.path.realpath(self.batch_upload_src)
478 source_files = list(_glob_files_locally(source_dir))
479
480 content_settings = ContentSettings(content_type=self.content_type,
481 content_encoding=self.content_encoding,
482 content_language=self.content_language,
483 content_disposition=self.content_disposition,
484 cache_control=self.cache_control,
485 content_md5=None)
486
487 for src, blob_path in source_files:
488 if self.batch_upload_dst:
489 blob_path = _normalize_blob_file_path(self.batch_upload_dst, blob_path)
490 if not self.check_mode:
491 try:
492 client = self.blob_service_client.get_blob_client(container=self.container, blob=blob_path)
493 with open(src, "rb") as data:
494 client.upload_blob(data=data,
495 blob_type=self.get_blob_type(self.blob_type),
496 metadata=self.tags,
497 content_settings=_guess_content_type(src, content_settings),
498 standard_blob_tier=self.get_blob_tier(self.standard_blob_tier),
499 overwrite=self.force)
500 except Exception as exc:
501 self.fail("Error creating blob {0} - {1}".format(src, str(exc)))
502 self.results['actions'].append('created blob from {0}'.format(src))
503
504 self.results['changed'] = True
505 self.results['container'] = self.container_obj
506
507 def get_blob_tier(self, blob_tier):
508 if blob_tier == "archive":
509 return StandardBlobTier.Archive
510 elif blob_tier == "cool":
511 return StandardBlobTier.Cool
512 elif blob_tier == "hot":
513 return StandardBlobTier.Hot
514 elif blob_tier == "cold":
515 return StandardBlobTier.Cold
516 else:
517 return None
518
519 def get_blob_type(self, blob_type):
520 if blob_type == "block":
521 return BlobType.BlockBlob
522 elif blob_type == "page":
523 return BlobType.PageBlob
524 else:
525 return BlobType.AppendBlob
526
527 def get_container(self):
528 if self.requires_data_plane_access():
529 try:
530 container = self.blob_service_client.get_container_client(container=self.container).get_container_properties()
531 return dict(
532 name=container["name"],
533 tags=container["metadata"],
534 last_modified=container["last_modified"].strftime('%d-%b-%Y %H:%M:%S %z'),
535 )
536 except ResourceNotFoundError:
537 return {}
538 else:
539 try:
540 container = self.storage_client.blob_containers.get(self.resource_group, self.storage_account_name, self.container)
541 return dict(
542 name=container.name,
543 tags=container.metadata or {},
544 last_modified=container.last_modified_time.strftime('%d-%b-%Y %H:%M:%S %z') if container.last_modified_time else None,
545 )
546 except Exception:
547 return {}
548
549 def get_blob(self):
550 result = dict()
551 blob = None
552 if self.blob:
553 try:
554 blob = self.blob_service_client.get_blob_client(container=self.container, blob=self.blob).get_blob_properties()
555 except ResourceNotFoundError:
556 pass
557 if blob:
558 result = dict(
559 name=blob["name"],
560 tags=blob["metadata"],
561 last_modified=blob["last_modified"].strftime('%d-%b-%Y %H:%M:%S %z'),
562 type=blob["blob_type"],
563 standard_blob_tier=blob.get('blob_tier'),
564 content_length=blob["size"],
565 content_settings=dict(
566 content_type=blob["content_settings"]["content_type"],
567 content_encoding=blob["content_settings"]["content_encoding"],
568 content_language=blob["content_settings"]["content_language"],
569 content_disposition=blob["content_settings"]["content_disposition"],
570 cache_control=blob["content_settings"]["cache_control"],
571 content_md5=blob["content_settings"]["content_md5"].hex() if blob["content_settings"]["content_md5"] else None,
572 )
573 )
574 return result
575
576 def create_container(self):
577 self.log('Create container %s' % self.container)
578
579 tags = None
580 if not self.blob and self.tags:
581 # when a blob is present, then tags are assigned at the blob level
582 tags = self.tags
583
584 if not self.check_mode:
585 try:
586 if self.requires_data_plane_access():
587 client = self.blob_service_client.get_container_client(container=self.container)
588 client.create_container(metadata=tags, public_access=self.public_access)
589 else:
590 blob_container = BlobContainer(
591 public_access=self.public_access,
592 metadata=tags
593 )
594 self.storage_client.blob_containers.create(
595 self.resource_group,
596 self.storage_account_name,
597 self.container,
598 blob_container
599 )
600 except Exception as exc:
601 self.fail("Error creating container {0} - {1}".format(self.container, str(exc)))
602 self.container_obj = self.get_container()
603 self.results['changed'] = True
604 self.results['actions'].append('created container {0}'.format(self.container))
605 self.results['container'] = self.container_obj
606
607 def upload_blob(self):
608 content_settings = None
609 if self.content_type or self.content_encoding or self.content_language or self.content_disposition or \
610 self.cache_control or self.content_md5:
611 content_settings = ContentSettings(
612 content_type=self.content_type,
613 content_encoding=self.content_encoding,
614 content_language=self.content_language,
615 content_disposition=self.content_disposition,
616 cache_control=self.cache_control,
617 content_md5=self.content_md5
618 )
619 if not self.check_mode:
620 try:
621 client = self.blob_service_client.get_blob_client(container=self.container, blob=self.blob)
622 with open(self.src, "rb") as data:
623 if self.blob_type == 'page':
624 client.upload_blob(data=data,
625 blob_type=self.get_blob_type(self.blob_type),
626 metadata=self.tags,
627 content_settings=content_settings,
628 overwrite=self.force)
629 else:
630 client.upload_blob(data=data,
631 blob_type=self.get_blob_type(self.blob_type),
632 metadata=self.tags,
633 content_settings=content_settings,
634 standard_blob_tier=self.get_blob_tier(self.standard_blob_tier),
635 overwrite=self.force)
636 except Exception as exc:
637 self.fail("Error creating blob {0} - {1}".format(self.blob, str(exc)))
638
639 self.blob_obj = self.get_blob()
640 self.results['changed'] = True
641 self.results['actions'].append('created blob {0} from {1}'.format(self.blob, self.src))
642 self.results['container'] = self.container_obj
643 self.results['blob'] = self.blob_obj
644
645 def upload_blob_from_url(self):
646 # Only support block blobs for source_url
647 if self.blob_type != 'block':
648 self.fail("source_url is only supported for block blobs. Set blob_type=block.")
649
650 content_settings = None
651 if self.content_type or self.content_encoding or self.content_language or self.content_disposition or \
652 self.cache_control or self.content_md5:
653 content_settings = ContentSettings(
654 content_type=self.content_type,
655 content_encoding=self.content_encoding,
656 content_language=self.content_language,
657 content_disposition=self.content_disposition,
658 cache_control=self.cache_control,
659 content_md5=self.content_md5
660 )
661 try:
662 client = self.blob_service_client.get_blob_client(container=self.container, blob=self.blob)
663 # If the blob exists and force is false, skip copy
664 if self.blob_obj and not self.force:
665 self.log(f"Destination blob {self.blob} already exists. Skipping copy. Use force=true to overwrite.")
666 self.results['changed'] = False
667 return
668 if not self.check_mode:
669 kwargs = {
670 "source_url": self.source_url,
671 "metadata": self.tags,
672 "standard_blob_tier": self.get_blob_tier(self.standard_blob_tier),
673 }
674
675 # Start async copy
676 client.start_copy_from_url(**kwargs)
677
678 while True:
679 props = client.get_blob_properties()
680 # SDK: BlobProperties has `copy` attribute; handle dict-like fallback defensively
681 copy_props = getattr(props, 'copy', None)
682 status = getattr(copy_props, 'status', None) if copy_props else None
683
684 if status in ('success', 'completed'):
685 break
686 if status in ('failed', 'aborted'):
687 desc = getattr(copy_props, 'status_description', '') if copy_props else ''
688 self.fail(f"Server-side copy failed/aborted (status={status}). {desc}")
689
690 time.sleep(5)
691
692 # Copy is complete; apply headers if requested
693 if content_settings:
694 client.set_http_headers(content_settings=content_settings)
695
696 self.blob_obj = self.get_blob()
697 self.results['changed'] = True
698 self.results['actions'].append(f'started copy of blob {self.blob} from {self.source_url}')
699 self.results['container'] = self.container_obj
700 self.results['blob'] = self.blob_obj
701 except Exception as exc:
702 self.fail(f"Error copying blob from url {self.source_url} - {str(exc)}")
703
704 def download_blob(self):
705 if not self.check_mode:
706 try:
707 client = self.blob_service_client.get_blob_client(container=self.container, blob=self.blob)
708 with open(self.dest, "wb") as blob_stream:
709 blob_data = client.download_blob()
710 blob_data.readinto(blob_stream)
711 except Exception as exc:
712 self.fail("Failed to download blob {0}:{1} to {2} - {3}".format(self.container,
713 self.blob,
714 self.dest,
715 exc))
716 self.results['changed'] = True
717 self.results['actions'].append('downloaded blob {0}:{1} to {2}'.format(self.container,
718 self.blob,
719 self.dest))
720
721 self.results['container'] = self.container_obj
722 self.results['blob'] = self.blob_obj
723
724 def src_is_valid(self):
725 if not os.path.isfile(self.src):
726 self.fail("The source path must be a file.")
727 if os.access(self.src, os.R_OK):
728 return True
729 self.fail("Failed to access {0}. Make sure the file exists and that you have "
730 "read access.".format(self.src))
731
732 def dest_is_valid(self):
733 if not self.check_mode:
734 if not os.path.basename(self.dest):
735 # dest is a directory
736 if os.path.isdir(self.dest):
737 self.log("Path is dir. Appending blob name.")
738 self.dest += self.blob
739 else:
740 try:
741 self.log('Attempting to makedirs {0}'.format(self.dest))
742 os.makedirs(self.dest)
743 except IOError as exc:
744 self.fail("Failed to create directory {0} - {1}".format(self.dest, str(exc)))
745 self.dest += self.blob
746 else:
747 # does path exist without basename
748 file_name = os.path.basename(self.dest)
749 path = self.dest.replace(file_name, '')
750 self.log('Checking path {0}'.format(path))
751 if not os.path.isdir(path):
752 try:
753 self.log('Attempting to makedirs {0}'.format(path))
754 os.makedirs(path)
755 except IOError as exc:
756 self.fail("Failed to create directory {0} - {1}".format(path, str(exc)))
757 self.log('Checking final path {0}'.format(self.dest))
758 if os.path.isfile(self.dest) and not self.force:
759 # dest already exists and we're not forcing
760 self.log("Dest {0} already exists. Cannot download. Use the force option.".format(self.dest))
761 return False
762 return True
763
764 def delete_container(self):
765 if not self.check_mode:
766 try:
767 if self.requires_data_plane_access():
768 self.blob_service_client.get_container_client(container=self.container).delete_container()
769 else:
770 self.storage_client.blob_containers.delete(
771 self.resource_group,
772 self.storage_account_name,
773 self.container
774 )
775 except Exception as exc:
776 self.fail("Error deleting container {0} - {1}".format(self.container, str(exc)))
777
778 self.results['changed'] = True
779 self.results['actions'].append('deleted container {0}'.format(self.container))
780
781 def container_has_blobs(self):
782 try:
783 blobs = self.blob_service_client.get_container_client(container=self.container).list_blobs()
784 except Exception as exc:
785 self.fail("Error list blobs in {0} - {1}".format(self.container, str(exc)))
786 if len(list(blobs)) > 0:
787 return True
788 return False
789
790 def delete_blob(self):
791 if not self.check_mode:
792 try:
793 self.blob_service_client.get_container_client(container=self.container).delete_blob(blob=self.blob)
794 except Exception as exc:
795 self.fail("Error deleting blob {0}:{1} - {2}".format(self.container, self.blob, str(exc)))
796
797 self.results['changed'] = True
798 self.results['actions'].append('deleted blob {0}:{1}'.format(self.container, self.blob))
799 self.results['container'] = self.container_obj
800
801 def update_container_tags(self, tags):
802 if not self.check_mode:
803 try:
804 if self.requires_data_plane_access():
805 self.blob_service_client.get_container_client(container=self.container).set_container_metadata(metadata=tags)
806 else:
807 blob_container = BlobContainer(metadata=tags)
808 self.storage_client.blob_containers.update(
809 self.resource_group,
810 self.storage_account_name,
811 self.container,
812 blob_container
813 )
814 except Exception as exc:
815 self.fail("Error updating container tags {0} - {1}".format(self.container, str(exc)))
816 self.container_obj = self.get_container()
817 self.results['changed'] = True
818 self.results['actions'].append("updated container {0} tags.".format(self.container))
819 self.results['container'] = self.container_obj
820
821 def update_blob_tags(self, tags):
822 if not self.check_mode:
823 try:
824 self.blob_service_client.get_blob_client(container=self.container, blob=self.blob).set_blob_metadata(metadata=tags)
825 except Exception as exc:
826 self.fail("Update blob tags {0}:{1} - {2}".format(self.container, self.blob, str(exc)))
827 self.blob_obj = self.get_blob()
828 self.results['changed'] = True
829 self.results['actions'].append("updated blob {0}:{1} tags.".format(self.container, self.blob))
830 self.results['container'] = self.container_obj
831 self.results['blob'] = self.blob_obj
832
833 def update_blob_tier(self):
834 client = self.blob_service_client.get_blob_client(container=self.container, blob=self.blob)
835 client.set_standard_blob_tier(standard_blob_tier=self.standard_blob_tier)
836 self.results['changed'] = True
837
838 def blob_content_settings_differ(self):
839 if self.content_type or self.content_encoding or self.content_language or self.content_disposition or \
840 self.cache_control or self.content_md5:
841 settings = dict(
842 content_type=self.content_type,
843 content_encoding=self.content_encoding,
844 content_language=self.content_language,
845 content_disposition=self.content_disposition,
846 cache_control=self.cache_control,
847 content_md5=self.content_md5
848 )
849 if self.blob_obj['content_settings'] != settings:
850 return True
851
852 return False
853
854 def update_blob_content_settings(self):
855 content_settings = ContentSettings(
856 content_type=self.content_type,
857 content_encoding=self.content_encoding,
858 content_language=self.content_language,
859 content_disposition=self.content_disposition,
860 cache_control=self.cache_control,
861 content_md5=self.content_md5
862 )
863 if not self.check_mode:
864 try:
865 self.blob_service_client.get_blob_client(container=self.container, blob=self.blob).set_http_headers(content_settings=content_settings)
866 except Exception as exc:
867 self.fail("Update blob content settings {0}:{1} - {2}".format(self.container, self.blob, str(exc)))
868
869 self.blob_obj = self.get_blob()
870 self.results['changed'] = True
871 self.results['actions'].append("updated blob {0}:{1} content settings.".format(self.container, self.blob))
872 self.results['container'] = self.container_obj
873 self.results['blob'] = self.blob_obj
874
875 def requires_data_plane_access(self):
876 """Determine if operation requires data plane access."""
877 return any([
878 self.blob,
879 self.src,
880 self.dest,
881 self.batch_upload_src,
882 self.source_url,
883 ])
884
885
886 def main():
887 AzureRMStorageBlob()
888
889
890 if __name__ == '__main__':
891 main()