An Azure service that stores unstructured data in the cloud as blobs.
Hi Denis Mukhamedov, I'm glad that you were able to resolve your issue and thank you for posting your solution so that others experiencing the same thing can easily reference this!
Since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others ", I'll repost your solution in case you'd like to "Accept" the answer. Accepted answers show up at the top, resulting in improved discoverability for others.
Issue: The initial code deletes all existing access policies for the storage container and creates a new one instead of adding a new policy while retaining the existing ones. The attempted solution encounters an error when trying to add a new policy directly to the existing policies dictionary returned by get_container_access_policy().
Root Cause: The initial code deletes existing access policies before adding a new one, causing the loss of previously configured policies. The attempted solution doesn't handle existing policies correctly when adding a new one, leading to errors in directly modifying the existing policies dictionary.
Solution: Customer provided solution that fixed the issue.
from azure.storage.blob import BlobServiceClient, ContainerSasPermissions, AccessPolicy
import datetime
# Replace with your Azure Storage account details
account_name = 'your_account_name'
account_key = 'your_account_key'
container_name = 'your_container_name'
policy_id = 'your_policy_id' # The ID for the new policy
policy_start = datetime.datetime.utcnow()
policy_expiry = policy_start + datetime.timedelta(hours=1) # Example: 1 hour validity
# Initialize the BlobServiceClient
blob_service_client = BlobServiceClient(account_url=f"https://{account_name}.blob.core.windows.net", credential=account_key)
# Get the container client
container_client = blob_service_client.get_container_client(container_name)
# Define the new access policy
new_access_policy = AccessPolicy(permission=ContainerSasPermissions(read=True, write=True), start=policy_start, expiry=policy_expiry)
# Get the existing access policies
existing_policies = container_client.get_container_access_policy()['signed_identifiers']
# Convert the list of existing policies to a dictionary
existing_policies_dict = {policy.id: policy.access_policy for policy in existing_policies}
# Update the existing policies with the new one
existing_policies_dict[policy_id] = new_access_policy
# Set the updated policies back to the container
container_client.set_container_access_policy(signed_identifiers=existing_policies_dict)