共用方式為


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

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

布建這些資源之後,請參閱 範例:使用 Azure 記憶體 來瞭解如何使用 Python 中的 Azure 用戶端連結庫,將檔案上傳至 Blob 容器。

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

1:設定本機開發環境

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

  • 使用 venv 或您選擇的工具設定 Python 虛擬環境。 若要開始使用虛擬環境,請務必加以啟用。 若要安裝 Python,請參閱 安裝 Python

    #!/bin/bash
    # Create a virtual environment
    python -m venv .venv
    # Activate the virtual environment
    source .venv/Scripts/activate # only required for Windows (Git Bash)
    
  • 使用 conda 環境。 若要安裝 Conda,請參閱 安裝 Miniconda

  • Visual Studio CodeGitHub Codespaces中使用 開發容器

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

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

    azure-mgmt-resource
    azure-mgmt-storage
    azure-identity
    
  2. 在已啟用虛擬環境的控制台中,安裝需求:

    pip install -r requirements.txt
    

3.設定環境變數

在此步驟中,您會設定環境變數以用於本文中的程序代碼。 程序代碼會使用os.environ方法來擷取值。

#!/bin/bash
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export LOCATION=<Location> # Change to your preferred region
export AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)
export STORAGE_ACCOUNT_NAME=<StorageAccountName> # Change to your preferred storage account name
export CONTAINER_NAME=<ContainerName> # Change to your preferred container name

4:撰寫程式代碼以建立記憶體帳戶和 Blob 容器

在此步驟中,您會使用下列程式代碼建立名為 provision_blob.py 的 Python 檔案。 此 Python 腳本會使用適用於 Python 的 Azure SDK 管理連結庫,使用適用於 Python 的 Azure SDK 來建立資源群組、Azure 儲存器帳戶和 Blob 容器。

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
from 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 variables
RESOURCE_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 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 = 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}")

程式代碼中的驗證

本文稍後會使用 Azure CLI 登入 Azure,以執行範例程序代碼。 如果您的帳戶有足夠的許可權可建立 Azure 訂用帳戶中的資源群組和記憶體資源,腳本應該會順利執行,而不需要額外的設定。

若要在生產環境中使用此程式碼,請藉由設定環境變數,使用服務主體進行驗證。 此方法可啟用安全、自動化的存取,而不需要依賴互動式登入。 如需詳細指引,請參閱 如何使用 Azure 服務驗證 Python 應用程式

請確定服務主體已獲指派具有足夠許可權的角色,以建立資源群組和記憶體帳戶。 例如,在訂用帳戶層級指派參與者角色可提供必要的存取權。 若要深入瞭解角色指派,請參閱 Azure 中的角色型訪問控制 (RBAC)。

5.執行腳本

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

    az login
    

  2. 執行指令碼:

    python provision_blob.py
    

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

6:驗證資源

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

    新資源群組的 Azure 入口網站頁面,其中顯示記憶體帳戶

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

    Azure 入口網站頁面顯示儲存帳戶的 Blob 容器

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

如需使用 Azure 記憶體管理連結庫的另一個範例,請參閱 管理 Python 記憶體範例

7:清除資源

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

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

#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait

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

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

#!/bin/bash
#!/bin/bash

# Set variables
export LOCATION=<Location> # Change to your preferred region
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export STORAGE_ACCOUNT_NAME=<StorageAccountName> # Change to your preferred storage account name
export CONTAINER_NAME=<ContainerName> # Change to your preferred container name

# Provision the resource group
echo "Creating resource group: $AZURE_RESOURCE_GROUP_NAME"
az group create \
    --location "$LOCATION" \
    --name "$AZURE_RESOURCE_GROUP_NAME"

# Provision the storage account
az storage account create -g $AZURE_RESOURCE_GROUP_NAME -l $LOCATION -n $STORAGE ACCOUNT_NAME --kind StorageV2 --sku Standard_LRS

echo Storage account name is $STORAGE_ACCOUNT_NAME

# Retrieve the connection string
CONNECTION_STRING=$(az storage account show-connection-string -g $AZURE_RESOURCE_GROUP_NAME -n $STORAGE_ACCOUNT_NAME --query connectionString)

# Provision the blob container
az storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --connection-string $CONNECTION_STRING

另請參閱