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

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

管理ライブラリ (azure-mgmt で始まる名前空間、たとえば azure-mgmt-web) を使用すると、Azure portal、Azure CLI、またはその他のリソース管理ツールから実行できるものと同じタスクを実行する構成およびデプロイ プログラムを記述できます。 たとえば、「クイックスタート: Python (Django または Flask) Web アプリを Azure App Service にデプロイする」を参照します。 (同等の Azure CLI コマンドについては、この記事の後半で説明します。)

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

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

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

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

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

azure-mgmt-resource
azure-mgmt-web
azure-identity

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

pip install -r requirements.txt

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

https://github.com/Azure-Samples/python-docs-hello-world にアクセスし、ご自身の GitHub アカウントにリポジトリをフォークします。 フォークを使用して、リポジトリを Azure にデプロイするためのアクセス権限があることを確認します。

Forking the sample repository on GitHub

次に、フォークの URL を使用して、REPO_URL という名前の環境変数を作成します。 次のセクションのコード例は、この環境変数に依存しています。

set REPO_URL=<url_of_your_fork>
set 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")

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

VM の管理を自動化するなど、このようなコードを本番スクリプトで使用する場合は、「Azure サービスで Python アプリを認証する方法」で説明されている方法に従ってサービス プリンシパルで 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

Web アプリ名 (--name オプション) とリソース グループ名 (--resource-group オプション) を、スクリプトで使用した値に置き換えます。

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

  1. Azure ポータルにアクセスします。
  2. [リソース グループ] を選択し、作成したリソース グループを見つけます。
  3. リソース グループ名を選択して、リソースグループに含まれるリソースを表示します。 具体的には、App Service プランと App Service があることを確認します。
  4. App Service を選択し、[デプロイ センター] を選択します。
  5. トップ メニューで [同期] を選択してコードをデプロイします。

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

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

この例で作成した リソース グループを保持する必要がない場合には、az group delete コマンドを実行します。 リソース グループの料金がサブスクリプションに課金され続けることはありませんが、実際に使用していないグループは普段からクリーンアップするようにしておきましょう。 --no-wait 引数を使用すると、操作が完了するまで待機するのではなく、直ちにコマンドから戻ることができます。

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

参考: 同等の Azure CLI コマンド

次の Azure CLI コマンドは、Python スクリプトと同じプロビジョニング手順を実行するものです。

rem Replace <your_github_user_name> with the account name of the fork.

set repoUrl=https://github.com/<your_github_user_name>/python-docs-hello-world
set appName=PythonAzureExample-WebApp-%random%

az group create -l centralus -n PythonAzureExample-WebApp-rg

az appservice plan create -n PythonAzureExample-WebApp-plan -g PythonAzureExample-WebApp-rg ^
     --is-linux --sku F1

echo Creating app: %appName%

az webapp create -g PythonAzureExample-WebApp-rg -n %appName% ^
    --plan PythonAzureExample-WebApp-plan --runtime "python|3.8"

rem You can use --deployment-source-url with the first create command. It is shown here
rem to match the sequence of the Python code.

az webapp create -n %appName% -g PythonAzureExample-WebApp-rg ^
    --plan PythonAzureExample-WebApp-plan --runtime "python|3.8" ^
    --deployment-source-url %repoUrl% 

rem The previous command sets up External Git deployment from the specified repository. This 
rem command triggers a pull from the repository.

az webapp deployment source sync --name %appName% --resource-group PythonAzureExample-WebApp-rg

関連項目