Share via


例: Azure ライブラリを使用してリソース グループを作成する

この例では、Python スクリプトで Azure SDK の管理ライブラリを使用してリソース グループを作成する方法について説明します。 (同等の Azure CLI コマンドについては、この記事の後半で説明します。Azure portal を使用する場合は、「リソース グループの作成」を参照してください)。

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

1: ローカルの開発環境を設定する

まだ行っていない場合は、このコードを実行できる環境を設定します。 次のことをお試しください。

2: Azure ライブラリ パッケージをインストールする

requirements.txt という名前のファイルを作成し、内容を次のようにします。

azure-mgmt-resource
azure-identity

仮想環境をアクティブ化し、ターミナルまたはコマンド プロンプトで要件をインストールします。

pip install -r requirements.txt

3: リソース グループを作成するコードを記述する

次のコードを使用して、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"]

# 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(
    "PythonAzureExample-rg", {"location": "centralus"}
)

# 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(
    "PythonAzureExample-rg",
    {
        "location": "centralus",
        "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 アプリを認証する方法」を参照してください。 サブスクリプションの 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_rg.py
    

5: リソース グループを確認する

グループが存在することは、Azure portal または Azure CLI から確認できます。

  • Azure portal: Azure portal を開いて [リソース グループ] を選択し、対象のグループが一覧に表示されていることを確認します。 既にポータルが開いている場合は、[最新の情報に更新] コマンドを使用してリストを最新の情報に更新します。

  • Azure CLI: az group show コマンドを使用します。

    az group show -n PythonAzureExample-rg
    

6: リソースをクリーンアップする

この例で作成した リソース グループを保持する必要がない場合には、az group delete コマンドを実行します。 リソース グループではサブスクリプションに継続的な料金は発生しませんが、リソース グループ内のリソースには引き続き料金が発生する可能性があります。 アクティブに使用していないグループをクリーン アップすることをお勧めします。 --no-wait 引数を使用すると、操作が完了するまで待機するのではなく、直ちにコマンドから戻ることができます。

az group delete -n PythonAzureExample-rg  --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"

関連項目