範例:使用適用於 Python 的 Azure 連結庫建立 Azure 儲存體

在本文中,您將瞭解如何使用 Python 腳本中的 Azure 管理連結庫來建立包含 Azure 儲存體 帳戶和 Blob 記憶體容器的資源群組。

建立資源之後,請參閱範例:使用 Azure 儲存體 在 Python 應用程式程式代碼中使用 Azure 用戶端連結庫,將檔案上傳至 Blob 記憶體容器。

本文中的所有命令在Linux/macOS bash和 Windows 命令殼層中都相同,除非另有說明。

本文稍後會列出對等的 Azure CLI 命令。 如果您想要使用 Azure 入口網站,請參閱建立 Azure 記憶體帳戶建立 Blob 容器

1:設定本機開發環境

如果您尚未設定,請設定可在其中執行程式碼的環境。 以下列出一些選項:

2:安裝所需的 Azure 連結庫套件

  1. 建立requirements.txt檔案,其中列出此範例中使用的管理連結庫:

    azure-mgmt-resource
    azure-mgmt-storage
    azure-identity
    
  2. 在啟用虛擬環境的終端機中,安裝需求:

    pip install -r requirements.txt
    

3:撰寫程式代碼以建立記憶體資源

使用下列程式代碼建立名為 provision_blob.py 的 Python 檔案。 批註會說明詳細數據。 腳本會從環境變數 讀取您的訂用帳戶標識碼 AZURE_SUBSCRIPTION_ID。 您會在稍後的步驟中設定此變數。 資源組名、位置、記憶體帳戶名稱和容器名稱全都定義為程序代碼中的常數。

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 DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.storage import StorageManagementClient

# Acquire a credential object.
credential = DefaultAzureCredential()

# Retrieve subscription ID from environment variable.
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)

# Constants we need in multiple places: the resource group name and the region
# in which we provision resources. You can change these values however you want.
RESOURCE_GROUP_NAME = "PythonAzureExample-Storage-rg"
LOCATION = "centralus"

# Step 1: Provision the resource group.

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 = f"pythonazurestorage{random.randint(1,100000):05}"

# You can replace the storage account here with any unique name. A random number is used
# by default, but note that the name changes every time you run this script.
# The name must be 3-24 lower case letters and numbers only.


# 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 account
poller = 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 = "blob-container-01"
container = storage_client.blob_containers.create(RESOURCE_GROUP_NAME, STORAGE_ACCOUNT_NAME, CONTAINER_NAME, {})

# The fourth argument is a required BlobContainer object, but because we don't need any
# special values there, so we just pass empty JSON.

print(f"Provisioned blob container {container.name}")

程式代碼中的驗證

本文稍後會使用 Azure CLI 登入 Azure,以執行範例程序代碼。 如果您的帳戶具有在 Azure 訂用帳戶中建立資源群組和記憶體資源的許可權,程式代碼將會順利執行。

若要在生產腳本中使用這類程序代碼,您可以將環境變數設定為使用服務主體型方法進行驗證。 若要深入瞭解,請參閱 如何使用 Azure 服務驗證 Python 應用程式。 您必須在 Azure 中指派適當的角色,以確保服務主體有足夠的許可權在訂用帳戶中建立資源群組和記憶體資源;例如,訂用帳戶上的參與者角色。

4.執行腳本

  1. 如果您尚未登入 Azure,請使用 Azure CLI 登入 Azure:

    az login
    
  2. AZURE_SUBSCRIPTION_ID 環境變數設定為訂用帳戶標識碼。 (您可以執行 az account show 命令,並從輸出中的 屬性取得訂用帳戶識別碼 id

    set AZURE_SUBSCRIPTION_ID=00000000-0000-0000-0000-000000000000
    
  3. 執行指令碼:

    python provision_blob.py
    

腳本需要一兩分鐘才能完成。

5:驗證資源

  1. 開啟 Azure 入口網站,以確認資源群組和記憶體帳戶已如預期般建立。 您可能需要等候一分鐘,同時選取 [ 顯示資源群組中的隱藏類型 ]。

    Azure portal page for the new resource group, showing the storage account

  2. 選取記憶體帳戶,然後在左側功能表中選取 [數據記憶體>容器],以確認 “blob-container-01” 出現:

    Azure portal page for the storage account showing the blob container

  3. 如果您想要嘗試從應用程式程式代碼使用這些資源,請繼續進行範例:使用 Azure 儲存體

如需使用 Azure 儲存體 管理連結庫的其他範例,請參閱管理 Python 儲存體 範例

如需參考:對等的 Azure CLI 命令

下列 Azure CLI 命令會完成與 Python 腳本相同的建立步驟:

rem Provision the resource group

az group create ^
-n PythonAzureExample-Storage-rg ^
-l centralus

rem Provision the storage account

set account=pythonazurestorage%random%
echo Storage account name is %account%

az storage account create ^
-g PythonAzureExample-Storage-rg ^
-l centralus ^
-n %account% ^
--kind StorageV2 ^
--sku Standard_LRS

rem Retrieve the connection string

FOR /F %i IN ('az storage account show-connection-string -g PythonAzureExample-Storage-rg -n %account% --query connectionString') do (SET connstr=%i)

rem Provision the blob container

az storage container create ^
--name blob-container-01 ^
--account-name %account% ^
--connection-string %connstr%

6:清除資源

如果您想要遵循範例:在應用程式程式代碼中使用 Azure 儲存體 使用這些資源一文,請保留資源。 否則,如果您不需要保留在此範例中建立的資源群組和記憶體資源,請執行 az group delete 命令。

資源群組不會在您的訂用帳戶中產生任何持續費用,但資源群組中的資源,例如記憶體帳戶,可能會產生費用。 最好清除您未主動使用的任何群組。 自 --no-wait 變數可讓命令立即傳回,而不是等待作業完成。

az group delete -n PythonAzureExample-Storage-rg  --no-wait

您也可以使用 ResourceManagementClient.resource_groups.begin_delete 方法,從程式代碼中刪除資源群組。 範例:建立資源群組中的程式代碼會示範使用方式。

另請參閱