This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
In this article, you learn how to use the Azure management libraries for Python to create a resource group, along with an Azure Storage account and a Blob storage container.
After provisioning these resources, refer to the sectionExample: Use Azure Storage to see how to use the Azure client libraries in Python to upload a file to the Blob container.
TheEquivalent Azure CLI commands for bash and PowerShell are listed later in this article. If you prefer to use the Azure portal, seeCreate an Azure storage account andCreate a blob container.
If you haven't already, set up an environment where you can run the code. Here are some options:
Configure a Python virtual environment usingvenv
or your tool of choice. To start using the virtual environment, be sure to activate it. To install python, seeInstall Python.
#!/bin/bash# Create a virtual environmentpython -m venv .venv# Activate the virtual environmentsource .venv/Scripts/activate # only required for Windows (Git Bash)
Use aconda environment. To install Conda, seeInstall Miniconda.
Use aDev Container inVisual Studio Code orGitHub Codespaces.
In your console, create arequirements.txt file that lists the management libraries used in this example:
azure-mgmt-resourceazure-mgmt-storageazure-identity
In your console with the virtual environment activated, install the requirements:
pip install -r requirements.txt
In this step, you set environment variables for use in the code in this article. The code uses theos.environ
method to retrieve the values.
#!/bin/bashexport AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group nameexport LOCATION=<Location> # Change to your preferred regionexport AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)export STORAGE_ACCOUNT_NAME=<StorageAccountName> # Change to your preferred storage account nameexport CONTAINER_NAME=<ContainerName> # Change to your preferred container name
In this step, you create a Python file namedprovision_blob.py with the following code. This Python script uses the Azure SDK for Python management libraries to create a resource group, Azure Storage account, and Blob container using the Azure SDK for Python.
import os, random# Import the needed management objects from the libraries. The azure.common library# is installed automatically with the other libraries.from azure.identity import DefaultAzureCredentialfrom azure.mgmt.resource import ResourceManagementClientfrom azure.mgmt.storage import StorageManagementClientfrom azure.mgmt.storage.models import BlobContainer# Acquire a credential object.credential = DefaultAzureCredential()# Retrieve subscription ID from environment variable.subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]# Retrieve resource group name and location from environment variablesRESOURCE_GROUP_NAME = os.environ["AZURE_RESOURCE_GROUP_NAME"]LOCATION = os.environ["LOCATION"]# Step 1: Provision the resource group.resource_client = ResourceManagementClient(credential, subscription_id)rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME, { "location": LOCATION })print(f"Provisioned resource group {rg_result.name}")# For details on the previous code, see Example: Provision a resource group# at https://docs.microsoft.com/azure/developer/python/azure-sdk-example-resource-group# Step 2: Provision the storage account, starting with a management object.storage_client = StorageManagementClient(credential, subscription_id)STORAGE_ACCOUNT_NAME = os.environ["STORAGE_ACCOUNT_NAME"] # Check if the account name is available. Storage account names must be unique across# Azure because they're used in URLs.availability_result = storage_client.storage_accounts.check_name_availability( { "name": STORAGE_ACCOUNT_NAME })if not availability_result.name_available: print(f"Storage name {STORAGE_ACCOUNT_NAME} is already in use. Try another name.") exit()# The name is available, so provision the accountpoller = storage_client.storage_accounts.begin_create(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME, { "location" : LOCATION, "kind": "StorageV2", "sku": {"name": "Standard_LRS"} })# Long-running operations return a poller object; calling poller.result()# waits for completion.account_result = poller.result()print(f"Provisioned storage account {account_result.name}")# Step 3: Retrieve the account's primary access key and generate a connection string.keys = storage_client.storage_accounts.list_keys(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME)print(f"Primary key for storage account: {keys.keys[0].value}")conn_string = f"DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName={STORAGE_ACCOUNT_NAME};AccountKey={keys.keys[0].value}"# print(f"Connection string: {conn_string}")# Step 4: Provision the blob container in the account (this call is synchronous)CONTAINER_NAME = os.environ["CONTAINER_NAME"]container = storage_client.blob_containers.create(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME, CONTAINER_NAME, BlobContainer())print(f"Provisioned blob container {container.name}")
Later in this article, you sign in to Azure using the Azure CLI to execute the sample code. If your account has sufficient permissions to create resource groups and storage resources in your Azure subscription, the script should run successfully without additional configuration.
To use this code in a production environment, authenticate using a service principal by setting environment variables. This approach enables secure, automated access without relying on interactive login. For detailed guidance, seeHow to authenticate Python apps with Azure services.
Ensure that the service principal is assigned a role with sufficient permissions to create resource groups and storage accounts. For example, assigning the Contributor role at the subscription level provides the necessary access. To learn more about role assignments, seeRole-based access control (RBAC) in Azure.
If you haven't already, sign in to Azure using the Azure CLI:
az login
Run the script:
python provision_blob.py
The script takes a minute or two to complete.
Open theAzure portal to verify that the resource group and storage account were created as expected. You may need to wait a minute and also selectShow hidden types in the resource group.
Select the storage account, then selectData storage >Containers in the left-hand menu to verify that the "blob-container-01" appears:
If you want to try using these resources from application code, continue withExample: Use Azure Storage.
For another example of using the Azure Storage management library, see theManage Python Storage sample.
Leave the resources in place if you want to follow the articleExample: Use Azure Storage to use these resources in app code. Otherwise, run theaz group delete command if you don't need to keep the resource group and storage resources created in this example.
Resource groups don't incur any ongoing charges in your subscription, but resources, like storage accounts, in the resource group might incur charges. It's a good practice to clean up any group that you aren't actively using. The--no-wait
argument allows the command to return immediately instead of waiting for the operation to finish.
#!/bin/bashaz group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait
The following Azure CLI commands complete the same creation steps as the Python script:
#!/bin/bash#!/bin/bash# Set variablesexport LOCATION=<Location> # Change to your preferred regionexport AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group nameexport STORAGE_ACCOUNT_NAME=<StorageAccountName> # Change to your preferred storage account nameexport CONTAINER_NAME=<ContainerName> # Change to your preferred container name# Provision the resource groupecho "Creating resource group: $AZURE_RESOURCE_GROUP_NAME"az group create \ --location "$LOCATION" \ --name "$AZURE_RESOURCE_GROUP_NAME"# Provision the storage accountaz storage account create -g $AZURE_RESOURCE_GROUP_NAME -l $LOCATION -n $STORAGE ACCOUNT_NAME --kind StorageV2 --sku Standard_LRSecho Storage account name is $STORAGE_ACCOUNT_NAME# Retrieve the connection stringCONNECTION_STRING=$(az storage account show-connection-string -g $AZURE_RESOURCE_GROUP_NAME -n $STORAGE_ACCOUNT_NAME --query connectionString)# Provision the blob containeraz storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --connection-string $CONNECTION_STRING
Was this page helpful?
Was this page helpful?