この例では、Python スクリプトで Azure SDK 管理ライブラリを使用してリソース グループを作成する方法を示します。 ( 同等の Azure CLI コマンド については、この記事の後半で説明します。Azure portal を使用する場合は、「 リソース グループの作成」を参照してください)。
この記事のすべてのコマンドは、特に明記されていない限り、Linux/macOS bash と Windows コマンド シェルで同じように動作します。
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-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)
4: リソース グループを作成するコードを記述する
この手順では、次のコードを使用 して、provision_blob.py という名前の Python ファイルを作成します。 この Python スクリプトでは、Azure SDK for Python 管理ライブラリを使用して、Azure サブスクリプションにリソース グループを作成します。
次のコードを使用 して、provision_rg.py という名前の Python ファイルを作成します。 コメントでは、詳細について説明します。
# Import the needed credential and management objects from the libraries.
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
# Acquire a credential object using DevaultAzureCredential.
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"]
# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)
# 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}")
# Within the ResourceManagementClient is an object named resource_groups,
# which is of class ResourceGroupsOperations, which contains methods like
# create_or_update.
#
# The second parameter to create_or_update here is technically a ResourceGroup
# object. You can create the object directly using ResourceGroup(___location=
# LOCATION) or you can express the object as inline JSON as shown here. For
# details, see Inline JSON pattern for object arguments at
# https://learn.microsoft.com/azure/developer/python/sdk
# /azure-sdk-library-usage-patterns#inline-json-pattern-for-object-arguments
print(
f"Provisioned resource group {rg_result.name} in the {rg_result.___location} region"
)
# The return value is another ResourceGroup object with all the details of the
# new group. In this case the call is synchronous: the resource group has been
# provisioned by the time the call returns.
# To update the resource group, repeat the call with different properties, such
# as tags:
rg_result = resource_client.resource_groups.create_or_update(
RESOURCE_GROUP_NAME,
{
"___location": LOCATION,
"tags": {"environment": "test", "department": "tech"},
},
)
print(f"Updated resource group {rg_result.name} with tags")
# Optional lines to delete the resource group. begin_delete is asynchronous.
# poller = resource_client.resource_groups.begin_delete(rg_result.name)
# result = poller.result()
コード内の認証
この記事の後半では、Azure CLI を使用して Azure にサインインしてサンプル コードを実行します。 アカウントに、Azure サブスクリプションでリソース グループとストレージ リソースを作成するための十分なアクセス許可がある場合、スクリプトは追加の構成なしで正常に実行されます。
運用環境でこのコードを使用するには、環境変数を設定してサービス プリンシパルを使用して認証します。 この方法により、対話型ログインに依存することなく、セキュリティで保護された自動アクセスが可能になります。 詳細なガイダンスについては、 Azure サービスで Python アプリを認証する方法に関するページを参照してください。
リソース グループとストレージ アカウントを作成するための十分なアクセス許可を持つロールがサービス プリンシパルに割り当てられていることを確認します。 たとえば、サブスクリプション レベルで共同作成者ロールを割り当てると、必要なアクセス権が提供されます。 ロールの割り当ての詳細については、 Azure でのロールベースのアクセス制御 (RBAC) に関するページを参照してください。
コードで使用されるクラスの参照リンク
5: スクリプトを実行する
まだサインインしていない場合は、Azure CLI を使用して Azure にサインインします。
az login
次のスクリプトを実行します。
python provision_rg.py
6: リソース グループを確認する
リソース グループが存在することを確認するには、Azure portal または Azure CLI を使用します。
Azure portal: Azure portal を開き、[ リソース グループ] を選択して、グループが一覧表示されていることを確認します。 必要に応じて、[ 更新 ] コマンドを使用して一覧を更新します。
Azure CLI: az group show コマンドを使用します。
#!/bin/bash az group show -n $AZURE_RESOURCE_GROUP_NAME
7: リソースをクリーンアップする
この例で作成したリソース グループを保持する必要がない場合は、 az group delete コマンドを実行します。 リソース グループではサブスクリプションに継続的な料金は発生しませんが、リソース グループ内のリソースには引き続き料金が発生する可能性があります。 アクティブに使用していないグループをクリーンアップすることをお勧めします。
--no-wait
引数を使用すると、操作の完了を待たずにコマンドをすぐに返すことができます。
#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait
ResourceManagementClient.resource_groups.begin_delete
メソッドを使用して、コードからリソース グループを削除することもできます。 この記事のスクリプトの下部にあるコメント付きコードは、使用方法を示しています。
リファレンス: 同等の Azure CLI コマンド
次の Azure CLI az group create コマンドは、Python スクリプトと同じようにタグを持つリソース グループを作成します。
az group create -n PythonAzureExample-rg -l centralus --tags "department=tech" "environment=test"