次の方法で共有


例: Python 用 Azure ライブラリを使用して Azure Storage を作成する

この記事では、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 ライブラリ パッケージをインストールする

  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 スクリプトでは、Azure SDK for Python 管理ライブラリを使用して、Azure SDK for Python を使用してリソース グループ、Azure Storage アカウント、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 CLI を使用して Azure にサインインします。

    az login
    

  2. 次のスクリプトを実行します。

    python provision_blob.py
    

    スクリプトの完了には 1 ~ 2 分かかります。

6: リソースを確認する

  1. Azure portal を開き、リソース グループとストレージ アカウントが想定どおりに作成されたことを確認します。 少し待ってから、リソース グループの 非表示の種類を表示 するを選択する必要がある場合もあります。

    ストレージ アカウントが表示されている、新しいリソース グループの Azure portal ページ

  2. ストレージ アカウントを選択し、左側のメニューで [データ ストレージ>Containers ] を選択して、"blob-container-01" が表示されることを確認します。

    BLOB コンテナーが表示されているストレージ アカウントの Azure portal ページ

  3. アプリケーション コードからこれらのリソースを使用する場合は、「 例: 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
#!/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

こちらも参照ください