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

この記事では、Python スクリプトで Azure 管理ライブラリを使用して、Azure Storage アカウントと Blob Storage コンテナを含むリソース グループを作成する方法について説明します。

リソースを作成したら、例: Azure Storage の使用を参照して、Python アプリケーション コードで Azure クライアント ライブラリを使用して Blob Storage コンテナにファイルをアップロードします。

特に記載のない限り、この記事で使用されているコマンドはいずれも、Linux と macOS の bash および Windows のコマンド シェルで同じように動作します。

同等の Azure CLI コマンドは、この記事で一覧されています。 Azure Portal を使用する場合は、「Azure Storage アカウントの作成」と「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 の環境変数からサブスクリプション 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 アプリを認証する方法」を参照してください。 サブスクリプションの Contributor ロールなど、Azure の適切なロールを割り当てて、サブスクリプションでリソース グループやストレージ リソースを作成するための十分なアクセス許可がサービス プリンシパルにあることを確認します。

4. スクリプトを実行します

  1. 実行していない場合、Azure CLI を使用して Azure にサインインします。

    az login
    
  2. AZURE_SUBSCRIPTION_ID 環境変数を、サブスクリプション ID に設定します。 (az account show コマンドを実行すると、出力の id プロパティからお使いのサブスクリプション ID を取得できます。)

    set AZURE_SUBSCRIPTION_ID=00000000-0000-0000-0000-000000000000
    
  3. 次のスクリプトを実行します。

    python provision_blob.py
    

スクリプトが完了するまでに 1 分から 2 分かかります。

5: リソースを確認する

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

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

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

    Azure portal page for the storage account showing the blob container

  3. これらのリソースをアプリケーション コードから使用したい場合は、「例: Azure Storageの使用」を続行します。

Azure Storage の管理ライブラリを使用するその他の例については、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 Storage の使用」の記事に従ってこれらのリソースをアプリ コードで使用する場合は、リソースをそのままにしておいてください。 この例で作成したリソース グループおよびストレージ リソースを維持する必要が無い場合は、az group delete コマンドを実行します。

リソース グループではサブスクリプションに継続的な料金は発生しませんが、リソース グループ内のストレージ アカウントなどのリソースには料金が発生する可能性があります。 アクティブに使用していないグループをクリーン アップすることをお勧めします。 --no-wait 引数を使用すると、操作が完了するまで待機するのではなく、直ちにコマンドから戻ることができます。

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

コードから ResourceManagementClient.resource_groups.begin_delete メソッドを使用してリソース グループを削除することもできます。 「例: リソース グループを作成する」のコードでは、使用方法を示しています。

関連項目