次の方法で共有


例: Azure ライブラリを使用して Web アプリを作成してデプロイする

この例では、Python スクリプトで Azure SDK 管理ライブラリを使用して、GitHub リポジトリからプルされたアプリ コードを使用して、Web アプリを作成して Azure App Service にデプロイする方法を示します。

Azure SDK for Python には、リソースの構成とデプロイを自動化できる管理ライブラリ ( azure-mgmt 以降の名前空間) が含まれています。これは、Azure portal、Azure CLI、または ARM テンプレートで実行できる操作と同様です。 例については、「 クイック スタート: Python (Django または Flask) Web アプリを Azure App Service にデプロイする」を参照してください。

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-web
azure-identity

ローカル開発環境で、次のコードを使用して要件をインストールします。

pip install -r requirements.txt

3: サンプル リポジトリをフォークする

  1. https://github.com/Azure-Samples/python-docs-hello-worldにアクセスし、リポジトリを独自の GitHub アカウントにフォークします。 フォークを使用すると、アプリを Azure にデプロイするために必要なアクセス許可が確保されます。

    GitHub でのサンプル リポジトリのフォーク

  2. 次に、 REPO_URL という名前の環境変数を作成し、フォークされたリポジトリの URL に設定します。 この変数は、次のセクションのコード例で必要になります。

export REPO_URL=<url_of_your_fork>
export AZURE_SUBSCRIPTION_ID=<subscription_id>

4: Web アプリを作成してデプロイするコードを記述する

provision_deploy_web_app.pyという名前 Python ファイルを作成し、次のコードを追加します。 インライン コメントでは、スクリプトの各部分が何を行うかを説明します。 REPO_URL環境変数とAZURE_SUBSCRIPTION_ID環境変数は、前の手順で既に設定されている必要があります。

import random, os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.web import WebSiteManagementClient

# Acquire a credential object using CLI-based authentication.
credential = AzureCliCredential()

