다음을 통해 공유


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

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

Python용 Azure SDK에는 Azure Portal, Azure CLI 또는 ARM 템플릿으로 azure-mgmt수행할 수 있는 작업과 유사하게 리소스 구성 및 배포를 자동화할 수 있는 관리 라이브러리(네임스페이스부터 시작)가 포함되어 있습니다. 예를 들어 빠른 시작: Azure App Service에 Python(Django 또는 Flask) 웹앱 배포를 참조하세요.

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: 웹앱을 만들고 배포하는 코드 작성

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

프로덕션 스크립트에서 이러한 코드를 사용하려면(예: VM 관리를 자동화하기 위해) Azure 서비스를 사용하여 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

스크립트에서 리소스 그룹 이름(--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

스크립트에서 리소스 그룹 이름(--resource-group 옵션)을 변경하지 않는 한 변경할 필요가 없습니다.

이 예제에서 만든 리소스 그룹이 더 이상 필요하지 않은 경우 az group delete 명령을 실행하여 삭제할 수 있습니다. 리소스 그룹에는 지속적인 요금이 발생하지 않지만 사용하지 않는 리소스를 정리하는 것이 좋습니다. 인수를 --no-wait 사용하여 삭제가 완료되길 기다리지 않고 명령줄에 컨트롤을 즉시 반환합니다.

ResourceManagementClient.resource_groups.begin_delete 메서드를 사용하여 프로그래밍을 통해 리소스 그룹을 삭제할 수도 있습니다.

참고하십시오