この記事では、Python 用 Azure 管理ライブラリを使用して、Azure Storage アカウントと BLOB ストレージ コンテナーと共にリソース グループを作成する方法について説明します。
これらのリソースをプロビジョニングした後、「 例: Azure Storage を使用 して、Python で Azure クライアント ライブラリを使用して BLOB コンテナーにファイルをアップロードする方法」セクションを参照してください。
Bash と PowerShell に 対応する Azure CLI コマンド については、この記事の後半で説明します。 Azure portal を使用する場合は、「 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 Code または GitHub Codespaces で開発コンテナーを使用します。
2: 必要な Azure ライブラリ パッケージをインストールする
コンソールで、次の例で使用する管理ライブラリを一覧表示する requirements.txt ファイルを作成します。
azure-mgmt-resource azure-mgmt-storage azure-identity仮想環境がアクティブ化された本体に、次の要件をインストールします。
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を使用して、リソース グループ、Azure Storage アカウント、BLOB コンテナーを作成します。
import os
# Import the needed credential and management objects from the 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: Create a resource group:
# https://learn.microsoft.com/azure/developer/python/sdk/examples/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, "type": "Microsoft.Storage/storageAccounts" }
)
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("Retrieved the primary key for the storage account")
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) に関するページを参照してください。
コードで使用されるクラスの参照リンク
- DefaultAzureCredential (azure.identity)
- ResourceManagementClient (azure.mgmt.resource)
- StorageManagementClient (azure.mgmt.storage)
5. スクリプトを実行する
まだサインインしていない場合は、Azure CLIを使用してAzureにサインインします。
az login
次のスクリプトを実行します。
python provision_blob.pyスクリプトの完了には 1 ~ 2 分かかります。
6: リソースを確認する
Azure portal を開き、リソース グループとストレージ アカウントが想定どおりに作成されたことを確認します。 1 分間待ってから、リソース グループ ビューを更新することが必要になる場合があります。
ストレージ アカウントを選択し、左側のメニューで [データ ストレージ>Containers ] を選択して、作成したコンテナーが表示されることを確認します。
アプリケーション コードからこれらのリソースを使用する場合は、「 例: Azure Storage を使用する」に進みます。
Azure Storage 管理ライブラリを使用する別の例については、「 Python Storage の管理」サンプルを参照してください。
7: リソースをクリーンアップする
これらのリソースをアプリ コードで使用する場合は、例: Azure Storage を使用する の記事の手順に従ってください。 それ以外の場合は、この例で作成したリソース グループとストレージ リソースを保持する必要がない場合は、 az group delete コマンドを実行します。
リソース グループではサブスクリプションに継続的な料金は発生しませんが、リソース グループ内のストレージ アカウントなどのリソースには料金が発生する可能性があります。 アクティブに使用していないリソース グループをクリーンアップすることをお勧めします。
--no-wait引数を使用すると、操作の完了を待たずにコマンドをすぐに返すことができます。
#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait
リファレンス: 同等の Azure CLI コマンド
次の Azure CLI コマンドは、Python スクリプトと同じ作成手順を実行します。
#!/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 \
--resource-group "$AZURE_RESOURCE_GROUP_NAME" \
--location "$LOCATION" \
--name "$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 \
--resource-group "$AZURE_RESOURCE_GROUP_NAME" \
--name "$STORAGE_ACCOUNT_NAME" \
--query connectionString \
--output tsv)
# Provision the blob container
az storage container create \
--name "$CONTAINER_NAME" \
--account-name "$STORAGE_ACCOUNT_NAME" \
--connection-string "$CONNECTION_STRING"