# Retrieve subscription ID from environment variable
subscription_id = os.environ["AZURE_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-WebApp-rg'
LOCATION = "centralus"

# 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 App Service plan, which defines the underlying VM for the web app.

# Names for the App Service plan and App Service. We use a random number with the
# latter to create a reasonably unique name. If you've already provisioned a
# web app and need to re-run the script, set the WEB_APP_NAME environment 
# variable to that name instead.
SERVICE_PLAN_NAME = 'PythonAzureExample-WebApp-plan'
WEB_APP_NAME = os.environ.get("WEB_APP_NAME", f"PythonAzureExample-WebApp-{random.randint(1,100000):05}")

# Obtain the client object
app_service_client = WebSiteManagementClient(credential, subscription_id)

# Provision the plan; Linux is the default
poller = app_service_client.app_service_plans.begin_create_or_update(RESOURCE_GROUP_NAME,
    SERVICE_PLAN_NAME,
    {
        "___location": LOCATION,
        "reserved": True,
        "sku" : {"name" : "B1"}
    }
)

plan_result = poller.result()

print(f"Provisioned App Service plan {plan_result.name}")


# Step 3: With the plan in place, provision the web app itself, which is the process that can host
# whatever code we want to deploy to it.

poller = app_service_client.web_apps.begin_create_or_update(RESOURCE_GROUP_NAME,
    WEB_APP_NAME,
    {
        "___location": LOCATION,
        "server_farm_id": plan_result.id,
        "site_config": {
            "linux_fx_version": "python|3.8"
        }
    }
)

web_app_result = poller.result()

print(f"Provisioned web app {web_app_result.name} at {web_app_result.default_host_name}")

# Step 4: deploy code from a GitHub repository. For Python code, App Service on Linux runs
# the code inside a container that makes certain assumptions about the structure of the code.
# For more information, see How to configure Python apps,
# https://docs.microsoft.com/azure/app-service/containers/how-to-configure-python.
#
# The create_or_update_source_control method doesn't provision a web app. It only sets the
# source control configuration for the app. In this case we're simply pointing to
# a GitHub repository.
#
# You can call this method again to change the repo.

REPO_URL = os.environ["REPO_URL"]

poller = app_service_client.web_apps.begin_create_or_update_source_control(RESOURCE_GROUP_NAME,
    WEB_APP_NAME, 
    { 
        "___location": "GitHub",
        "repo_url": REPO_URL,
        "branch": "master",
        "is_manual_integration": True
    }
)

sc_result = poller.result()

print(f"Set source control on web app to {sc_result.branch} branch of {sc_result.repo_url}")

# Step 5: Deploy the code using the repository and branch configured in the previous step.
#
# If you push subsequent code changes to the repo and branch, you must call this method again
# or use another Azure tool like the Azure CLI or Azure portal to redeploy. 
# Note: By default, the method returns None.

app_service_client.web_apps.sync_repository(RESOURCE_GROUP_NAME, WEB_APP_NAME)

print(f"Deploy code")

このコードでは、( AzureCliCredential を使用して) CLI ベースの認証を使用します。これは、Azure CLI で直接実行できるアクションを示しているためです。 どちらの場合も、認証に同じ ID を使用しています。 環境によっては、認証の前にまず az login を実行することが必要になる場合があります。

運用スクリプトでこのようなコードを使用するには (たとえば、VM 管理を自動化するために)、「Azure サービスで DefaultAzureCredential」の説明に従って、サービス プリンシパル ベースの方法で (推奨) を使用します。

5: スクリプトを実行する

python provision_deploy_web_app.py

6: Web アプリのデプロイを確認する

デプロイされた Web サイトを表示するには、次のコマンドを実行します。

az webapp browse --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg

Web アプリ名 (--name) をスクリプトによって生成された値に置き換えます。 スクリプトで変更しない限り、リソース グループ名 (--resource-group) を変更する必要はありません。 サイトを開くと、"Hello, World!" と表示されます。 ブラウザーの中です。

ヒント

予想される出力が表示されない場合は、数分待ってからやり直してください。

期待される出力が表示されない場合は、次の手順を実行します。

  1. Azure ポータルにアクセスします。
  2. [リソース グループ] に移動し、作成したリソース グループを見つけます。
  3. リソース グループを選択して、そのリソースを表示します。 これには、App Service プランと App Service の両方を含めるようにしてください。
  4. App Service を選択し、デプロイ センターに移動します。
  5. [ ログ ] タブを開き、デプロイ ログでエラーや状態の更新を確認します。

7: Web アプリ コードを再デプロイする (省略可能)

このスクリプトは、Web アプリをホストするために必要なすべてのリソースをプロビジョニングし、手動統合を使用してフォークされたリポジトリを使用するようにデプロイ ソースを構成します。 手動統合では、Web アプリを手動でトリガーして、指定したリポジトリとブランチから更新をプルする必要があります。

このスクリプトでは 、WebSiteManagementClient.web_apps.sync_repository メソッドを使用して、Web アプリをトリガーしてリポジトリからコードをプルします。 コードをさらに変更する場合は、この API をもう一度呼び出すか、Azure CLI や Azure portal などの他の Azure ツールを使用して再デプロイできます。

az webapp deployment source sync コマンドを実行して、Azure CLI を使用してコードを再デプロイできます。

az webapp deployment source sync --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg

スクリプトで変更しない限り、リソース グループ名 (--resource-group) を変更する必要はありません。

Azure portal からコードをデプロイするには:

  1. Azure ポータルにアクセスします。
  2. [リソース グループ] に移動し、作成したリソース グループを見つけます。
  3. リソース グループ名を選択して、そのリソースを表示します。 これには、App Service プランと App Service の両方を含めるようにしてください。
  4. App Service を選択し、デプロイ センターに移動します。
  5. 上部のメニューで [ 同期 ] を選択して、コードのデプロイをトリガーします。

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

az group delete --name PythonAzureExample-WebApp-rg --no-wait

スクリプトで変更しない限り、リソース グループ名 (--resource-group オプション) を変更する必要はありません。

この例で作成したリソース グループが不要になった場合は、 az group delete コマンドを実行して削除できます。 リソース グループには継続的な料金は発生しませんが、未使用のリソースをクリーンアップすることをお勧めします。 --no-wait引数を使用して、削除が完了するのを待たずにコマンド ラインに制御を直ちに戻します。

ResourceManagementClient.resource_groups.begin_delete メソッドを使用してプログラムでリソース グループを削除することもできます。

こちらも参照ください