예: Azure 라이브러리를 사용하여 웹앱 만들기 및 배포

이 예제에서는 Python 스크립트에서 Azure SDK 관리 라이브러리를 사용하여 웹앱을 만들고 Azure 앱 Service에 배포하는 방법을 보여 줍니다. 앱 코드는 GitHub 리포지토리에서 배포됩니다.

관리 라이브러리(네임스페이스(예azure-mgmt-web: 네임스페이스)azure-mgmt를 사용하여 구성 및 배포 프로그램을 작성하여 Azure Portal, Azure CLI 또는 기타 리소스 관리 도구를 통해 수행할 수 있는 동일한 작업을 수행할 수 있습니다. 예를 들어 빠른 시작: Azure 앱 Service에 Python(Django 또는 Flask) 웹앱 배포를 참조하세요. (동등 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: 웹앱을 만들고 배포하는 코드 작성

다음 코드를 사용하여 provision_deploy_web_app.py라는 Python 파일을 만듭니다. 주석은 코드의 세부 정보를 설명합니다. 스크립트를 실행하기 전에 환경 변수 및 AZURE_SUBSCRIPTION_ID 환경 변수를 정의 REPO_URL 해야 합니다.

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로 직접 수행할 수 있는 작업을 보여 주므로 CLI 기반 인증(사용 AzureCliCredential)을 사용합니다. 두 경우 모두 인증에 동일한 ID를 사용합니다. 환경에 따라 먼저 실행 az login 하여 인증해야 할 수 있습니다.

프로덕션 스크립트에서 이러한 코드를 사용하려면(예: VM 관리를 자동화하기 위해) Azure 서비스를 사용하여 Python 앱을 인증하는 방법에 설명된 대로 서비스 주체 기반 메서드와 함께 사용 DefaultAzureCredential (권장)합니다.

5: 스크립트 실행

python provision_deploy_web_app.py

6: 웹앱 배포 확인

다음 명령을 실행하여 배포된 웹 사이트를 방문합니다.

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

웹앱 이름(--name 옵션) 및 리소스 그룹 이름(--resource-group 옵션)을 스크립트에서 사용한 값으로 바꿉니다. 브라우저에 "Hello, World!"가 표시됩니다.

예상 출력이 표시되지 않으면 몇 분 정도 기다렸다가 다시 시도하세요.

예상 출력이 아직 표시되지 않으면 다음을 수행합니다.

  1. Azure Portal로 이동합니다.
  2. 리소스 그룹을 선택하고 만든 리소스 그룹을 찾습니다.
  3. 포함된 리소스를 보려면 리소스 그룹 이름을 선택합니다. 특히 App Service 계획 및 App Service가 있는지 확인합니다.
  4. App Service를 선택한 다음, 배포 센터를 선택합니다.
  5. 로그 탭을 선택하여 배포 로그를 봅니다.

7: 웹앱 코드 다시 배포(선택 사항)

스크립트는 웹앱을 호스트하는 데 필요한 리소스를 설정하고 수동 통합을 사용하여 배포 원본을 포크로 설정합니다. 수동 통합을 사용하면 구성된 리포지토리 및 분기에서 끌어오도록 웹앱을 트리거해야 합니다.

스크립트는 WebSiteManagementClient.web_apps.sync_repository 메서드를 호출하여 웹앱에서 끌어오기를 트리거합니다. 후속 코드 변경 내용을 리포지토리에 푸시하는 경우 이 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

웹앱 이름(--name 옵션) 및 리소스 그룹 이름(--resource-group 옵션)을 스크립트에서 사용한 값으로 바꿉니다.

Azure Portal에서 코드를 배포하려면 다음을 수행합니다.

  1. Azure Portal로 이동합니다.
  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

참고 항목